repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
STAMP-project/dspot
dspot/src/test/java/eu/stamp_project/dspot/selector/TakeAllSelectorTest.java
1404
package eu.stamp_project.dspot.selector; import org.junit.Test; import spoon.reflect.declaration.CtMethod; import java.util.Collections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; /** * Created by Benjamin DANGLOT * benjamin.danglot@inria.fr * on 08/08/17 */ public class TakeAllSelectorTest extends AbstractSelectorTest { @Override protected TestSelector getTestSelector() { return new TakeAllSelector(this.builder, this.configuration); } @Override protected CtMethod<?> getAmplifiedTest() { return getTest(); } @Override protected String getContentReportFile() { return ""; } @Test public void testSelector() throws Exception { this.testSelectorUnderTest.init(); this.testSelectorUnderTest.selectToKeep( this.testSelectorUnderTest.selectToAmplify( getTestClass(), Collections.singletonList(getTest()) ) ); assertFalse(this.testSelectorUnderTest.getAmplifiedTestCases().isEmpty()); this.testSelectorUnderTest.selectToKeep( this.testSelectorUnderTest.selectToAmplify( getTestClass(), Collections.singletonList(getAmplifiedTest()) ) ); assertFalse(this.testSelectorUnderTest.getAmplifiedTestCases().isEmpty()); this.testSelectorUnderTest.report(); } @Test public void testReportForCollector() { assertEquals("", this.testSelectorUnderTest.report().getReportForCollector()); } }
lgpl-3.0
cismet/cismap-commons
src/test/java/java/de/cismet/commons/cismap/io/converters/ConvertersSuite.java
1215
package java.de.cismet.commons.cismap.io.converters; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * * @author mscholl */ @RunWith(Suite.class) @Suite.SuiteClasses( { de.cismet.commons.cismap.io.converters.AbstractGeometryFromTextConverterTest.class, de.cismet.commons.cismap.io.converters.PolygonFromTextConverterTest.class, de.cismet.commons.cismap.io.converters.PointFromTextConverterTest.class, de.cismet.commons.cismap.io.converters.BoundingBoxFromTextConverterTest.class, de.cismet.commons.cismap.io.converters.PolylineFromTextConverterTest.class, de.cismet.commons.cismap.io.converters.GeomFromWkbAsHexTextConverterTest.class, de.cismet.commons.cismap.io.converters.GeomFromWktConverterTest.class }) public class ConvertersSuite { @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } }
lgpl-3.0
kiyosue/ECbaser
html/basercms/lib/Baser/View/Elements/admin/header.php
2444
<?php /** * [ADMIN] ヘッダー * * baserCMS : Based Website Development Project <http://basercms.net> * Copyright 2008 - 2015, baserCMS Users Community <http://sites.google.com/site/baserusers/> * * @copyright Copyright 2008 - 2015, baserCMS Users Community * @link http://basercms.net baserCMS Project * @package Baser.View * @since baserCMS v 2.0.0 * @license http://basercms.net/license/index.html */ if (!empty($this->request->params['prefix'])) { $loginUrl = $this->request->params['prefix'] . '/users/login'; } else { $loginUrl = '/users/login'; } ?> <div id="Header" class="clearfix"> <?php $this->BcBaser->element('toolbar') ?> <?php if ($this->name == 'Installations' || ('/' . $this->request->url == Configure::read('BcAuthPrefix.admin.loginAction')) || (@$this->request->params['prefix'] == 'admin' && $this->BcAdmin->isAdminGlobalmenuUsed())): ?> <div class="clearfix" id="HeaderInner"> <?php if ($this->name != 'Installations' && ('/' . $this->request->url != Configure::read('BcAuthPrefix.admin.loginAction'))): ?> <div id="GlobalMenu"> <ul class="clearfix"> <li id="GlobalMenu1"><?php $this->BcBaser->link('固定ページ管理', array('plugin' => '', 'controller' => 'pages', 'action' => 'index')) ?></li> <li id="GlobalMenu2"><?php $this->BcBaser->link('ウィジェット管理', array('plugin' => '', 'controller' => 'widget_areas', 'action' => 'index')) ?></li> <li id="GlobalMenu3"><?php $this->BcBaser->link('テーマ管理', array('plugin' => '', 'controller' => 'themes', 'action' => 'index')) ?></li> <li id="GlobalMenu4"><?php $this->BcBaser->link('プラグイン管理', array('plugin' => '', 'controller' => 'plugins', 'action' => 'index')) ?></li> <li id="GlobalMenu5"><?php $this->BcBaser->link('システム管理', array('plugin' => '', 'controller' => 'site_configs', 'action' => 'form')) ?></li> </ul> </div> <?php endif ?> <div id="Logo"> <?php if (!empty($user)): ?> <?php $this->BcBaser->link($this->BcBaser->getImg('admin/logo_header.png', array('width' => 153, 'height' => 30, 'alt' => 'baserCMS')), array('plugin' => null, 'controller' => 'dashboard', 'action' => 'index')) ?> <?php else: ?> <?php $this->BcBaser->img('admin/logo_header.png', array('width' => 153, 'height' => 30, 'alt' => 'baserCMS')) ?> <?php endif ?> </div> </div> <?php endif ?> <!-- / #Header .clearfix --></div>
lgpl-3.0
jefersondaniel/novoboletophp
src/NovoBoletoPHP/Base/Boleto.php
4827
<?php namespace NovoBoletoPHP\Base; abstract class Boleto { protected $twig; public $data; public function __construct($twig, array $data) { $this->twig = $twig; $this->data = $this->filterData($data); $this->configure(); } protected function configure() { } protected function filterData(array $data) { $codigoBanco = $this->getCodigoBancoComDv(); $data = array_merge($data, array( 'logo_banco' => $this->getLogoBanco(), 'codigo_banco_com_dv' => $this->getCodigoBancoComDv(), 'texto_sacado' => 'Pagador', 'texto_cedente' => 'Beneficiário', 'exibir_demonstrativo_na_ficha' => true, 'exibir_demonstrativo_no_recibo' => false, )); return $data; } abstract public function getTemplate(); abstract public function getLogoBanco(); abstract public function getCodigoBanco(); public function getCodigoBancoFormatado() { return sprintf('%03d', $this->getCodigoBanco()); } protected function getCodigoBancoComDv() { $numero = $this->getCodigoBancoFormatado(); $parte1 = substr($numero, 0, 3); $parte2 = $this->modulo11($parte1); return $parte1 . "-" . $parte2; } public function asHTML() { return $this->twig->render($this->getTemplate(), $this->data); } public function fatorVencimento($data) { $data = explode("/", $data); $ano = $data[2]; $mes = $data[1]; $dia = $data[0]; return(abs(($this->dateToDays("1997","10","07")) - ($this->dateToDays($ano, $mes, $dia)))); } protected function dateToDays($year,$month,$day) { $century = substr($year, 0, 2); $year = substr($year, 2, 2); if ($month > 2) { $month -= 3; } else { $month += 9; if ($year) { $year--; } else { $year = 99; $century --; } } return ( floor(( 146097 * $century) / 4 ) + floor(( 1461 * $year) / 4 ) + floor(( 153 * $month + 2) / 5 ) + $day + 1721119); } public function modulo10($num) { $numtotal10 = 0; $fator = 2; for ($i = strlen($num); $i > 0; $i--) { $numeros[$i] = substr($num,$i-1,1); $parcial10[$i] = $numeros[$i] * $fator; $numtotal10 .= $parcial10[$i]; if ($fator == 2) { $fator = 1; } else { $fator = 2; } } $soma = 0; for ($i = strlen($numtotal10); $i > 0; $i--) { $numeros[$i] = substr($numtotal10,$i-1,1); $soma += $numeros[$i]; } $resto = $soma % 10; $digito = 10 - $resto; if ($resto == 0) { $digito = 0; } return $digito; } /** * Autor: * Pablo Costa <pablo@users.sourceforge.net> * * Função: * Calculo do Modulo 11 para geracao do digito verificador * de boletos bancarios conforme documentos obtidos * da Febraban - www.febraban.org.br * * Entrada: * $num: string numérica para a qual se deseja calcularo digito verificador; * $base: valor maximo de multiplicacao [2-$base] * $r: quando especificado um devolve somente o resto * * Saída: * Retorna o Digito verificador. * * Observações: * - Script desenvolvido sem nenhum reaproveitamento de código pré existente. * - Assume-se que a verificação do formato das variáveis de entrada é feita antes da execução deste script. */ public function modulo11($num, $base = 9, $r = 0) { $soma = 0; $fator = 2; /* Separacao dos numeros */ for ($i = strlen($num); $i > 0; $i--) { // pega cada numero isoladamente $numeros[$i] = substr($num, $i-1, 1); // Efetua multiplicacao do numero pelo falor $parcial[$i] = $numeros[$i] * $fator; // Soma dos digitos $soma += $parcial[$i]; if ($fator == $base) { // restaura fator de multiplicacao para 2 $fator = 1; } $fator++; } /* Calculo do modulo 11 */ if ($r == 0) { $soma *= 10; $digito = $soma % 11; if ($digito == 10) { $digito = 0; } return $digito; } elseif ($r == 1) { $resto = $soma % 11; return $resto; } } }
lgpl-3.0
hutch/xamplr
lib/xamplr/test-support/test-indexed-array.rb
3062
#!/usr/bin/env ruby require "test/unit" #require "rubygems" #require_gem "arrayfields" #require "arrayfields-local" require "indexed-array" class TestXampl < Test::Unit::TestCase def xtest_dummy_fieldarray ia = [] ia.fields = [] ia << 0 << 1 << 2 ia["three"] = 3 ia["four"] = 4 ia["five"] = 5 assert_equal(0, ia[0]) assert_equal(1, ia[1]) assert_equal(2, ia[2]) assert_equal(3, ia[3]) assert_equal(4, ia[4]) assert_equal(5, ia[5]) assert_equal(3, ia["three"]) assert_equal(4, ia["four"]) assert_equal(5, ia["five"]) ia["four"] = 44 assert_equal(44, ia["four"]) assert_equal(44, ia[4]) end def test_remove ia = IndexedArray.new ia["one"] = 1 ia["two"] = 2 ia["three"] = 3 assert_equal(1, ia["one"]) assert_equal(2, ia["two"]) assert_equal(3, ia["three"]) ia.delete_at("one") assert_equal(2, ia["two"]) assert_equal(3, ia["three"]) assert_equal(2, ia.size) assert_equal(2, ia[0]) assert_equal(3, ia[1]) end def xtest_remove_fieldarray ia = [] ia.fields = [] ia["one"] = 1 ia["two"] = 2 ia["three"] = 3 assert_equal(1, ia["one"]) assert_equal(2, ia["two"]) assert_equal(3, ia["three"]) ia.delete_at("one") assert_equal(2, ia["two"]) assert_equal(3, ia["three"]) assert_equal(2, ia.size) assert_equal(2, ia[0]) assert_equal(3, ia[1]) end def test_two a = IndexedArray.new b = IndexedArray.new a["one"] = 1 a["two"] = 2 a["three"] = 3 # a.each_pair { | k, v | # puts "a:: k: #{k}, v: #{v}" # } # a.dump("a") # b.each_pair { | k, v | # puts "b:: k: #{k}, v: #{v}" # } # b.dump("b") b["three"] = 300 b["two"] = 200 b["one"] = 100 assert_equal(1, a["one"]) assert_equal(2, a["two"]) assert_equal(3, a["three"]) assert_equal(1, a[0]) assert_equal(2, a[1]) assert_equal(3, a[2]) assert_equal(300, b["three"]) assert_equal(200, b["two"]) assert_equal(100, b["one"]) assert_equal(300, b[0]) ### returns 100 here assert_equal(200, b[1]) assert_equal(100, b[2]) # a.dump("a") # b.dump("b") end def xtest_two_fieldarray a = [] a.fields = [] b = [] b.fields = [] a["one"] = 1 a["two"] = 2 a["three"] = 3 # a.each_pair { | k, v | # puts "a:: k: #{k}, v: #{v}" # } # a.dump("a") # b.each_pair { | k, v | # puts "b:: k: #{k}, v: #{v}" # } # b.dump("b") b["three"] = 300 b["two"] = 200 b["one"] = 100 assert_equal(1, a["one"]) assert_equal(2, a["two"]) assert_equal(3, a["three"]) assert_equal(1, a[0]) assert_equal(2, a[1]) assert_equal(3, a[2]) assert_equal(300, b["three"]) assert_equal(200, b["two"]) assert_equal(100, b["one"]) assert_equal(300, b[0]) ### returns 100 here assert_equal(200, b[1]) assert_equal(100, b[2]) # a.dump("a") # b.dump("b") end end
lgpl-3.0
ABBAPOH/libs
src/io/inqt5/qmimetype.cpp
14583
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtCore 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 "qmimetype.h" #include "qmimetype_p.h" #include "qmimedatabase_p.h" #include "qmimeprovider_p.h" #include "qmimeglobpattern_p.h" #include <QtCore/QDebug> #include <QtCore/QLocale> #include <memory> QT_BEGIN_NAMESPACE QMimeTypePrivate::QMimeTypePrivate() : loaded(false) {} QMimeTypePrivate::QMimeTypePrivate(const QMimeType &other) : name(other.d->name), localeComments(other.d->localeComments), genericIconName(other.d->genericIconName), iconName(other.d->iconName), globPatterns(other.d->globPatterns), loaded(other.d->loaded) {} void QMimeTypePrivate::clear() { name.clear(); localeComments.clear(); genericIconName.clear(); iconName.clear(); globPatterns.clear(); loaded = false; } void QMimeTypePrivate::addGlobPattern(const QString &pattern) { globPatterns.append(pattern); } /*! \class QMimeType \inmodule QtCore \ingroup shared \brief The QMimeType class describes types of file or data, represented by a MIME type string. \since 5.0 For instance a file named "readme.txt" has the MIME type "text/plain". The MIME type can be determined from the file name, or from the file contents, or from both. MIME type determination can also be done on buffers of data not coming from files. Determining the MIME type of a file can be useful to make sure your application supports it. It is also useful in file-manager-like applications or widgets, in order to display an appropriate icon() for the file, or even the descriptive comment() in detailed views. To check if a file has the expected MIME type, you should use inherits() rather than a simple string comparison based on the name(). This is because MIME types can inherit from each other: for instance a C source file is a specific type of plain text file, so text/x-csrc inherits text/plain. \sa QMimeDatabase */ /*! \fn QMimeType::QMimeType(); Constructs this QMimeType object initialized with default property values that indicate an invalid MIME type. */ QMimeType::QMimeType() : d(new QMimeTypePrivate()) { } /*! \fn QMimeType::QMimeType(const QMimeType &other); Constructs this QMimeType object as a copy of \a other. */ QMimeType::QMimeType(const QMimeType &other) : d(other.d) { } /*! \fn QMimeType &QMimeType::operator=(const QMimeType &other); Assigns the data of \a other to this QMimeType object, and returns a reference to this object. */ QMimeType &QMimeType::operator=(const QMimeType &other) { if (d != other.d) d = other.d; return *this; } /*! \fn QMimeType::QMimeType(const QMimeTypePrivate &dd); Assigns the data of the QMimeTypePrivate \a dd to this QMimeType object, and returns a reference to this object. \internal */ QMimeType::QMimeType(const QMimeTypePrivate &dd) : d(new QMimeTypePrivate(dd)) { } /*! \fn void QMimeType::swap(QMimeType &other); Swaps QMimeType \a other with this QMimeType object. This operation is very fast and never fails. The swap() method helps with the implementation of assignment operators in an exception-safe way. For more information consult \l {http://en.wikibooks.org/wiki/More_C++_Idioms/Copy-and-swap} {More C++ Idioms - Copy-and-swap}. */ /*! \fn QMimeType::~QMimeType(); Destroys the QMimeType object, and releases the d pointer. */ QMimeType::~QMimeType() { } /*! \fn bool QMimeType::operator==(const QMimeType &other) const; Returns true if \a other equals this QMimeType object, otherwise returns false. The name is the unique identifier for a mimetype, so two mimetypes with the same name, are equal. */ bool QMimeType::operator==(const QMimeType &other) const { return d == other.d || d->name == other.d->name; } /*! \fn bool QMimeType::operator!=(const QMimeType &other) const; Returns true if \a other does not equal this QMimeType object, otherwise returns false. */ /*! \fn bool QMimeType::isValid() const; Returns true if the QMimeType object contains valid data, otherwise returns false. A valid MIME type has a non-empty name(). The invalid MIME type is the default-constructed QMimeType. */ bool QMimeType::isValid() const { return !d->name.isEmpty(); } /*! \fn bool QMimeType::isDefault() const; Returns true if this MIME type is the default MIME type which applies to all files: application/octet-stream. */ bool QMimeType::isDefault() const { return d->name == QMimeDatabasePrivate::instance()->defaultMimeType(); } /*! \fn QString QMimeType::name() const; Returns the name of the MIME type. */ QString QMimeType::name() const { return d->name; } /*! Returns the description of the MIME type to be displayed on user interfaces. The system language (QLocale::system().name()) is used to select the appropriate translation. */ QString QMimeType::comment() const { QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d); QStringList languageList; languageList << QLocale::system().name(); languageList << QLocale::system().uiLanguages(); Q_FOREACH (const QString &language, languageList) { const QString lang = language == QLatin1String("C") ? QLatin1String("en_US") : language; const QString comm = d->localeComments.value(lang); if (!comm.isEmpty()) return comm; const int pos = lang.indexOf(QLatin1Char('_')); if (pos != -1) { // "pt_BR" not found? try just "pt" const QString shortLang = lang.left(pos); const QString commShort = d->localeComments.value(shortLang); if (!commShort.isEmpty()) return commShort; } } // Use the mimetype name as fallback return d->name; } /*! \fn QString QMimeType::genericIconName() const; Returns the file name of a generic icon that represents the MIME type. This should be used if the icon returned by iconName() cannot be found on the system. It is used for categories of similar types (like spreadsheets or archives) that can use a common icon. The freedesktop.org Icon Naming Specification lists a set of such icon names. The icon name can be given to QIcon::fromTheme() in order to load the icon. */ QString QMimeType::genericIconName() const { QMimeDatabasePrivate::instance()->provider()->loadGenericIcon(*d); if (d->genericIconName.isEmpty()) { // From the spec: // If the generic icon name is empty (not specified by the mimetype definition) // then the mimetype is used to generate the generic icon by using the top-level // media type (e.g. "video" in "video/ogg") and appending "-x-generic" // (i.e. "video-x-generic" in the previous example). QString group = name(); const int slashindex = group.indexOf(QLatin1Char('/')); if (slashindex != -1) group = group.left(slashindex); return group + QLatin1String("-x-generic"); } return d->genericIconName; } /*! \fn QString QMimeType::iconName() const; Returns the file name of an icon image that represents the MIME type. The icon name can be given to QIcon::fromTheme() in order to load the icon. */ QString QMimeType::iconName() const { QMimeDatabasePrivate::instance()->provider()->loadIcon(*d); if (d->iconName.isEmpty()) { // Make default icon name from the mimetype name d->iconName = name(); const int slashindex = d->iconName.indexOf(QLatin1Char('/')); if (slashindex != -1) d->iconName[slashindex] = QLatin1Char('-'); } return d->iconName; } /*! \fn QStringList QMimeType::globPatterns() const; Returns the list of glob matching patterns. */ QStringList QMimeType::globPatterns() const { QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d); return d->globPatterns; } /*! A type is a subclass of another type if any instance of the first type is also an instance of the second. For example, all image/svg+xml files are also text/xml, text/plain and application/octet-stream files. Subclassing is about the format, rather than the category of the data (for example, there is no 'generic spreadsheet' class that all spreadsheets inherit from). Conversely, the parent mimetype of image/svg+xml is text/xml. A mimetype can have multiple parents. For instance application/x-perl has two parents: application/x-executable and text/plain. This makes it possible to both execute perl scripts, and to open them in text editors. */ QStringList QMimeType::parentMimeTypes() const { return QMimeDatabasePrivate::instance()->provider()->parents(d->name); } static void collectParentMimeTypes(const QString &mime, QStringList &allParents) { QStringList parents = QMimeDatabasePrivate::instance()->provider()->parents(mime); foreach (const QString &parent, parents) { // I would use QSet, but since order matters I better not if (!allParents.contains(parent)) allParents.append(parent); } // We want a breadth-first search, so that the least-specific parent (octet-stream) is last // This means iterating twice, unfortunately. foreach (const QString &parent, parents) { collectParentMimeTypes(parent, allParents); } } /*! Return all the parent mimetypes of this mimetype, direct and indirect. This includes the parent(s) of its parent(s), etc. For instance, for image/svg+xml the list would be: application/xml, text/plain, application/octet-stream. Note that application/octet-stream is the ultimate parent for all types of files (but not directories). */ QStringList QMimeType::allAncestors() const { QStringList allParents; collectParentMimeTypes(d->name, allParents); return allParents; } /*! Return the list of aliases of this mimetype. For instance, for text/csv, the returned list would be: text/x-csv, text/x-comma-separated-values. Note that all QMimeType instances refer to proper mimetypes, never to aliases directly. The order of the aliases in the list is undefined. */ QStringList QMimeType::aliases() const { return QMimeDatabasePrivate::instance()->provider()->listAliases(d->name); } /*! Returns the known suffixes for the MIME type. No leading dot is included, so for instance this would return "jpg", "jpeg" for image/jpeg. */ QStringList QMimeType::suffixes() const { QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d); QStringList result; foreach (const QString &pattern, d->globPatterns) { // Not a simple suffix if it looks like: README or *. or *.* or *.JP*G or *.JP? if (pattern.startsWith(QLatin1String("*.")) && pattern.length() > 2 && pattern.indexOf(QLatin1Char('*'), 2) < 0 && pattern.indexOf(QLatin1Char('?'), 2) < 0) { const QString suffix = pattern.mid(2); result.append(suffix); } } return result; } /*! Returns the preferred suffix for the MIME type. No leading dot is included, so for instance this would return "pdf" for application/pdf. The return value can be empty, for mime types which do not have any suffixes associated. */ QString QMimeType::preferredSuffix() const { const QStringList suffixList = suffixes(); return suffixList.isEmpty() ? QString() : suffixList.at(0); } /*! \fn QString QMimeType::filterString() const; Returns a filter string usable for a file dialog. */ QString QMimeType::filterString() const { QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d); QString filter; if (!d->globPatterns.empty()) { filter += comment() + QLatin1String(" ("); for (int i = 0; i < d->globPatterns.size(); ++i) { if (i != 0) filter += QLatin1Char(' '); filter += d->globPatterns.at(i); } filter += QLatin1Char(')'); } return filter; } /*! \fn bool QMimeType::inherits(const QString &mimeTypeName) const; Returns true if this mimetype is \a mimeTypeName, or inherits \a mimeTypeName (see parentMimeTypes()), or \a mimeTypeName is an alias for this mimetype. */ bool QMimeType::inherits(const QString &mimeTypeName) const { if (d->name == mimeTypeName) return true; return QMimeDatabasePrivate::instance()->inherits(d->name, mimeTypeName); } QT_END_NAMESPACE
lgpl-3.0
openlecturnity/os45
lecturnity/common/avedit/skewclock.cpp
2645
#include "StdAfx.h" #include "skewclock.h" CSkewReferenceClock::CSkewReferenceClock(IReferenceClock *pRC, REFERENCE_TIME rtOffset) { #ifdef _DEBUGFILE DebugMsg("CSkewReferenceClock()\n"); #endif m_pRC = pRC; if (m_pRC) m_pRC->AddRef(); m_rtOffset = rtOffset; m_nRefCounter = 0; m_rtSkew = 0; m_rtLastReturned = 0; } CSkewReferenceClock::~CSkewReferenceClock() { if (m_pRC) m_pRC->Release(); m_pRC = NULL; } HRESULT CSkewReferenceClock::GetTime(REFERENCE_TIME *pTime) { HRESULT hr = E_NOTIMPL; if (m_pRC) hr = m_pRC->GetTime(pTime); if (SUCCEEDED(hr)) { *pTime -= (m_rtOffset + m_rtSkew); if (*pTime < m_rtLastReturned) *pTime = m_rtLastReturned; } return hr; } HRESULT CSkewReferenceClock::AdviseTime(REFERENCE_TIME rtBaseTime, REFERENCE_TIME rtStreamTime, HEVENT hEvent, DWORD_PTR *pdwAdviseCookie) { if (m_pRC) return m_pRC->AdviseTime(rtBaseTime + m_rtOffset + m_rtSkew, rtStreamTime, hEvent, pdwAdviseCookie); else return E_NOTIMPL; } HRESULT CSkewReferenceClock::AdvisePeriodic(REFERENCE_TIME rtStartTime, REFERENCE_TIME rtPeriodic, HSEMAPHORE hSemaphore, DWORD_PTR *pdwAdviseCookie) { if (m_pRC) return m_pRC->AdvisePeriodic(rtStartTime + m_rtOffset + m_rtSkew, rtPeriodic, hSemaphore, pdwAdviseCookie); else return E_NOTIMPL; } HRESULT CSkewReferenceClock::Unadvise(DWORD_PTR dwAdviseCookie) { if (m_pRC) return m_pRC->Unadvise(dwAdviseCookie); else return E_NOTIMPL; } ULONG CSkewReferenceClock::AddRef() { m_nRefCounter += 1; return m_nRefCounter; } ULONG CSkewReferenceClock::Release() { // Achtung: Hier wird eine temporäre Variable // angelegt, damit (im Falle, dass das Objekt // zerstört wird) nicht eine Zugriffsverletzung // beim Zugriff auf die (Member-)Variable // m_nRefCounter auftritt: ULONG tempRefC = --m_nRefCounter; if (m_nRefCounter <= 0) delete this; // Die temporäre Variable zurückgeben! return tempRefC; } HRESULT CSkewReferenceClock::QueryInterface(REFIID refIid, LPVOID *pDest) { HRESULT hr = S_OK; if (refIid == IID_IUnknown) { *pDest = (IUnknown *) this; } else if (refIid == IID_IReferenceClock) { *pDest = (IReferenceClock *) this; } else hr = E_NOINTERFACE; if (SUCCEEDED(hr)) AddRef(); return hr; }
lgpl-3.0
ulbpodcast/ezcast
commons/traces_analyzing/modules/Infos_per_month_module.php
8732
<?php /** * === View === * A user have "view" a video if he have watch minimum 1 minute. * * === Total === * We use "session" to count total view. So if a user watch a video * go to menu and watch agin this video, there will be only one view. * * === Unique === * A user can only have (maximum) one view per video (per month). * If a user watch a video, and the next day watch the same video * (if it's the same month), there will be only one view. * ANONYM * For anonym user, we use "session". * */ class Infos_per_month extends Module { private static $VIEW_MIN_TIME = 60; private $sql_data = array(); private $saved_view_data = array(); private $month; private $cache_asset_name = array(); public function analyse_line($date, $timestamp, $session, $ip, $netid, $level, $action, $other_info = null) { $this->month = date('m-Y', $timestamp); if ($action == "video_play_time") { // other_info: current_album, current_asset, current_asset_name, type, last_play_start, play_time $album = trim($other_info[0]); $asset = trim($other_info[1]); $asset_name = trim($other_info[2]); $type = trim($other_info[3]); $start = trim($other_info[4]); $play_time = trim($other_info[5]); if (!array_key_exists($album, $this->saved_view_data)) { $this->saved_view_data[$album] = array(); $this->cache_asset_name[$album] = array(); } $this->cache_asset_name[$album][$asset] = $asset_name; if (!array_key_exists($asset, $this->saved_view_data[$album])) { $this->saved_view_data[$album][$asset] = array( 'total' => array(), 'unique' => array(), 'unique_session' => array() ); } $key_unique_netid = 'unique'; if ($netid == 'nologin') { $netid = $session; $key_unique_netid = 'unique_session'; } if (!array_key_exists($netid, $this->saved_view_data[$album][$asset][$key_unique_netid])) { $this->saved_view_data[$album][$asset][$key_unique_netid][$netid] = $play_time; } elseif ($this->saved_view_data[$album][$asset][$key_unique_netid][$netid] < self::$VIEW_MIN_TIME) { $this->saved_view_data[$album][$asset][$key_unique_netid][$netid] += $play_time; } if (!array_key_exists($session, $this->saved_view_data[$album][$asset]['total'])) { $this->saved_view_data[$album][$asset]['total'][$session] = $play_time; } elseif ($this->saved_view_data[$album][$asset]['total'][$session] < self::$VIEW_MIN_TIME) { $this->saved_view_data[$album][$asset]['total'][$session] += $play_time; } } } public function end_file() { foreach ($this->saved_view_data as $album => $album_data) { foreach ($album_data as $asset => $asset_data) { $this->add_album_asset_sql_data($album, $asset); if (!array_key_exists('nbr_view_unique', $this->sql_data[$album][$asset])) { $this->sql_data[$album][$asset]['nbr_view_unique'] = 0; $this->sql_data[$album][$asset]['nbr_view_total'] = 0; } foreach ($asset_data['total'] as $session => $value) { if ($value >= self::$VIEW_MIN_TIME) { $this->sql_data[$album][$asset]['nbr_view_total']++; } } $user_file = $this->get_user_view_file($album, $asset); foreach ($asset_data['unique'] as $netid => $value) { if ($value >= self::$VIEW_MIN_TIME && !in_array($netid, $user_file)) { $this->sql_data[$album][$asset]['nbr_view_unique']++; $this->add_user_view_file($album, $asset, $netid); } } foreach ($asset_data['unique_session'] as $netid => $value) { if ($value >= self::$VIEW_MIN_TIME) { $this->sql_data[$album][$asset]['nbr_view_unique']++; } } } } // SAVE_TO_SQL foreach ($this->sql_data as $album => $album_data) { foreach ($album_data as $asset => $asset_data) { $nbr_view_total = 0; $nbr_view_unique = 0; if (array_key_exists('nbr_view_total', $asset_data)) { $nbr_view_total = $asset_data['nbr_view_total']; $nbr_view_unique = $asset_data['nbr_view_unique']; } if ($nbr_view_total > 0 || $nbr_view_unique > 0) { $asset_name = ""; if (isset($this->cache_asset_name[$album][$asset])) { $asset_name = $this->cache_asset_name[$album][$asset]; } $this->save_to_sql($album, $asset, $asset_name, $nbr_view_total, $nbr_view_unique); } } } // Reset saved_view_data $this->cache_asset_name = array(); $this->saved_view_data = array(); } public function save_to_sql($album, $asset, $asset_name, $nbr_view_total, $nbr_view_unique) { $this->logger->debug('[infos_per_month] save sql: album: ' . $album . ' | asset: ' . $asset . ' | asset_name: ' . $asset_name . ' | nbr_view_total: ' . $nbr_view_total . ' | nbr_view_unique: ' . $nbr_view_unique . ' | month: ' . $this->month); $db = $this->database->get_database_object(); $query = $db->prepare('INSERT INTO ' . $this->database->get_table('stats_video_month_infos') . ' ' . '(visibility, asset, asset_name, album, nbr_view_total, nbr_view_unique, month) ' . 'VALUES(:visibility, :asset, :asset_name, :album, :nbr_view_total, :nbr_view_unique, :month) '. 'ON DUPLICATE KEY UPDATE ' . 'nbr_view_total = nbr_view_total + :nbr_view_total, ' . 'nbr_view_unique = nbr_view_unique + :nbr_view_unique;'); $query->execute(array( ':visibility' => 1, ':asset' => $asset, ':asset_name' => $asset_name, ':album' => $album, ':nbr_view_total' => $nbr_view_total, ':nbr_view_unique' => $nbr_view_unique, ':month' => $this->month )); $query->execute(array( ':visibility' => 0, ':asset' => $asset, ':asset_name' => $asset_name, ':album' => $album, ':nbr_view_total' => $nbr_view_total, ':nbr_view_unique' => $nbr_view_unique, ':month' => $this->month )); } private function add_album_asset_sql_data($album, $asset) { if (!array_key_exists($album, $this->sql_data)) { $this->sql_data[$album] = array($asset => array()); } if (!array_key_exists($asset, $this->sql_data[$album])) { $this->sql_data[$album][$asset] = array(); } } private function get_user_view_file($album, $asset) { $path_file = $path_file = $this->get_user_view_file_path($album, $asset); if (file_exists($path_file)) { return explode("\n", file_get_contents($path_file)); } return array(); } private function add_user_view_file($album, $asset, $netid) { $path_file = $this->get_user_view_file_path($album, $asset); if (file_exists($path_file)) { $data = "\n" . $netid; } else { $data = $netid; } $dir_path = dirname($path_file); if (!file_exists($path_file)) { $allPath = array(); $currentPath = $dir_path; while ($currentPath != "/") { $currentPath = dirname($currentPath); $allPath[] = $currentPath; } $allPath = array_reverse($allPath); foreach ($allPath as $interPath) { if (!is_dir($interPath)) { mkdir($interPath, 0777, true); } } } file_put_contents($path_file, $data, FILE_APPEND); } private function get_user_view_file_path($album, $asset) { return $this->repos_folder . '/' . $album . '/' . $asset . '/' . 'user_view.txt'; } }
lgpl-3.0
pcolby/libqtaws
src/iotsitewise/updateassetmodelresponse.cpp
3446
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "updateassetmodelresponse.h" #include "updateassetmodelresponse_p.h" #include <QDebug> #include <QNetworkReply> #include <QXmlStreamReader> namespace QtAws { namespace IoTSiteWise { /*! * \class QtAws::IoTSiteWise::UpdateAssetModelResponse * \brief The UpdateAssetModelResponse class provides an interace for IoTSiteWise UpdateAssetModel responses. * * \inmodule QtAwsIoTSiteWise * * Welcome to the AWS IoT SiteWise API Reference. AWS IoT SiteWise is an AWS service that connects <a * href="https://en.wikipedia.org/wiki/Internet_of_things#Industrial_applications">Industrial Internet of Things (IIoT)</a> * devices to the power of the AWS Cloud. For more information, see the <a * href="https://docs.aws.amazon.com/iot-sitewise/latest/userguide/">AWS IoT SiteWise User Guide</a>. For information about * AWS IoT SiteWise quotas, see <a href="https://docs.aws.amazon.com/iot-sitewise/latest/userguide/quotas.html">Quotas</a> * in the <i>AWS IoT SiteWise User * * \sa IoTSiteWiseClient::updateAssetModel */ /*! * Constructs a UpdateAssetModelResponse object for \a reply to \a request, with parent \a parent. */ UpdateAssetModelResponse::UpdateAssetModelResponse( const UpdateAssetModelRequest &request, QNetworkReply * const reply, QObject * const parent) : IoTSiteWiseResponse(new UpdateAssetModelResponsePrivate(this), parent) { setRequest(new UpdateAssetModelRequest(request)); setReply(reply); } /*! * \reimp */ const UpdateAssetModelRequest * UpdateAssetModelResponse::request() const { Q_D(const UpdateAssetModelResponse); return static_cast<const UpdateAssetModelRequest *>(d->request); } /*! * \reimp * Parses a successful IoTSiteWise UpdateAssetModel \a response. */ void UpdateAssetModelResponse::parseSuccess(QIODevice &response) { //Q_D(UpdateAssetModelResponse); QXmlStreamReader xml(&response); /// @todo } /*! * \class QtAws::IoTSiteWise::UpdateAssetModelResponsePrivate * \brief The UpdateAssetModelResponsePrivate class provides private implementation for UpdateAssetModelResponse. * \internal * * \inmodule QtAwsIoTSiteWise */ /*! * Constructs a UpdateAssetModelResponsePrivate object with public implementation \a q. */ UpdateAssetModelResponsePrivate::UpdateAssetModelResponsePrivate( UpdateAssetModelResponse * const q) : IoTSiteWiseResponsePrivate(q) { } /*! * Parses a IoTSiteWise UpdateAssetModel response element from \a xml. */ void UpdateAssetModelResponsePrivate::parseUpdateAssetModelResponse(QXmlStreamReader &xml) { Q_ASSERT(xml.name() == QLatin1String("UpdateAssetModelResponse")); Q_UNUSED(xml) ///< @todo } } // namespace IoTSiteWise } // namespace QtAws
lgpl-3.0
ClearSkyTeam/ClearSky
src/pocketmine/event/player/PlayerCreationEvent.php
2420
<?php namespace pocketmine\event\player; use pocketmine\event\Event; use pocketmine\network\SourceInterface; use pocketmine\Player; /** * Allows the creation of players overriding the base Player class */ class PlayerCreationEvent extends Event{ public static $handlerList = null; /** @var SourceInterface */ private $interface; /** @var mixed */ private $clientId; /** @var string */ private $address; /** @var int */ private $port; /** @var Player::class */ private $baseClass; /** @var Player::class */ private $playerClass; /** * @param SourceInterface $interface * @param Player::class $baseClass * @param Player::class $playerClass * @param mixed $clientId * @param string $address * @param int $port */ public function __construct(SourceInterface $interface, $baseClass, $playerClass, $clientId, $address, $port){ $this->interface = $interface; $this->clientId = $clientId; $this->address = $address; $this->port = $port; if(!is_a($baseClass, Player::class, true)){ throw new \RuntimeException("Base class $baseClass must extend " . Player::class); } $this->baseClass = $baseClass; if(!is_a($playerClass, Player::class, true)){ throw new \RuntimeException("Class $playerClass must extend " . Player::class); } $this->playerClass = $playerClass; } /** * @return SourceInterface */ public function getInterface(){ return $this->interface; } /** * @return string */ public function getAddress(){ return $this->address; } /** * @return int */ public function getPort(){ return $this->port; } /** * @return mixed */ public function getClientId(){ return $this->clientId; } /** * @return Player::class */ public function getBaseClass(){ return $this->baseClass; } /** * @param Player::class $class */ public function setBaseClass($class){ if(!is_a($class, $this->baseClass, true)){ throw new \RuntimeException("Base class $class must extend " . $this->baseClass); } $this->baseClass = $class; } /** * @return Player::class */ public function getPlayerClass(){ return $this->playerClass; } /** * @param Player::class $class */ public function setPlayerClass($class){ if(!is_a($class, $this->baseClass, true)){ throw new \RuntimeException("Class $class must extend " . $this->baseClass); } $this->playerClass = $class; } }
lgpl-3.0
newrealmcoder/New-Realm-Minecraft
src/main/java/com/realmcoder/newrealmminecraft/proxy/ServerProxy.java
145
package com.realmcoder.newrealmminecraft.proxy; /** * Created by RealmCoder on 8/5/14. */ public class ServerProxy extends CommonProxy { }
lgpl-3.0
JackTheBones/Ride
core/src/com/infiniteloop/ride/Kamikaze.java
3761
package com.infiniteloop.ride; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.Align; /** * Created by jackthebones on 18/06/15. */ public class Kamikaze extends Actor{ public static final int KamikazeWidth = 32; public static final int KamikazeHeight = 32; //Velocidad y aceleracion posiciones X y Y private Vector2 Velocity; private TextureRegion textureRegion; public static int KamikazeLifePoints = MathUtils.random(1, 2); public int KAMIKAZEAMOUNT; //Estado del personaje public State state; //Posibles estados de personaje durante el juego public enum State {alive, dead} private Rectangle KamikazePerimeter; public Kamikaze(int KamikazeAmount) { KAMIKAZEAMOUNT = KamikazeAmount; textureRegion = new TextureRegion(Assets.kamikaze); setWidth(KamikazeWidth); setHeight(KamikazeHeight); //Inicializa el personaje como "alive" state = State.alive; //Variables de movimiento del personaje //Velocidad del personaje Velocity = new Vector2(0, -45f); //Peso o gravedad del personaje KamikazePerimeter = new Rectangle(0, 0, KamikazeWidth, KamikazeHeight); //Centro de rotacion del pj setOrigin(Align.center); } @Override public void draw(Batch batch, float parentAlpha) { batch.draw(textureRegion, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation()); } @Override public void act(float delta) { super.act(delta); switch (state){ case alive: ActAlive(delta); break; case dead: DeadRise(); break; } UpdatePerimeter(); } public void DeadRise(){ if (KAMIKAZEAMOUNT != 0){ KamikazeLifePoints = MathUtils.random(1,2); setPosition(MathUtils.random(32, RideGame.WIDHT - 16), RideGame.HEIGHT + MathUtils.random(400,700), Align.center); state = State.alive; } else{ remove(); clear(); setKamikazePerimeter(new Rectangle(0, 0, -30, -30)); } } public void HitTaken() { KamikazeLifePoints--; if(KAMIKAZEAMOUNT != 0){ if(KamikazeLifePoints == 0){ state = State.dead; KAMIKAZEAMOUNT--; } } } private void UpdatePerimeter() { KamikazePerimeter.x = getX(); KamikazePerimeter.y = getY(); } public Rectangle getKamikazePerimeter() { return KamikazePerimeter; } public void setKamikazePerimeter(Rectangle kamikazePerimeter) { KamikazePerimeter = kamikazePerimeter; } private void ActAlive(float delta) { UpdatePosition(delta); if (IsBelowGround()){ ResetKamikaze(); } } private boolean IsBelowGround(){ return getY(Align.top) < 0; } private void ResetKamikaze(){ setPosition(MathUtils.random(32, RideGame.WIDHT), RideGame.HEIGHT + MathUtils.random(400,700), Align.center); } private void UpdatePosition(float delta) { //Mueve el personaje, utilizando el metodo setX y setY //pasandole la ubicacion en el momento + añadiendole las variables del //cambio de posicion. setY(getY() + Velocity.y * delta); } }
lgpl-3.0
Dragoon-Lab/LaitsV3
www/js/con-student.js
46667
/** *Dragoon Project *Arizona State University *(c) 2014, Arizona Board of Regents for and on behalf of Arizona State University * *This file is a part of Dragoon *Dragoon 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. * *Dragoon 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 Dragoon. If not, see <http://www.gnu.org/licenses/>. * */ /* global define */ /* * Student mode-specific handlers */ define([ "dojo/aspect", "dojo/_base/array", 'dojo/_base/declare', "dojo/_base/lang", "dojo/dom", "dojo/dom-class", "dojo/dom-style", "dojo/ready", "dojo/on", "dojo/dom-construct", "dijit/focus", 'dijit/registry', "dijit/TooltipDialog", "dijit/popup", './controller', "./pedagogical_module", "./typechecker", "./equation", "./schemas-student" ], function(aspect, array, declare, lang, dom, domClass, style, ready,on, domConstruct, focusUtil, registry, tooltipDialog, popup, controller, PM, typechecker, expression, schemaStudent) { /* Summary: // Summary: // MVC for the node editor, for students // Description: // Handles selections from the student as he/she completes a model; // inherits controller.js // Tags: // controller, student mode, coached mode, test mode /* Methods in controller specific to the student modes */ return declare(controller, { _PM: null, _previousExpression: null, _assessment: null, constructor: function (mode, subMode, model) { console.log("++++++++ In student constructor"); this._PM = new PM(mode, subMode, model, this.activityConfig); if (this.activityConfig.get("showNodeEditor")) { lang.mixin(this.widgetMap, this.controlMap); ready(this, "populateSelections"); this.init(); } else if (this.activityConfig.get("showIncrementalEditor")) { this.initIncrementalMenu(); }else if(this.activityConfig.get("showExecutionEditor")){ this.initExecutionEditor(); }else if(this.activityConfig.get("showWaveformEditor")){ this.initWaveformEditor(); } }, resettableControls: ["initial", "equation"], incButtons: ["Increase", "Decrease", "Stays-Same", "Unknown"], init: function () { aspect.after(this, "closeEditor", function () { var directives = this._PM.notifyCompleteness(this._model); this.applyDirectives(directives); }, true); }, // A list of control map specific to students controlMap: { description: "selectDescription", units: "selectUnits", inputs: "nodeInputs" }, setPMState: function (state) { this._PM.setState(state); }, setAssessment: function (session) { if (this._model.active.getSchemas()) { this._assessment = new schemaStudent(this._model, session, this.activityConfig); } this._PM.setAssessment(this._assessment); }, populateSelections: function () { /* Initialize select options in the node editor that are common to all nodes in a problem. In AUTHOR mode, this needs to be done when the node editor is opened. */ // Add fields to Description box and inputs box // In author mode, the description control must be a text box var d = registry.byId(this.controlMap.description); // populate input field var t = registry.byId(this.controlMap.inputs); if (!t) { this.logging.clientLog("assert", { message: "Can't find widget for " + this.controlMap.inputs, functionTag: 'populateSelections' }); } var positiveInputs = registry.byId("positiveInputs"); var negativeInputs = registry.byId("negativeInputs"); console.log("description widget = ", d, this.controlMap.description); // d.removeOption(d.getOptions()); // Delete all options //get descriptions to sort as alphabetic order var descriptions = this._model.given.getDescriptions(); //create map of names for sorting var descNameMap = {}; array.forEach(descriptions, function (desc) { descNameMap[desc.value] = this._model.given.getName(desc.value); }, this); descriptions.sort(function (obj1, obj2) { //return obj1.label > obj2.label; return descNameMap[obj1.value].toLowerCase().localeCompare(descNameMap[obj2.value].toLowerCase()); }, this); array.forEach(descriptions, function (desc) { d.addOption(desc); var name = this._model.given.getName(desc.value); var option = {label: name + " (" + desc.label + ")", value: desc.value}; console.log("option is",option); t.addOption(option); positiveInputs.addOption(option); negativeInputs.addOption(option); }, this); }, //this function populates the options for the current iteration in the execution activity populateExecOptions: function(id){ var executionValue = registry.byId("executionValue"); var execValStatus = this._model.active.getNode(id).status["executionValue"] || false; console.log("before populating",execValStatus); if(!execValStatus) { console.log("start populating"); var ret_arr = this._model.student.getAllExecutionValues(); //remove duplicates if any var uniqueOptions = ret_arr.filter(function (elem, pos) { return ret_arr.indexOf(elem) == pos; }); //populate the executionValue comboBox console.log("unique options", uniqueOptions, ret_arr); var currentOption = []; executionValue.removeOption(executionValue.getOptions()); //ad default option executionValue.addOption({label: "select",value: "default"}); array.forEach(uniqueOptions, function (optionVal) { console.log(optionVal, typeof optionVal); currentOption = [{label: "" + optionVal, value: "" + optionVal}]; executionValue.removeOption(currentOption); executionValue.addOption(currentOption); }); uniqueOptions=[]; } }, // should be moved to a function in controller.js updateInputNode: function (/** auto node id **/ id, /**variable name**/ variable) { console.log("updating nodes student controller"); //getDescriptionID using variable name var descID = this._model.given.getNodeIDByName(variable); //console.log(id,descID,this._model.given.getName(descID)); var directives = this._PM.processAnswer(id, 'description', descID, this._model.given.getName(descID)); // Need to send to PM and update status, but don't actually // apply directives since they are for a different node. array.forEach(directives, function (directive) { this.updateModelStatus(directive, id); }, this); }, isExpressionChanged: function () { var evalue = registry.byId(this.controlMap.equation).get("value"); if (this._previousExpression) { var expr = evalue; expr = expr.replace(/\s+/g, ''); if (expr == this._previousExpression) { alert("Expression is same, Please modify the expression."); return true; } else { this._previousExpression = expr; } } else { this._previousExpression = evalue.replace(/\s+/g, ''); } return false; }, handleDescription: function (selectDescription) { console.log("****** in handleDescription ", this.currentID, selectDescription); if (selectDescription == 'defaultSelect') { return; // don't do anything if they choose default } this._model.active.setDescriptionID(this.currentID, selectDescription); this.updateNodes(); // This is only needed if the type has already been set, // something that is generally only possible in TEST mode. this.updateEquationLabels(); this.applyDirectives( this._PM.processAnswer(this.currentID, 'description', selectDescription, this._model.given.getName(selectDescription))); /* if (this._forumparams) { // enable forum button and activate the event this.activateForumButton(); }*/ // Send selectedAnswer for elecronix tutor /* if(this.activityConfig.get("ElectronixTutor")){ var taskname = this._model.getTaskName().split(' ').join('-'); var nodename = this._model.active.getName(this.currentID).split(' ').join('-'); var step_id = taskname +'_'+ nodename +'_'+'SelectDescription'; this.ETConnect.sendSubmittedAnswer('description', this._model.given.getName(selectDescription), step_id, "text"); }*/ this.logging.setModelChanged(true); }, explanationHandler: function () { var givenID = this._model.student.getGivenID(this.currentID); var editorWidget = registry.byId("editorContent"); var content = this._model.given.getExplanation(givenID); editorWidget.set('value', content); // load the explanation in the editor editorWidget.set('disabled', 'true'); var toolWidget = registry.byId("dijit_Toolbar_0"); var cancelButtonWidget = registry.byId("cancelEditorButton"); cancelButtonWidget.domNode.style.display = "none";// Hide the cancel button toolWidget.domNode.style.display = "none"; // Hide the toolbar }, handleType: function (type) { console.log("****** Student has chosen type ", type, this); if (type == 'defaultSelect') return; // don't do anything if they choose default // Hide the value and expression controls in the node editor, depending on the type of node //this.adjustStudentNodeEditor(type); this.updateType(type); this.applyDirectives(this._PM.processAnswer(this.currentID, 'type', type)); // Send selectedAnswer for elecronix tutor /* if(this.activityConfig.get("ElectronixTutor")){ var taskname = this._model.getTaskName().split(' ').join('-'); var nodename = this._model.active.getName(this.currentID).split(' ').join('-'); var step_id = taskname +'_'+ nodename +'_'+'SelectType'; this.ETConnect.sendSubmittedAnswer('type', type , step_id, "text"); }*/ if(type == "parameter"){ dom.byId("initLabel").innerHTML = ""; } else if(type == "accumulator"){ dom.byId("initLabel").innerHTML = "Initial "; } this.logging.setModelChanged(true); }, // Hide the value and expression controls in the node editor, depending on the type of node /*adjustStudentNodeEditor: function(type){ if (type=="function"){ // style.set('valueDiv','display', 'none'); style.set('valueDiv','visibility', 'hidden'); style.set('expressionDiv', 'display', 'block'); } else if (type=="parameter"){ // style.set('valueDiv','display', 'inline'); style.set('valueDiv','visibility', 'visible'); style.set('initLabel', 'display', 'none'); style.set('expressionDiv', 'display', 'none'); } else{ style.set('expressionDiv', 'display', 'block'); style.set('valueDiv','visibility', 'visible'); // style.set('valueDiv','display', 'inline'); style.set('initLabel', 'display', 'inline'); } },*/ typeSet: function (value) { this.updateType(value); }, /* Handler for initial value input */ handleInitial: function (initial) { //IniFlag returns the status and initial value var IniFlag = typechecker.checkInitialValue(this.widgetMap.initial, this.lastInitial); if (IniFlag.status) { //If the initial value is not a number or is unchanged from // previous value we dont process var newInitial = IniFlag.value; this._model.active.setInitial(this.currentID, newInitial); console.log("ini value action"); console.log("current ID", this.currentID, newInitial); this.applyDirectives(this._PM.processAnswer(this.currentID, 'initial', newInitial)); } else if (IniFlag.errorType) { this.logging.log('solution-step', { type: IniFlag.errorType, node: this._model.active.getName(this.currentID), property: "initial-value", value: initial, correctResult: this._model.active.getInitial(this.currentID), checkResult: "INCORRECT" }); } // Send selectedAnswer for elecronix tutor /* if(this.activityConfig.get("ElectronixTutor")){ var taskname = this._model.getTaskName().split(' ').join('-'); var nodename = this._model.active.getName(this.currentID).split(' ').join('-'); var step_id = taskname +'_'+ nodename +'_'+'SelectInitial'; this.ETConnect.sendSubmittedAnswer('initial', initial , step_id, "text"); } */ this.logging.setModelChanged(true); }, initialSet: function (value) { this._model.active.setInitial(this.currentID, value); }, /* * handle event on inputs box */ handleInputs: function (id) { //check if id is not select else return console.log("*******Student has chosen input", id, this); // Should add name associated with id to equation // at position of cursor or at the end. var expr = this._model.given.getName(id); // if user selected selectdefault selection [--select--] no action required, calling return on handler if (expr === null) return; this.equationInsert(expr); //restore to default - creating select input as stateless registry.byId(this.controlMap.inputs).set('value', 'defaultSelect', false); this.logging.setModelChanged(true); }, handleUnits: function (unit) { console.log("*******Student has chosen unit", unit, this); // updating node editor and the model. this._model.student.setUnits(this.currentID, unit); this.applyDirectives(this._PM.processAnswer(this.currentID, 'units', unit)); // Send selectedAnswer for elecronix tutor /* if(this.activityConfig.get("ElectronixTutor")){ var taskname = this._model.getTaskName().split(' ').join('-'); var nodename = this._model.active.getName(this.currentID).split(' ').join('-'); var step_id = taskname +'_'+ nodename +'_'+'SelectUnits'; this.ETConnect.sendSubmittedAnswer('unit', unit , step_id, "text"); }*/ this.logging.setModelChanged(true); }, unitsSet: function (value) { // Update the model. this._model.student.setUnits(this.currentID, value); }, equationDoneHandler: function () { var directives = []; /*if (this.isExpressionChanged()) return; //2365 fix, just to check pattern change, not evaluating */var parse = this.equationAnalysis(directives, false); console.log("************",parse); if (parse) { var dd = this._PM.processAnswer(this.currentID, 'equation', parse, registry.byId(this.controlMap.equation).get("value")); directives = directives.concat(dd); var context = this; var showHints = this.activityConfig.get("showHints"); directives.every(function(ele){ if(ele.attribute != 'status' || ele.value != 'incorrect' || !showHints) return true; var d, s; d = (s = context.expressionSuggestor(context.currentID, parse)) ? { attribute : "append", id : "message", value : s } : null; directives.push(d); return false; }); } this.applyDirectives(directives); var isDemo = false; //When the PM returns directives, and the status is demo, there are two cases //case 1: user got the equation wrong twice and PM sent a demo status //case 2: user got the equation wrong, deleted the constituent nodes, then entered correct input, but still the user gets a demo //In case 1, nodes are auto created, but in case 2 node has been deleted and we need to create expression nodes so isDemo parameter should consider that additional case //So, as a additional check, we can check if PM has sent equation value attribute directive as well when sending a demo status, in case 2 it does not sends a value attribute var hasValAttr = false; if (directives.length > 0) { isDemo = array.some(directives, function (directive) { if(directive.attribute == "value" && directive.value != "") hasValAttr = true; if (directive.attribute == "status" && directive.value == "demo" && hasVal) return true; }); } if (!isDemo) { this.createExpressionNodes(parse, false); } // Send selectedAnswer for elecronix tutor /* if(this.activityConfig.get("ElectronixTutor")){ var taskname = this._model.getTaskName().split(' ').join('-'); var nodename = this._model.active.getName(this.currentID).split(' ').join('-'); var step_id = taskname +'_'+ nodename +'_'+'CheckExpression'; this.ETConnect.sendSubmittedAnswer('expression', registry.byId(this.controlMap.equation).get("value"), step_id, "text"); } */ this.logging.setModelChanged(true); return directives; }, equationSet: function (value) { // applyDirectives updates equationBox, but not equationText: dom.byId("equationText").innerHTML = value; if(value != ""){ var directives = []; // Parse and update model, connections, etc. var parse = this.equationAnalysis(directives); // Generally, since this is the correct solution, there should be no directives this.applyDirectives(directives); //Set equation and process answer var parsedEquation = parse.toString(true); this._model.active.setEquation(this.currentID, parsedEquation); var dd = this._PM.processAnswer(this.currentID, 'equation', parse, registry.byId(this.controlMap.equation).get("value")); this.applyDirectives(dd); //Create expression nodes for parsed equation this.createExpressionNodes(parse); } }, //Set description for autocreated Nodes setNodeDescription: function (id, variable) { //getDescriptionID using variable name var descID = this._model.given.getNodeIDByName(variable); //setDescriptionID for the node id this._model.active.setDescriptionID(id, descID); this.updateNodeLabel(id); }, /* Settings for a new node, as supplied by the PM. These don't need to be recorded in the model, since they are applied each time the node editor is opened. */ initialControlSettings: function (nodeid) { // Apply settings from PM this.applyDirectives(this._PM.newAction(), true); this.applyDirectives(this._PM.newActionVisibility(), true); // Set the selected value in the description. var desc = this._model.student.getDescriptionID(nodeid); console.log('description is', desc || "not set"); registry.byId(this.controlMap.description).set('value', desc || 'defaultSelect', false); var type = this._model.student.getType(nodeid); if(type){ this.applyDirectives(this._PM.getActionForType(nodeid, type)); } /* Set color and enable/disable */ if(!this.activityConfig.get("allowEditGivenNode")){ array.forEach(this._model.student.getStatusDirectives(nodeid), function (directive) { var w = registry.byId(this.controlMap[directive.id]); w.set(directive.attribute, directive.value); // The actual values should be in the model itself, not in status directives. if (directive.attribute == "value") { this.logging.clientLog("error", { message: "Values should not be set in status directives", functionTag: 'initialControlSettings' }); } }, this); } }, // Need to save state of the node editor in the status section // of the student model. See documentation/json-format.md updateModelStatus: function (desc, id) { //in case of autocreation nodes, id must be passed explicitly id = id || this.currentID; if (this.validStatus[desc.attribute]) { var opt = {}; opt[desc.attribute] = desc.value; this._model.student.setStatus(id, desc.id, opt); } else { // There are some directives that should update // the student model node (but not the status section). // console.warn("======= not saving in status, node=" + this.currentID + ": ", desc); } }, checkDonenessMessage: function () { // Returns true if model is not complete. var directives = this._PM.checkDoneness(this._model); this.applyDirectives(directives); return directives; }, nodeStartAssessment: function () { if (this._assessment) { this._assessment.nodeStart(this.currentID); } }, nodeCloseAssessment: function () { if (this._assessment && this._assessment.currentNodeTime) { this._assessment.nodeClose(this.currentID); } }, /* * Common functions for Incremental and Execution activities */ getChangeDescriptionText:function(changeDesc){ var changeDescript; switch(changeDesc) { case "Increase": changeDescript=" has been increased." break; case "Decrease": changeDescript=" has been decreased." break; case "Stays-Same": changeDescript=" stays the same." break; case "Unknown": changeDescript=" will sometimes increase and sometimes decrease." break; default: changeDescript="" } return changeDescript; }, formatEquationMessage: function(){ /* * Summary: Formats the message to be displayed by equation dialog * Used by showEquationDialog */ var type = this._model.active.getType(this.currentID); var equationMessage = ""; var equation = expression.convert(this._model.active, this._model.active.getEquation(this.currentID)); var nodeName = this._model.active.getName(this.currentID); var inputs=this._model.active.getInputs(this.currentID); if (type == "accumulator") { equationMessage = "<p><b>"+"new " + nodeName + " = " + "current " + nodeName + " + " + equation+"</b></p>"; } else if (type == "function") { equationMessage = "<p><b>"+ nodeName + " = " + equation+"</b></p>"; } if (this.activityConfig._activity=="incrementalDemo") { equationMessage+="<p><div style='text-align:left'>"+"Compared to the original model:"+"</p>"; equationMessage+="<ul>"; array.forEach(inputs, lang.hitch(this, function(node){ var nodeType=this._model.active.getType(node.ID); var changeDesc=this._model.active.getTweakDirection(node.ID); var changeDescription=this.getChangeDescriptionText(changeDesc); if (nodeType==="accumulator") equationMessage+="<li>"+"Initial value for the "+this._model.active.getName(node.ID)+" stays the same"+"</li>"; else equationMessage+="<li>"+this._model.active.getName(node.ID)+changeDescription+"</li>"; })); equationMessage+="</ul><p>"+ "Therefore, "+nodeName+this.getChangeDescriptionText(this._model.active.getTweakDirection(this.currentID))+"</p>"; } return equationMessage }, showEquationDialog: function(){ /* * Summary: Shows the equation of the node in a popup dialog with correct formatting * Used by initIncrementalMenu and initExecutionMenu */ var nodeName = this._model.active.getName(this.currentID); var equationMessage = this.formatEquationMessage(); this.logging.log('ui-action', { type: "open-equation", node: this._model.active.getName(this.currentID), nodeID: this.currentID }); this.applyDirectives([{ id: "crisisAlert", attribute: "title", value: "Equation for " + nodeName }, { id: "crisisAlert", attribute: "open", value: equationMessage }]); }, showExplanationDialog: function(){ /* * Summary: Shows the explanation(if exists) for the node in a popup dialog * Used by initIncrementalMenu and initExecutionMenu */ var givenID = this._model.active.getDescriptionID(this.currentID); if (this._model.given.getExplanation(givenID)) { var nodeName = this._model.active.getName(this.currentID); this.logging.log('ui-action', { type: "open-explanation", node: nodeName, nodeID: this.currentID }); this.applyDirectives([{ id: "crisisAlert", attribute: "title", value: "Explanation for " + nodeName }, { id: "crisisAlert", attribute: "open", value: this._model.given.getExplanation(givenID) }]); } }, /* * Incremental Menu * Summary: initialize, add event handlers and show incremental menu tooltipDialog */ showIncrementalEditor: function (id) { this.currentID = id; this.isIncrementalEditorVisible = true; var type = this._model.active.getType(id); var givenID = this._model.active.getDescriptionID(id); var nodeName = this._model.active.getName(id); var showEquationButton = registry.byId("EquationButton").domNode; var showExplanationButton = registry.byId("ShowExplanationButton").domNode; if (type != "accumulator" && type != "function") { style.set(showEquationButton, "display", "none"); this.closeIncrementalMenu(); } else { if (!this.activityConfig.get("showPopupIfComplete") || (this.activityConfig.get("showPopupIfComplete") && this._model.active.isComplete(id))) { //Set Node Name dom.byId("IncrementalNodeName").innerHTML = "<strong>" + nodeName + "</strong>"; //Show hide explanation button this._model.given.getExplanation(givenID) ? style.set(showExplanationButton, "display", "block") : style.set(showExplanationButton, "display", "none"); style.set(showEquationButton, "display", "block"); var tweakStatus = this._model.active.getNode(id).status["tweakDirection"]; //Enable/Disable incremental buttons if (tweakStatus && tweakStatus.disabled) { array.forEach(this.incButtons, function (widget) { var w = registry.byId(widget + "Button"); w.set("disabled", tweakStatus.disabled); }); } else { array.forEach(this.incButtons, function (widget) { var w = registry.byId(widget + "Button"); w.set("disabled", false); }); } popup.open({ popup: this._incrementalMenu, around: dom.byId(id) }); this._incrementalMenu.onBlur = lang.hitch(this, function () { if(this.isIncrementalEditorVisible) this.closeIncrementalMenu(); }); } } }, initIncrementalMenu: function () { var that = this; //Hide or show inc Buttons array.forEach(this.incButtons, lang.hitch(this, function (buttonID) { var button = registry.byId(buttonID + "Button").domNode; style.set(button, "display", this._uiConfig.get("qualitativeChangeButtons")); })); //Initialize incremental popup this._incrementalMenu = registry.byId("incrementalMenu"); this._incrementalMenu.onShow = lang.hitch(this, function () { //logging for pop up start that.logging.log('ui-action', { type: "open-tweak-popup", node: that._model.active.getName(that.currentID), nodeID: that.currentID }); //assessment for tweak pop up that.nodeStartAssessment(that.currentID); focusUtil.focus(dom.byId("IncreaseButton")); }); this.incButtons.forEach(function (item) { var btn = registry.byId(item + "Button"); on(btn, "click", function (e) { e.preventDefault(); //Set in the model that._model.active.setTweakDirection(that.currentID, item); //Process Answer var result = that._PM.processAnswer(that.currentID, "tweakDirection", item); that.applyDirectives(result); //Update Node Label that.updateNodeLabel(that.currentID); //Close popup that.closeIncrementalMenu(true); // Send selectedAnswer for elecronix tutor /* if(that.activityConfig.get("ElectronixTutor")){ var taskname = that._model.getTaskName().split(' ').join('-'); var nodename = that._model.active.getName(that.currentID).split(' ').join('-'); var step_id = taskname +'_'+ nodename +'_'+'SelectTweakDirection'; that.ETConnect.sendSubmittedAnswer('tweakDirection', item , step_id, "text"); } */ }); }); var showEquationButton = registry.byId("EquationButton"); on(showEquationButton, "click", lang.hitch(this, function () { this.showEquationDialog(); })); var showExplanationButton = registry.byId("ShowExplanationButton"); on(showExplanationButton, 'click', lang.hitch(this, function () { this.showExplanationDialog(); })); }, closeIncrementalMenu: function (doColorNodeBorder) { this.logging.log('ui-action', { type: "close-tweak-popup", node: this._model.active.getName(this.currentID), nodeID: this.currentID }); this.nodeCloseAssessment(this.currentID); this.isIncrementalEditorVisible = false; popup.close(this._incrementalMenu); if (doColorNodeBorder) { this.colorNodeBorder(this.currentID, true); } }, //code moved to main.js as events should be handled there. //added an aspect.after for each node menu close for every activity and that is how done message is shown - Sachin Grover /*canShowDonePopup: function () { studId = this._model.active.getNodes(); var isFinished = true; studId.forEach(lang.hitch(this, function (newId) { //each node should be complete and correct else set isFinished to false if (!this._model.active.isComplete(newId.ID) || this._model.student.getCorrectness(newId.ID) === "incorrect") isFinished = false; })); if (isFinished) { if (registry.byId("closeHint")) { var closeHintId = registry.byId("closeHint"); closeHintId.destroyRecursive(false); } //close popup each time popup.close(problemDoneHint); var problemDoneHint = new tooltipDialog({ style: "width: 300px;", content: '<p>You have completed this activity. Click "Done" when you are ready to save and submit your work.</p>' + ' <button type="button" data-dojo-type="dijit/form/Button" id="closeHint">Ok</button>', onShow: function () { on(registry.byId('closeHint'), 'click', function () { popup.close(problemDoneHint); }); }, onBlur: function () { popup.close(problemDoneHint); } }); this.logging.log('solution-step', { type: "completeness-check", problemComplete: isFinished }); var res=popup.open({ popup: problemDoneHint, around: dom.byId('doneButton') }); this.shownDone = true; // Trigger notify completeness since we're done. // Construction triggers this when the node editor closes instead. if (this.activityConfig.getActivity() != "construction"){ var directives = this._PM.notifyCompleteness(this._model); this.applyDirectives(directives); } } },*/ highlightNextNode: function () { if (this.activityConfig.get("demoIncrementalFeatures") || this.activityConfig.get("demoExecutionFeatures")) { //Get next node in the list from PM var nextID = this._PM.getNextNode(); if (nextID) { var node = dom.byId(nextID); domClass.add(node, "glowNode"); this.currentHighLight = nextID; } else { this.currentHighLight = null; } return; } }, showIncrementalAnswer: function (id) { this.currentID = id; if (id === this.currentHighLight) { //remove glow var node = dom.byId(id); domClass.remove(node, "glowNode"); //Process Answer var givenID = this._model.active.getDescriptionID(id); var answer = this._model.given.getTweakDirection(givenID); var result = this._PM.processAnswer(this.currentID, "tweakDirection", answer); this.applyDirectives(result); //Set correct answer in model this._model.active.setTweakDirection(this.currentID, answer); //Update Node Label this.updateNodeLabel(id); this.colorNodeBorder(this.currentID, true); //highlight next node in the list this.highlightNextNode(); } }, resetNodesIncDemo: function (){ var studId = this._model.active.getNodes(); var nowHighLighted = this.currentHighLight; studId.forEach(lang.hitch(this, function (newId) { //remove the glow for current highlighted node as a part of reset if(newId.ID === nowHighLighted) { var noHighlight = dom.byId(newId.ID); domClass.remove(noHighlight, "glowNode"); } if(newId.type!=="parameter"){ //set tweak direction to null and status none this._model.active.setTweakDirection(newId.ID,null); this._model.active.setStatus(newId.ID,"tweakDirection",""); //update node label and border color this.updateNodeLabel(newId.ID); this.colorNodeBorder(newId.ID, true); } })); //highlight next (should be the first) node in the list //reset the node counter to 0 before highlighting this._PM.nodeCounter = 0; this.highlightNextNode(); this.shownDone = false; }, resetNodesExecDemo: function(){ var studId = this._model.active.getNodes(); var nowHighLighted = this.currentHighLight; this._model.student.setIteration(0); studId.forEach(lang.hitch(this, function (newId) { //remove the glow for current highlighted node as a part of reset if(newId.ID === nowHighLighted) { var noHighlight = dom.byId(newId.ID); domClass.remove(noHighlight, "glowNode"); } if(newId.type!=="parameter"){ //empty the execution values this._model.student.emptyExecutionValues(newId.ID); //update node label and border color this.updateNodeLabel(newId.ID); this.colorNodeBorder(newId.ID, true); } })); //highlight next (should be the first) node in the list this._PM.nodeCounter = 0; this.highlightNextNode(); }, resetIterationExecDemo: function(){ var studId = this._model.active.getNodes(); var nowHighLighted = this.currentHighLight; var iteration = this._model.student.getIteration(); studId.forEach(lang.hitch(this, function (newId) { var givenID = this._model.active.getDescriptionID(newId.ID); //remove the glow for current highlighted node as a part of reset if(newId.ID === nowHighLighted) { var noHighlight = dom.byId(newId.ID); domClass.remove(noHighlight, "glowNode"); } if(newId.type!=="parameter"){ //update node label and border color this.updateNodeLabel(newId.ID); this.colorNodeBorder(newId.ID, true); if(this.activityConfig.get("executionExercise")) { this._model.active.getNode(newId.ID).status["executionValue"]=null; registry.byId("executionValue").set("disabled", false); } this._model.given.getNode(givenID).attemptCount['assistanceScore'] = 0; this._model.given.getNode(givenID).attemptCount['tweakDirection'] = 0; this._model.given.getNode(givenID).attemptCount['executionValue'][iteration] = 0; //Update Node Label this.updateNodeLabel(newId.ID); this.colorNodeBorder(newId.ID, true); } })); //highlight next (should be the first) node in the list this._PM.nodeCounter = 0; this.highlightNextNode(); }, /* * Execution Editor * Summary: initialize, add event handlers and show execution menu tooltipDialog */ initExecutionEditor: function (){ var that = this; this._executionMenu = registry.byId("executionMenu"); this._executionMenu.onShow = lang.hitch(this, function () { //logging for pop up start that.logging.log('ui-action', { type: "open-execution-popup", node: that._model.active.getName(that.currentID), nodeID: that.currentID }); //assessment for tweak pop up that.nodeStartAssessment(that.currentID); focusUtil.focus(dom.byId("executionValue")); }); var showEquationButton = registry.byId("ExecEquationButton"); on(showEquationButton, "click", lang.hitch(this, function () { this.showEquationDialog(); })); var showExplanationButton = registry.byId("ExecShowExplanationButton"); on(showExplanationButton, 'click', lang.hitch(this, function () { this.showExplanationDialog(); })); this._executionMenu.onBlur = lang.hitch(this, function () { this.closeExecutionMenu(); }); var executionValue = registry.byId("executionValue"); //for change in the select values executionValue.on('change', lang.hitch(this, function () { var currentValue = this._model.active.getExecutionValue(this.currentID) || ""; if(executionValue.value !== "default" && currentValue !== executionValue.value) { //var givenID = this._model.active.getDescriptionID(id); var answer = executionValue.value; this._model.active.setExecutionValue(this.currentID, answer); var result = this._PM.processAnswer(this.currentID, "executionValue", answer); this.applyDirectives(result); //Update Node Label this.updateNodeLabel(this.currentID); this.colorNodeBorder(this.currentID, true); } this.canRunNextIteration(); })); var executionValText = registry.byId("executionValue"); executionValText._setStatusAttr = this._setStatus; }, showExecutionMenu: function (id){ this.currentID = id; var givenID = this._model.active.getDescriptionID(id); var type = this._model.active.getType(id); var nodeName = this._model.active.getName(id); var showExplanationButton = registry.byId("ExecShowExplanationButton").domNode; if (type != "accumulator" && type != "function") { this.closeExecutionMenu(); } else { if (!this.activityConfig.get("showPopupIfComplete") || (this.activityConfig.get("showPopupIfComplete") && this._model.active.isComplete(id))) { //set node name dom.byId("executionNodeName").innerHTML = "<strong>" + nodeName + "</strong>"; var executionValue = registry.byId("executionValue"); //Show hide explanation button this._model.given.getExplanation(givenID) ? style.set(showExplanationButton, "display", "block") : style.set(showExplanationButton, "display", "none"); //in case of execution demo we need to show the correct answer if(this.activityConfig.get("demoExecutionFeatures")) { var answer = this._model.active.getExecutionValue(id) || ""; executionValue.set("value", answer); } //in case of execution activity we need to populate the options for the student to solve else if(this.activityConfig.get("executionExercise")){ answer = this._model.active.getExecutionValue(id) || ""; executionValue.set("value", answer); this.populateExecOptions(id); } //enable/disable textbox and button var execValStatus = this._model.active.getNode(id).status["executionValue"] || false; executionValue.set("status", execValStatus.status|| ""); if (execValStatus && execValStatus.disabled) { executionValue.set("disabled", execValStatus.disabled); }else{ executionValue.set("disabled", false); } //open execution menu popup.open({ popup: this._executionMenu, around: dom.byId(id) }); } } //check if is the end of iteration with the current node completion this.canRunNextIteration(); }, showExecutionAnswer : function (id){ this.currentID = id; if(id === this.currentHighLight){ //console.log("Updating answer in node: "+id); //remove glow var node = dom.byId(id); domClass.remove(node, "glowNode"); // process answer var givenID = this._model.active.getDescriptionID(id); var answer = this._model.given.getExecutionValue(givenID); var result = this._PM.processAnswer(id, "executionValue", answer); this.applyDirectives(result); //Set correct answer in model this._model.active.setExecutionValue(this.currentID, answer); registry.byId("executionValue").addOption({label: ""+answer, value: ""+answer}); registry.byId("executionValue").attr("value",answer); //Update Node Label this.updateNodeLabel(id); this.colorNodeBorder(this.currentID, true); //highlight next node in the list this.highlightNextNode(); } }, handleExecChange: function(val){ console.log("value returned is",val); }, closeExecutionMenu: function (){ this.logging.log('ui-action', { type: "close-execution-popup", node: this._model.active.getName(this.currentID), nodeID: this.currentID }); this.nodeCloseAssessment(this.currentID); popup.close(this._executionMenu); }, canRunNextIteration: function () { var crisis=registry.byId(this.widgetMap.crisisAlert); crisis._onKey=function(){}; // Override the _onKey function to prevent crisis dialogbox from closing when ESC is pressed style.set(crisis.closeButtonNode,"display","none"); // Hide the close button var iterationNum=this._model.student.getIteration(); var maxItration=this._model.getExecutionIterations(); studId = this._model.active.getNodes(); var isFinished = true; studId.forEach(lang.hitch(this, function (newId) { //each node should be complete and correct else set isFinished to false if (!this._model.active.isComplete(newId.ID) || this._model.student.getCorrectness(newId.ID) === "incorrect") isFinished = false; })); if (isFinished & iterationNum<maxItration-1) { // Not in the last iteration this.applyDirectives([{ id: "crisisAlert", attribute: "title", value: "Iteration Has Completed" }, { id: "crisisAlert", attribute: "open", value: "You have completed all the values for this time step. Click 'Ok' to proceed to the next time step." }]); } else if (isFinished && iterationNum==maxItration-1 && !this.isFinalMessageShown) {// In last iteration this.applyDirectives([{ id: "crisisAlert", attribute: "title", value: "Demonstration Completed" }, { id: "crisisAlert", attribute: "open", value: "Good work, now Dragoon will compute the rest of the values for you and display them as a table and as a graph in the next window. Explore the graph window, and close it when you are done." }]); // We're done, so notify completeness this.applyDirectives(this._PM.notifyCompleteness(this._model)); this.isFinalMessageShown = true; } //console.log("model is",this._model); }, callNextIteration: function () { this._model.student.incrementIteration(); console.log("iteration count is",this._model.student.getIteration()); var crisis = registry.byId(this.widgetMap.crisisAlert); if(this._model.student.getIteration() <= this._model.getExecutionIterations()) { this.resetIterationExecDemo(); } }, /* *************************** Waveform Editor ******************************* */ initWaveformEditor: function(){ console.log("---initWaveformEditor---"); var waveformEditorDialog = registry.byId('waveformEditor'); //Fetch array of waveforms dojo.xhrGet({ url:"waveforms.json", handleAs: "json", load: lang.hitch(this, function(result){ this.waveforms = result; if(this.waveforms.length > 0) { var waveformsContainer = dom.byId("waveform-container"); this.waveforms.forEach(lang.hitch(this, function (w, index) { var waveform = '<div id="' + w + 'Div" class="waveformItem">' + '<img class="imgWaveform" alt="' + w + '" src="images/waveforms/' + w + '.png"/>' + '</div>'; if ((index + 1) % 7 == 0) waveform += '<br/>' dojo.place(waveform, waveformsContainer, "last"); //Add click event for waveform images except the already selected one var waveFormDivDom = dom.byId(w + "Div"); on(waveFormDivDom, "click", lang.hitch(this, function (evt) { //Set selected waveform to model var selectedWaveform = evt.target; var value = dojo.getAttr(selectedWaveform, 'alt'); if (value != null) { this._model.active.setWaveformValue(this.currentID, value); //Call process Answer var directives = this._PM.processAnswer(this.currentID, 'waveformValue', value); this.applyDirectives(directives); //Update UI and Node border this.updateNodeLabel(this.currentID); this.colorNodeBorder(this.currentID, true); waveformEditorDialog.hide(); // Send selectedAnswer for elecronix tutor /* if(this.activityConfig.get("ElectronixTutor")){ var taskname = this._model.getTaskName().split(' ').join('-'); var nodename = this._model.active.getName(this.currentID).split(' ').join('-'); var step_id = taskname +'_'+ nodename +'_'+'SelectWaveform'; this.ETConnect.sendSubmittedAnswer('waveform', value , step_id, "text"); }*/ } })); })); } }), error: function(err){ console.log(err); } }); var showEquationButton = registry.byId("WaveformEquationButton"); on(showEquationButton, "click", lang.hitch(this, function () { this.showEquationDialog(); })); var showExplanationButton = registry.byId("WaveformExplanationButton"); on(showExplanationButton, 'click', lang.hitch(this, function () { this.showExplanationDialog(); })); }, showWaveformEditor: function(id){ this.currentID = id; var givenID = this._model.active.getDescriptionID(id); if(this._model.active.getType(id) === "parameter") return; var nodeName = this._model.active.getName(id); var value = this._model.active.getWaveformValue(id); var waveformEditorDialog = registry.byId('waveformEditor'); var waveformContainer = dom.byId('waveform-container'); //array of handlers for waveforms var waveformStatus = this._model.active.getNode(id).status["waveformValue"]; //Add handlers to the images if(typeof value !== "undefined") { style.set(waveformContainer, "display", "block"); dojo.query(".waveformDisabled").forEach(dojo.destroy); this.waveforms.forEach(lang.hitch(this, function (w, index) { var waveFormDivDom = dom.byId(w + "Div"); //Set selected answer in the editor if (value == w) { domClass.add(waveFormDivDom, "waveformSelected"); } else { domClass.remove(waveFormDivDom, "waveformSelected"); } if (waveformStatus && waveformStatus.disabled) { var disableOverlay = '<div class="waveformDisabled"></div>'; dojo.place(disableOverlay, waveFormDivDom, "first"); waveFormDivDom.style.pointerEvents = "none"; } else { waveFormDivDom.style.pointerEvents = "auto"; } })); }else{ style.set(waveformContainer, "display", "none"); } //Show Waveform editor waveformEditorDialog.set('title', nodeName); waveformEditorDialog.show(); var showExplanationButton = registry.byId('WaveformExplanationButton').domNode; //Show hide explanation button if(this._model.given.getExplanation(givenID)) style.set(showExplanationButton, "display", "block"); else style.set(showExplanationButton, "display", "none"); }, notifyCompleteness: function(){ // Trigger notify completeness since we're done. // Construction triggers this when the node editor closes instead. if (this.activityConfig.getActivity() != "construction"){ var directives = this._PM.notifyCompleteness(this._model); this.applyDirectives(directives); } } }); });
lgpl-3.0
fuinorg/event-store-commons
test/src/test/java/org/fuin/esc/test/ReadAllForwardChunk.java
4816
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * 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 3 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, see http://www.gnu.org/licenses/. */ package org.fuin.esc.test; import java.util.ArrayList; import java.util.List; import org.fuin.esc.api.CommonEvent; import org.fuin.esc.api.EventId; import org.fuin.esc.api.SimpleCommonEvent; import org.fuin.esc.test.examples.BookAddedEvent; import org.fuin.objects4j.common.Nullable; import org.fuin.objects4j.vo.UUIDStrValidator; /** * Expected chunk when reading forward all events of a stream. */ public final class ReadAllForwardChunk { // Creation (Initialized by Cucumber) // DO NOT CHANGE ORDER OR RENAME VARIABLES! private String resultEventId1; private String resultEventId2; private String resultEventId3; private String resultEventId4; private String resultEventId5; private String resultEventId6; private String resultEventId7; private String resultEventId8; private String resultEventId9; // NOT set by Cucumber private List<CommonEvent> eventList; /** * Default constructor used by Cucumber. */ public ReadAllForwardChunk() { super(); } /** * Constructor for manual creation. * * @param events * Events. */ public ReadAllForwardChunk(@Nullable final String... events) { super(); eventList = new ArrayList<>(); if (events != null) { for (final String event : events) { addEvent(eventList, event); } } } /** * Constructor for manual creation. * * @param events * Events. */ public ReadAllForwardChunk(@Nullable final List<CommonEvent> events) { super(); eventList = new ArrayList<>(); if (events != null) { eventList.addAll(events); } } /** * Returns a list of expected events. * * @return Event list. */ public final List<CommonEvent> getEvents() { if (eventList == null) { eventList = new ArrayList<>(); addEvent(eventList, resultEventId1); addEvent(eventList, resultEventId2); addEvent(eventList, resultEventId3); addEvent(eventList, resultEventId4); addEvent(eventList, resultEventId5); addEvent(eventList, resultEventId6); addEvent(eventList, resultEventId7); addEvent(eventList, resultEventId8); addEvent(eventList, resultEventId9); } return eventList; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((eventList == null) ? 0 : eventList.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ReadAllForwardChunk other = (ReadAllForwardChunk) obj; if (eventList == null) { if (other.eventList != null) { return false; } } else if (!eventList.equals(other.eventList)) { return false; } return true; } private static void addEvent(final List<CommonEvent> events, final String eventId) { if (eventId != null && UUIDStrValidator.isValid(eventId)) { final CommonEvent ce = new SimpleCommonEvent(new EventId(eventId), BookAddedEvent.TYPE, new BookAddedEvent("Any", "John Doe")); events.add(ce); } } @Override public String toString() { final StringBuilder sb = new StringBuilder("{"); if (eventList != null) { for (final CommonEvent event : eventList) { if (sb.length() > 1) { sb.append(", "); } sb.append(event.getId()); } } sb.append("}"); return sb.toString(); } }
lgpl-3.0
c2mon/c2mon-client-ext-history
src/main/java/cern/c2mon/client/ext/history/data/event/HistoryLoaderListener.java
1778
/****************************************************************************** * Copyright (C) 2010-2016 CERN. All rights not expressly granted are reserved. * * This file is part of the CERN Control and Monitoring Platform 'C2MON'. * C2MON 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. * * C2MON 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 C2MON. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ package cern.c2mon.client.ext.history.data.event; import cern.c2mon.client.ext.history.playback.data.HistoryLoader; /** * Used by {@link HistoryLoader} to inform about events * * @see HistoryLoaderAdapter * * @author vdeila * */ public interface HistoryLoaderListener { /** * Invoked when the starting to initialize history */ void onInitializingHistoryStarting(); /** * Invoked with the current status of the initialization * * @param progressMessage A message describing the current actions taken */ void onInitializingHistoryProgressStatusChanged(final String progressMessage); /** * Invoked when the history initialization is finished */ void onInitializingHistoryFinished(); /** * Invoked if memory resources is to low to load more data */ void onStoppedLoadingDueToOutOfMemory(); }
lgpl-3.0
SergiyKolesnikov/fuji
examples/Chat_casestudies/chat-tuellenburg/src/PrivateMessage.java
286
public class PrivateMessage extends Message { private String message; public PrivateMessage(String line) { this.message = line; } public String getMessage() { return message; } public void setMessage(String message) { ((PrivateMessage) this).message = message; } }
lgpl-3.0
nisavid/spruce-datetime
spruce/datetime/_misc.py
786
"""Miscellany""" __copyright__ = "Copyright (C) 2014 Ivan D Vasin" __docformat__ = "restructuredtext" from datetime import datetime as _datetime import pytz as _pytz from . import _tz def now(): """The current UTC date-time The resulting :class:`~datetime.datetime` is time-zone-aware, unlike the result of :meth:`datetime.utcnow() <datetime.datetime.utcnow>`. :rtype: :class:`datetime.datetime` """ return _datetime.now(_pytz.UTC) def now_localtime(): """The current local-time date-time The resulting :class:`~datetime.datetime` is time-zone-aware, unlike the result of calling :meth:`datetime.now() <datetime.datetime.now>` with no argument. :rtype: :class:`datetime.datetime` """ return _datetime.now(_tz.LOCALTIME)
lgpl-3.0
webeweb/WBWHighchartsBundle
Tests/API/Chart/Series/Area/HighchartsDataLabelsTest.php
17012
<?php /** * This file is part of the highcharts-bundle package. * * (c) 2017 WEBEWEB * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace WBW\Bundle\HighchartsBundle\Tests\API\Chart\Series\Area; use WBW\Bundle\HighchartsBundle\Tests\AbstractTestCase; /** * Highcharts data labels test. * * @author webeweb <https://github.com/webeweb/> * @package WBW\Bundle\HighchartsBundle\Tests\API\Chart\Series\Area * @version 5.0.14 */ final class HighchartsDataLabelsTest extends AbstractTestCase { /** * Tests the __construct() method. * * @return void */ public function testConstructor() { $obj1 = new \WBW\Bundle\HighchartsBundle\API\Chart\Series\Area\HighchartsDataLabels(true); $this->assertNull($obj1->getAlign()); $this->assertNull($obj1->getAllowOverlap()); $this->assertNull($obj1->getBackgroundColor()); $this->assertNull($obj1->getBorderColor()); $this->assertNull($obj1->getBorderRadius()); $this->assertNull($obj1->getBorderWidth()); $this->assertNull($obj1->getClassName()); $this->assertNull($obj1->getColor()); $this->assertNull($obj1->getCrop()); $this->assertNull($obj1->getDefer()); $this->assertNull($obj1->getEnabled()); $this->assertNull($obj1->getFormat()); $this->assertNull($obj1->getFormatter()); $this->assertNull($obj1->getInside()); $this->assertNull($obj1->getOverflow()); $this->assertNull($obj1->getPadding()); $this->assertNull($obj1->getRotation()); $this->assertNull($obj1->getShadow()); $this->assertNull($obj1->getShape()); $this->assertNull($obj1->getStyle()); $this->assertNull($obj1->getUseHTML()); $this->assertNull($obj1->getVerticalAlign()); $this->assertNull($obj1->getX()); $this->assertNull($obj1->getY()); $this->assertNull($obj1->getZIndex()); $obj0 = new \WBW\Bundle\HighchartsBundle\API\Chart\Series\Area\HighchartsDataLabels(false); $this->assertEquals("center", $obj0->getAlign()); $this->assertEquals(false, $obj0->getAllowOverlap()); $this->assertNull($obj0->getBackgroundColor()); $this->assertNull($obj0->getBorderColor()); $this->assertEquals(0, $obj0->getBorderRadius()); $this->assertEquals(0, $obj0->getBorderWidth()); $this->assertNull($obj0->getClassName()); $this->assertNull($obj0->getColor()); $this->assertEquals(true, $obj0->getCrop()); $this->assertEquals(true, $obj0->getDefer()); $this->assertEquals(false, $obj0->getEnabled()); $this->assertEquals("{y}", $obj0->getFormat()); $this->assertNull($obj0->getFormatter()); $this->assertNull($obj0->getInside()); $this->assertEquals("justify", $obj0->getOverflow()); $this->assertEquals(5, $obj0->getPadding()); $this->assertEquals(0, $obj0->getRotation()); $this->assertEquals(false, $obj0->getShadow()); $this->assertEquals("square", $obj0->getShape()); $this->assertEquals(["color" => "contrast", "fontSize" => "11px", "fontWeight" => "bold", "textOutline" => "1px contrast"], $obj0->getStyle()); $this->assertEquals(false, $obj0->getUseHTML()); $this->assertNull($obj0->getVerticalAlign()); $this->assertEquals(0, $obj0->getX()); $this->assertEquals(-6, $obj0->getY()); $this->assertEquals(6, $obj0->getZIndex()); } /** * Tests the jsonSerialize() method. * * @return void */ public function testJsonSerialize() { $obj = new \WBW\Bundle\HighchartsBundle\API\Chart\Series\Area\HighchartsDataLabels(true); $this->assertEquals([], $obj->jsonSerialize()); } /** * Tests the toArray() method. * * @return void */ public function testToArray() { $obj = new \WBW\Bundle\HighchartsBundle\API\Chart\Series\Area\HighchartsDataLabels(true); $obj->setAlign("right"); $res1 = ["align" => "right"]; $this->assertEquals($res1, $obj->toArray()); $obj->setAllowOverlap(1); $res2 = ["align" => "right", "allowOverlap" => 1]; $this->assertEquals($res2, $obj->toArray()); $obj->setBackgroundColor("930f2a43179a7ae5fc25ed873223e99f"); $res3 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f"]; $this->assertEquals($res3, $obj->toArray()); $obj->setBorderColor("97da935a74593c55d78be9d1295aa994"); $res4 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994"]; $this->assertEquals($res4, $obj->toArray()); $obj->setBorderRadius(93); $res5 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93]; $this->assertEquals($res5, $obj->toArray()); $obj->setBorderWidth(71); $res6 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71]; $this->assertEquals($res6, $obj->toArray()); $obj->setClassName("6f66e878c62db60568a3487869695820"); $res7 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820"]; $this->assertEquals($res7, $obj->toArray()); $obj->setColor("70dda5dfb8053dc6d1c492574bce9bfd"); $res8 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd"]; $this->assertEquals($res8, $obj->toArray()); $obj->setCrop(0); $res9 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0]; $this->assertEquals($res9, $obj->toArray()); $obj->setDefer(1); $res10 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1]; $this->assertEquals($res10, $obj->toArray()); $obj->setEnabled(0); $res11 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0]; $this->assertEquals($res11, $obj->toArray()); $obj->setFormat("1ddcb92ade31c8fbd370001f9b29a7d9"); $res12 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9"]; $this->assertEquals($res12, $obj->toArray()); $obj->setFormatter("f2ffc59487832cbad265a8fef2133592"); $res13 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592"]; $this->assertEquals($res13, $obj->toArray()); $obj->setInside(1); $res14 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1]; $this->assertEquals($res14, $obj->toArray()); $obj->setOverflow("none"); $res15 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none"]; $this->assertEquals($res15, $obj->toArray()); $obj->setPadding(47); $res16 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none", "padding" => 47]; $this->assertEquals($res16, $obj->toArray()); $obj->setRotation(25); $res17 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none", "padding" => 47, "rotation" => 25]; $this->assertEquals($res17, $obj->toArray()); $obj->setShadow(0); $res18 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none", "padding" => 47, "rotation" => 25, "shadow" => 0]; $this->assertEquals($res18, $obj->toArray()); $obj->setShape("8c73a98a300905900337f535531dfca6"); $res19 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none", "padding" => 47, "rotation" => 25, "shadow" => 0, "shape" => "8c73a98a300905900337f535531dfca6"]; $this->assertEquals($res19, $obj->toArray()); $obj->setStyle(["style" => "a1b01e734b573fca08eb1a65e6df9a38"]); $res20 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none", "padding" => 47, "rotation" => 25, "shadow" => 0, "shape" => "8c73a98a300905900337f535531dfca6", "style" => ["style" => "a1b01e734b573fca08eb1a65e6df9a38"]]; $this->assertEquals($res20, $obj->toArray()); $obj->setUseHTML(0); $res21 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none", "padding" => 47, "rotation" => 25, "shadow" => 0, "shape" => "8c73a98a300905900337f535531dfca6", "style" => ["style" => "a1b01e734b573fca08eb1a65e6df9a38"], "useHTML" => 0]; $this->assertEquals($res21, $obj->toArray()); $obj->setVerticalAlign("bottom"); $res22 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none", "padding" => 47, "rotation" => 25, "shadow" => 0, "shape" => "8c73a98a300905900337f535531dfca6", "style" => ["style" => "a1b01e734b573fca08eb1a65e6df9a38"], "useHTML" => 0, "verticalAlign" => "bottom"]; $this->assertEquals($res22, $obj->toArray()); $obj->setX(39); $res23 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none", "padding" => 47, "rotation" => 25, "shadow" => 0, "shape" => "8c73a98a300905900337f535531dfca6", "style" => ["style" => "a1b01e734b573fca08eb1a65e6df9a38"], "useHTML" => 0, "verticalAlign" => "bottom", "x" => 39]; $this->assertEquals($res23, $obj->toArray()); $obj->setY(6); $res24 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none", "padding" => 47, "rotation" => 25, "shadow" => 0, "shape" => "8c73a98a300905900337f535531dfca6", "style" => ["style" => "a1b01e734b573fca08eb1a65e6df9a38"], "useHTML" => 0, "verticalAlign" => "bottom", "x" => 39, "y" => 6]; $this->assertEquals($res24, $obj->toArray()); $obj->setZIndex(74); $res25 = ["align" => "right", "allowOverlap" => 1, "backgroundColor" => "930f2a43179a7ae5fc25ed873223e99f", "borderColor" => "97da935a74593c55d78be9d1295aa994", "borderRadius" => 93, "borderWidth" => 71, "className" => "6f66e878c62db60568a3487869695820", "color" => "70dda5dfb8053dc6d1c492574bce9bfd", "crop" => 0, "defer" => 1, "enabled" => 0, "format" => "1ddcb92ade31c8fbd370001f9b29a7d9", "formatter" => "f2ffc59487832cbad265a8fef2133592", "inside" => 1, "overflow" => "none", "padding" => 47, "rotation" => 25, "shadow" => 0, "shape" => "8c73a98a300905900337f535531dfca6", "style" => ["style" => "a1b01e734b573fca08eb1a65e6df9a38"], "useHTML" => 0, "verticalAlign" => "bottom", "x" => 39, "y" => 6, "zIndex" => 74]; $this->assertEquals($res25, $obj->toArray()); } }
lgpl-3.0
lunarnet76/CRUDsader
Form/Component/Association.php
803
<?php namespace CRUDsader\Form\Component { class Association extends \CRUDsader\Form\Component { public function toInput(){ $query=new \CRUDsader\Query('FROM '.$this->_options['class'].(\CRUDsader\Instancer::getInstance()->map->classHasParent($this->_options['class'])?',parent':'')); $html='<select '.$this->getHtmlAttributesToHtml().' ><option value="-1">Select</option>'; foreach($query->fetchAll() as $object){ $html.='<option value="'.$object->isPersisted().'" '.(isset($this->_value) && $this->_value==$object->isPersisted()?'selected="selected"':'').'>'.$object.'</option>'; } return $html.'</select>'; } public function isEmpty(){ return empty($this->_value) || $this->_value == -1; } } }
lgpl-3.0
kingjiang/SharpDevelopLite
src/AddIns/Misc/Debugger/Debugger.AddIn/Project/Src/Service/EditBreakpointScriptForm.cs
2840
/* * Created by SharpDevelop. * User: HP * Date: 25.08.2008 * Time: 09:37 */ using System; using System.IO; using System.Windows.Forms; using ICSharpCode.Core; using ICSharpCode.NRefactory; using ICSharpCode.SharpDevelop.Debugging; using ICSharpCode.SharpDevelop.Project; namespace Debugger.AddIn.Service { /// <summary> /// Description of EditBreakpointScriptForm. /// </summary> public partial class EditBreakpointScriptForm : Form { BreakpointBookmark data; public BreakpointBookmark Data { get { return data; } } public EditBreakpointScriptForm(BreakpointBookmark data) { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); this.data = data; this.data.Action = BreakpointAction.Condition; this.txtCode.Document.TextContent = data.Condition; this.cmbLanguage.Items.AddRange(new string[] { "C#", "VBNET" }); this.cmbLanguage.SelectedIndex = (!string.IsNullOrEmpty(data.ScriptLanguage)) ? this.cmbLanguage.Items.IndexOf(data.ScriptLanguage.ToUpper()) : this.cmbLanguage.Items.IndexOf(ProjectService.CurrentProject.Language.ToUpper()); this.txtCode.SetHighlighting(data.ScriptLanguage.ToUpper()); // Setup translation text this.Text = StringParser.Parse("${res:MainWindow.Windows.Debug.Conditional.Breakpoints.ScriptingWindow.Title}"); this.btnCancel.Text = StringParser.Parse("${res:Global.CancelButtonText}"); this.btnOK.Text = StringParser.Parse("${res:Global.OKButtonText}"); this.label1.Text = StringParser.Parse("${res:MainWindow.Windows.Debug.Conditional.Breakpoints.ScriptingWindow.ScriptingLanguage}") + ":"; this.btnCheckSyntax.Text = StringParser.Parse("${res:MainWindow.Windows.Debug.Conditional.Breakpoints.ScriptingWindow.CheckSyntax}"); } void CmbLanguageSelectedIndexChanged(object sender, EventArgs e) { this.txtCode.SetHighlighting(this.cmbLanguage.SelectedItem.ToString()); this.data.ScriptLanguage = this.cmbLanguage.SelectedItem.ToString(); } void BtnCheckSyntaxClick(object sender, EventArgs e) { CheckSyntax(); } bool CheckSyntax() { SupportedLanguage language = (SupportedLanguage)Enum.Parse(typeof(SupportedLanguage), this.cmbLanguage.SelectedItem.ToString().Replace("#", "Sharp"), true); using (IParser parser = ParserFactory.CreateParser(language, new StringReader(this.txtCode.Document.TextContent))) { parser.ParseExpression(); if (parser.Errors.Count > 0) { MessageService.ShowError(parser.Errors.ErrorOutput); return false; } } return true; } void BtnOKClick(object sender, EventArgs e) { if (!this.CheckSyntax()) return; this.data.Condition = this.txtCode.Document.TextContent; this.DialogResult = DialogResult.OK; this.Close(); } } }
lgpl-3.0
MyanmarAPI/election-website
resources/views/auth/password.blade.php
1422
@extends('layouts.default') @section('title', 'Reset Password') @section('content') <div class="row app-container mg-top"> <div class="col s6 offset-s3"> <div class="z-depth-1 box" id="login"> <h4 class="box-header mps-blue mps-yellow-text">Reset Password</h4> @if (session('status')) <div class="alert alert-success"> {{ session('status') }} </div> @endif {!! Form::open(['url' => '/password/email', 'autocomplete' => 'false', 'class' => 'form']) !!} <div class="row"> <div class="input-field col s12"> <input type="email" name="email" value="{{ old('email') }}" autocomplete="off" class="validate {{ $errors->has('email') ? 'invalid' : '' }}"> <label for="email">Email</label> <p class="form-error">{{ $errors->first('email') }}</p> </div> </div> <div class="row"> <div class="input-field col s12"> <button class="btn waves-effect waves-light indigo darken-2" type="submit" name="action" data-ga-event="Button|Click|SubmitSendPasswordResetLink"> Send Password Reset Link </button> </div> </div> {!! Form::close() !!} </div> <!-- end of div#login --> <p class="center-align"> Don't have an account? Sign Up for <a href="{{ url('auth/register') }}" data-ga-event="Link|Click|RegsiterFromPasswordReset">New Account</a> </p> </div> </div> @endsection
lgpl-3.0
slavat/MailSystem.NET
Class Library/ActiveUp.Net.Common/Events.cs
23078
// Copyright 2001-2010 - Active Up SPRLU (http://www.agilecomponents.com) // // This file is part of MailSystem.NET. // MailSystem.NET is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // MailSystem.NET 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 SharpMap; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA namespace ActiveUp.Net.Mail { #region Events Handling /*/// <summary> /// EventHandler to be used with the Progress event. /// </summary> public delegate void ProgressEventHandler(object sender, ActiveUp.Net.Mail.ProgressEventArgs e);*/ /// <summary> /// EventHandler to be used with the Authenticating event. /// </summary> public delegate void AuthenticatingEventHandler(object sender, ActiveUp.Net.Mail.AuthenticatingEventArgs e); /// <summary> /// EventHandler to be used with the Authenticated event. /// </summary> public delegate void AuthenticatedEventHandler(object sender, ActiveUp.Net.Mail.AuthenticatedEventArgs e); /// <summary> /// EventHandler to be used with the Nooping event. /// </summary> public delegate void NoopingEventHandler(object sender); /// <summary> /// EventHandler to be used with the Nooped event. /// </summary> public delegate void NoopedEventHandler(object sender); /// <summary> /// EventHandler to be used with the TcpWriting event. /// </summary> public delegate void TcpWritingEventHandler(object sender, ActiveUp.Net.Mail.TcpWritingEventArgs e); /// <summary> /// EventHandler to be used with the TcpWritten event. /// </summary> public delegate void TcpWrittenEventHandler(object sender, ActiveUp.Net.Mail.TcpWrittenEventArgs e); /// <summary> /// EventHandler to be used with the TcpReading event. /// </summary> public delegate void TcpReadingEventHandler(object sender); /// <summary> /// EventHandler to be used with the TcpRead event. /// </summary> public delegate void TcpReadEventHandler(object sender, ActiveUp.Net.Mail.TcpReadEventArgs e); /// <summary> /// EventHandler to be used with the MessageRetrieving event. /// </summary> public delegate void MessageRetrievingEventHandler(object sender, ActiveUp.Net.Mail.MessageRetrievingEventArgs e); /// <summary> /// EventHandler to be used with the MessageRetrieved event. /// </summary> public delegate void MessageRetrievedEventHandler(object sender, ActiveUp.Net.Mail.MessageRetrievedEventArgs e); /*/// <summary> /// EventHandler to be used with the BodyRetrieving event. /// </summary> public delegate void BodyRetrievingEventHandler(object sender, ActiveUp.Net.Mail.BodyRetrievingEventArgs e); /// <summary> /// EventHandler to be used with the BodyRetrieved event. /// </summary> public delegate void BodyRetrievedEventHandler(object sender, ActiveUp.Net.Mail.BodyRetrievedEventArgs e); /// <summary> /// EventHandler to be used with the ArticleRetrieving event. /// </summary> public delegate void ArticleRetrievingEventHandler(object sender, ActiveUp.Net.Mail.ArticleRetrievingEventArgs e); /// <summary> /// EventHandler to be used with the ArticleRetrieved event. /// </summary> public delegate void ArticleRetrievedEventHandler(object sender, ActiveUp.Net.Mail.ArticleRetrievedEventArgs e);*/ /// <summary> /// EventHandler to be used with the HeaderRetrieving event. /// </summary> public delegate void HeaderRetrievingEventHandler(object sender, ActiveUp.Net.Mail.HeaderRetrievingEventArgs e); /// <summary> /// EventHandler to be used with the HeaderRetrieved event. /// </summary> public delegate void HeaderRetrievedEventHandler(object sender, ActiveUp.Net.Mail.HeaderRetrievedEventArgs e); /// <summary> /// EventHandler to be used with the Disconnecting event. /// </summary> public delegate void DisconnectingEventHandler(object sender); /// <summary> /// EventHandler to be used with the Disconnected event. /// </summary> public delegate void DisconnectedEventHandler(object sender, ActiveUp.Net.Mail.DisconnectedEventArgs e); /// <summary> /// EventHandler to be used with the Connecting event. /// </summary> public delegate void ConnectingEventHandler(object sender); /// <summary> /// EventHandler to be used with the Connected event. /// </summary> public delegate void ConnectedEventHandler(object sender, ActiveUp.Net.Mail.ConnectedEventArgs e); /// <summary> /// EventHandler to be used with the MessageSending event. /// </summary> public delegate void MessageSendingEventHandler(object sender, ActiveUp.Net.Mail.MessageSendingEventArgs e); /// <summary> /// EventHandler to be used with the MessageSent event. /// </summary> public delegate void MessageSentEventHandler(object sender, ActiveUp.Net.Mail.MessageSentEventArgs e); /// <summary> /// EventHandler to be used with the NewMessage event. /// </summary> public delegate void NewMessageReceivedEventHandler(object sender, ActiveUp.Net.Mail.NewMessageReceivedEventArgs e); /// <summary> /// EventArgs used by the Disconnected event. /// </summary> #if !PocketPC [System.Serializable] #endif public class DisconnectedEventArgs : System.EventArgs { private string serverresponse; /// <summary> /// Constructor. /// </summary> /// <param name="serverresponse">The remote server's response.</param> public DisconnectedEventArgs(string serverresponse) { this.serverresponse = serverresponse; } /// <summary> /// The remote server's response. /// </summary> public string ServerResponse { get { return this.serverresponse; } } } /// <summary> /// EventArgs used by the Connected event. /// </summary> #if !PocketPC [System.Serializable] #endif public class ConnectedEventArgs : System.EventArgs { private string serverresponse; //private bool connected; /// <summary> /// Constructor. /// </summary> /// <param name="serverresponse">The remote server's response.</param> public ConnectedEventArgs(string serverresponse) { this.serverresponse = serverresponse; } /// <summary> /// The remote server's response. /// </summary> public string ServerResponse { get { return this.serverresponse; } } } /// <summary> /// EventArgs used by the MessageRetrieved event. /// </summary> #if !PocketPC [System.Serializable] #endif public class MessageRetrievedEventArgs : System.EventArgs { byte[] _data; int _index; int _totalCount; /// <summary> /// Constructor. /// </summary> /// <param name="data">The retrieved message as a byte array.</param> /// <param name="index">The index of the message that has been retrieved.</param> /// <param name="totalCount">The total amount of messages on the remote server (POP3 only).</param> public MessageRetrievedEventArgs(byte[] data, int index, int totalCount) { this._data = data; this._index = index; this._totalCount = totalCount; } /// <summary> /// Constructor. /// </summary> /// <param name="data">The retrieved message as a byte array.</param> /// <param name="index">The index of the message that has been retrieved.</param> public MessageRetrievedEventArgs(byte[] data, int index) { this._data = data; this._index = index; this._totalCount = -1; } /// <summary> /// The retrieved message as a Message object. /// </summary> public ActiveUp.Net.Mail.Message Message { get { return ActiveUp.Net.Mail.Parser.ParseMessage(this._data); } } /// <summary> /// The retrieved message's index on the remote server. /// </summary> public int MessageIndex { get { return this._index; } } /// <summary> /// The total amount of messages on the remote server (POP3 only). /// </summary> public int TotalCount { get { return this._totalCount; } } } /// <summary> /// EventArgs used by the MessageRetrieving event. /// </summary> #if !PocketPC [System.Serializable] #endif public class MessageRetrievingEventArgs : System.EventArgs { int _index; int _totalCount; /// <summary> /// Constructor. /// </summary> /// <param name="index">The message to be retrieved's index.</param> /// <param name="totalCount">The total amount of messages on the remote server.</param> public MessageRetrievingEventArgs(int index, int totalCount) { this._index = index; this._totalCount = totalCount; } /// <summary> /// Constructor. /// </summary> /// <param name="index">The message to be retrieved's index.</param> public MessageRetrievingEventArgs(int index) { this._index = index; this._totalCount = -1; } /// <summary> /// The index of the message to be retrieved on the remote server. /// </summary> public int MessageIndex { get { return this._index; } } /// <summary> /// The total amount of messages on the remote server (POP3 only). /// </summary> public int TotalCount { get { return this._totalCount; } } } /*/// <summary> /// EventArgs used by the Progress event. /// </summary> [System.Serializable] public class ProgressEventArgs : System.EventArgs { int _bytesRead; int _totalBytes; int _totalSize; /// <summary> /// Constructor. /// </summary> /// <param name="bytesRead">The amount of bytes read from the remote server since the event has been fired.</param> /// <param name="totalBytes">The total amount of bytes read from the server during the operation up to now.</param> /// <param name="totalSize">The total amount of bytes to be downloaded during the operation.</param> public ProgressEventArgs(int bytesRead, int totalBytes, int totalSize) { this._bytesRead = bytesRead; this._totalBytes = totalBytes; this._totalSize = totalSize; } /// <summary> /// The amount of bytes read from the remote server since the last event firing. /// </summary> public int BytesRead { get { return this._bytesRead; } } /// <summary> /// The total amount of bytes read from the remote server in this operation. /// </summary> public int TotalBytes { get { return this._totalBytes; } } /// <summary> /// The total amount of bytes to be read from the remote server in this operation. /// </summary> public int TotalSize { get { return this._totalSize; } } }*/ /// <summary> /// EventArgs used by the HeaderRetrieved event. /// </summary> #if !PocketPC [System.Serializable] #endif public class HeaderRetrievedEventArgs : System.EventArgs { byte[] _data; int _index; int _totalCount = -1; /// <summary> /// Event /// </summary> /// <param name="data">The retrieved Header as a byte array.</param> /// <param name="index">The index of the Header retrieved.</param> /// <param name="totalCount">The total amount of messages on the remote server (POP3 only).</param> public HeaderRetrievedEventArgs(byte[] data, int index, int totalCount) { this._index = index; this._totalCount = totalCount; this._data = data; } /// <summary> /// Event /// </summary> /// <param name="data">The retrieved Header as a byte array.</param> /// <param name="index">The index of the retrieved header.</param> public HeaderRetrievedEventArgs(byte[] data, int index) { this._index = index; this._data = data; this._totalCount = -1; } /// <summary> /// The Header retrieved from the remote server. /// </summary> public ActiveUp.Net.Mail.Header Header { get { return ActiveUp.Net.Mail.Parser.ParseHeader(this._data); } } /// <summary> /// The index of the message Header retrieved on the remote server. /// </summary> public int MessageIndex { get { return this._index; } } /// <summary> /// The total amount of messages on the remote server (POP3 only). /// </summary> public int TotalCount { get { return this._totalCount; } } } /// <summary> /// EventArgs used by the HeaderRetrieving event. /// </summary> #if !PocketPC [System.Serializable] #endif public class HeaderRetrievingEventArgs : System.EventArgs { int _index; int _totalCount = -1; /// <summary> /// Constructor. /// </summary> public HeaderRetrievingEventArgs(int index, int totalCount) { this._index = index; this._totalCount = totalCount; } /// <summary> /// Constructor. /// </summary> public HeaderRetrievingEventArgs(int index) { this._index = index; } /// <summary> /// The index of the message Header to be retrieved on the remote server. /// </summary> public int MessageIndex { get { return this._index; } } /// <summary> /// The total amount of messages on the remote server (POP3 only). /// </summary> public int TotalCount { get { return this._totalCount; } } } /// <summary> /// EventArgs used by the TcpWritten event. /// </summary> #if !PocketPC [System.Serializable] #endif public class TcpWrittenEventArgs : System.EventArgs { string _data; /// <summary> /// Constructor. /// </summary> /// <param name="data">Data sent to the server.</param> public TcpWrittenEventArgs(string data) { this._data = data; } /// <summary> /// Data sent to the server. /// </summary> public string Command { get { return this._data; } } } /// <summary> /// EventArgs used by the TcpWriting event. /// </summary> #if !PocketPC [System.Serializable] #endif public class TcpWritingEventArgs : System.EventArgs { string _data; /// <summary> /// Constructor. /// </summary> /// <param name="data">Data sent to the server.</param> public TcpWritingEventArgs(string data) { this._data = data; } /// <summary> /// Data sent to the server. /// </summary> public string Command { get { return this._data; } } } /// <summary> /// EventArgs used by the TcpRead event. /// </summary> #if !PocketPC [System.Serializable] #endif public class TcpReadEventArgs : System.EventArgs { string _data; /// <summary> /// Constructor. /// </summary> /// <param name="data">Data received from the server.</param> public TcpReadEventArgs(string data) { this._data = data; } /// <summary> /// The server's response. /// </summary> public string Response { get { return this._data; } } } /// <summary> /// Represents an authentication process. /// </summary> #if !PocketPC [System.Serializable] #endif public class AuthenticatedEventArgs : System.EventArgs { string _username,_password,_host,_serverResponse; /// <summary> /// Constructor. /// </summary> /// <param name="username">Username used to authenticate the user.</param> /// <param name="password">Password used to authenticate the user.</param> /// <param name="host">Address of the remote server.</param> /// <param name="serverResponse">The server response to the PASS command.</param> public AuthenticatedEventArgs(string username, string password, string host, string serverResponse) { this._username = username; this._password = password; this._host = host; this._serverResponse = serverResponse; } /// <summary> /// Constructor. /// </summary> /// <param name="username">Username used to authenticate the user.</param> /// <param name="password">Password used to authenticate the user.</param> /// <param name="serverResponse">The server response to the PASS command.</param> public AuthenticatedEventArgs(string username, string password, string serverResponse) { this._username = username; this._password = password; this._host = "unknown"; this._serverResponse = serverResponse; } /// <summary> /// The username used to authenticate the user. /// </summary> public string Username { get { return this._username; } } /// <summary> /// The password used to authenticate the user. /// </summary> public string Password { get { return this._username; } } /// <summary> /// The address of the remote server. /// </summary> public string Host { get { return this._host; } } /// <summary> /// The server's response /// </summary> public string ServerResponse { get { return this._serverResponse; } } } /// <summary> /// Represents a future authentication process. /// </summary> #if !PocketPC [System.Serializable] #endif public class AuthenticatingEventArgs : System.EventArgs { string _username,_password,_host; /// <summary> /// Constructor. /// </summary> /// <param name="username">Username used to authenticate the user.</param> /// <param name="password">Password used to authenticate the user.</param> /// <param name="host">Address of the remote server.</param> public AuthenticatingEventArgs(string username, string password, string host) { this._username = username; this._password = password; this._host = host; } /// <summary> /// Constructor. /// </summary> /// <param name="username">Username used to authenticate the user.</param> /// <param name="password">Password used to authenticate the user.</param> public AuthenticatingEventArgs(string username, string password) { this._username = username; this._password = password; this._host = "unkwown"; } /// <summary> /// The username used to authenticate the user. /// </summary> public string Username { get { return this._username; } } /// <summary> /// The password used to authenticate the user. /// </summary> public string Password { get { return this._password; } } /// <summary> /// The address of the remote server. /// </summary> public string Host { get { return this._host; } } } /*/// <summary> /// EventArgs used by the ArticleRetrieved event. /// </summary> [System.Serializable] public class ArticleRetrievedEventArgs : System.EventArgs { ActiveUp.Net.Mail.Message _message; int _index; /// <summary> /// Constructor. /// </summary> /// <param name="data">The retrieved article as a byte array.</param> /// <param name="index">The index of the article that has been retrieved.</param> public ArticleRetrievedEventArgs(ActiveUp.Net.Mail.Message article, int index) { this._message = article; this._index = index; } /// <summary> /// The retrieved message as a byte array. /// </summary> public ActiveUp.Net.Mail.Message Article { get { return this._message; } } /// <summary> /// The retrieved article's index on the remote server. /// </summary> public int MessageIndex { get { return this._index; } } } /// <summary> /// EventArgs used by the ArticleRetrieving event. /// </summary> [System.Serializable] public class ArticleRetrievingEventArgs : System.EventArgs { int _index; /// <summary> /// Constructor. /// </summary> /// <param name="index">The message to be retrieved's index.</param> public ArticleRetrievingEventArgs(int index) { this._index = index; } /// <summary> /// The index of the article to be retrieved on the remote server. /// </summary> public int MessageIndex { get { return this._index; } } } /// <summary> /// EventArgs used by the BodyRetrieved event. /// </summary> [System.Serializable] public class BodyRetrievedEventArgs : System.EventArgs { byte[] _data; int _index; /// <summary> /// Event /// </summary> /// <param name="data">The retrieved data as a byte array.</param> /// <param name="index">The index of the body retrieved.</param> public BodyRetrievedEventArgs(byte[] data, int index) { this._index = index; this._data = data; } /// <summary> /// The body retrieved from the remote server. /// </summary> public byte[] Data { get { return this._data; } } /// <summary> /// The index of the article body retrieved on the remote server. /// </summary> public int MessageIndex { get { return this._index; } } } /// <summary> /// EventArgs used by the BodyRetrieving event. /// </summary> [System.Serializable] public class BodyRetrievingEventArgs : System.EventArgs { int _index; /// <summary> /// Event /// </summary> /// <param name="index">The index of the body retrieved.</param> public BodyRetrievingEventArgs(int index) { this._index = index; } /// <summary> /// The index of the article body to be retrieved on the remote server. /// </summary> public int MessageIndex { get { return this._index; } } }*/ /// <summary> /// EventArgs used by the MessageSending event. /// </summary> #if !PocketPC [System.Serializable] #endif public class MessageSendingEventArgs : System.EventArgs { ActiveUp.Net.Mail.Message _message; /// <summary> /// Event fired when a message is going to be sent. /// </summary> /// <param name="index">The message to be sent.</param> public MessageSendingEventArgs(ActiveUp.Net.Mail.Message message) { this._message = message; } /// <summary> /// The message to be sent. /// </summary> public ActiveUp.Net.Mail.Message Message { get { return this._message; } } } /// <summary> /// EventArgs used by the MessageSent event. /// </summary> #if !PocketPC [System.Serializable] #endif public class MessageSentEventArgs : System.EventArgs { ActiveUp.Net.Mail.Message _message; /// <summary> /// Event fired when a message has been sent. /// </summary> /// <param name="message">The message that has been sent.</param> public MessageSentEventArgs(ActiveUp.Net.Mail.Message message) { this._message = message; } /// <summary> /// The message that has been sent. /// </summary> public ActiveUp.Net.Mail.Message Message { get { return this._message; } } } /// <summary> /// EventArgs used by the NewMessage event. /// </summary> #if !PocketPC [System.Serializable] #endif public class NewMessageReceivedEventArgs : System.EventArgs { int _messageCount; /// <summary> /// Event fired when a new message received. /// </summary> /// <param name="messageCount">The number of new messages received.</param> public NewMessageReceivedEventArgs(int messageCount) { this._messageCount = messageCount; } /// <summary> /// The number of new messages received. /// </summary> public int MessageCount { get { return this._messageCount; } } } #endregion }
lgpl-3.0
FrischerHering/Burngine
include/glm/core/func_vector_relational.hpp
7138
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net) /// 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. /// /// @ref core /// @file glm/core/func_vector_relational.hpp /// @date 2008-08-03 / 2011-06-15 /// @author Christophe Riccio /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> /// /// @defgroup core_func_vector_relational Vector Relational Functions /// @ingroup core /// /// Relational and equality operators (<, <=, >, >=, ==, !=) are defined to /// operate on scalars and produce scalar Boolean results. For vector results, /// use the following built-in functions. /// /// In all cases, the sizes of all the input and return vectors for any particular /// call must match. /////////////////////////////////////////////////////////////////////////////////// #ifndef GLM_CORE_func_vector_relational #define GLM_CORE_func_vector_relational GLM_VERSION #include "_detail.hpp" namespace glm { /// @addtogroup core_func_vector_relational /// @{ /// Returns the component-wise comparison result of x < y. /// /// @tparam vecType Floating-point or integer vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/lessThan.xml">GLSL lessThan man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template<typename vecType> GLM_FUNC_DECL typename vecType::bool_type lessThan( vecType const & x, vecType const & y); /// Returns the component-wise comparison of result x <= y. /// /// @tparam vecType Floating-point or integer vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/lessThanEqual.xml">GLSL lessThanEqual man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template<typename vecType> GLM_FUNC_DECL typename vecType::bool_type lessThanEqual(vecType const & x, vecType const & y); /// Returns the component-wise comparison of result x > y. /// /// @tparam vecType Floating-point or integer vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/greaterThan.xml">GLSL greaterThan man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template<typename vecType> GLM_FUNC_DECL typename vecType::bool_type greaterThan( vecType const & x, vecType const & y); /// Returns the component-wise comparison of result x >= y. /// /// @tparam vecType Floating-point or integer vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/greaterThanEqual.xml">GLSL greaterThanEqual man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template<typename vecType> GLM_FUNC_DECL typename vecType::bool_type greaterThanEqual( vecType const & x, vecType const & y); /// Returns the component-wise comparison of result x == y. /// /// @tparam vecType Floating-point, integer or boolean vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/equal.xml">GLSL equal man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template<typename vecType> GLM_FUNC_DECL typename vecType::bool_type equal(vecType const & x, vecType const & y); /// Returns the component-wise comparison of result x != y. /// /// @tparam vecType Floating-point, integer or boolean vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/notEqual.xml">GLSL notEqual man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template<typename vecType> GLM_FUNC_DECL typename vecType::bool_type notEqual( vecType const & x, vecType const & y); /// Returns true if any component of x is true. /// /// @tparam vecType Boolean vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/any.xml">GLSL any man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template<template<typename > class vecType> GLM_FUNC_DECL bool any(vecType<bool> const & v); /// Returns true if all components of x are true. /// /// @tparam vecType Boolean vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/all.xml">GLSL all man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template<template<typename > class vecType> GLM_FUNC_DECL bool all(vecType<bool> const & v); /// Returns the component-wise logical complement of x. /// /!\ Because of language incompatibilities between C++ and GLSL, GLM defines the function not but not_ instead. /// /// @tparam vecType Boolean vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/not.xml">GLSL not man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template<template<typename > class vecType> GLM_FUNC_DECL vecType<bool> not_(vecType<bool> const & v); /// @} }//namespace glm #include "func_vector_relational.inl" #endif//GLM_CORE_func_vector_relational
lgpl-3.0
vrsys/avango
avango-gua/python/avango/gua/renderer/LightVisibilityPassDescription.hpp
228
#ifndef AV_PYTHON_GUA_LIGHT_VISIBILITY_PASS_DESCRIPTION_HPP #define AV_PYTHON_GUA_LIGHT_VISIBILITY_PASS_DESCRIPTION_HPP void init_LightVisibilityPassDescription(); #endif // AV_PYTHON_GUA_LIGHT_VISIBILITY_PASS_DESCRIPTION_HPP
lgpl-3.0
TuranicTeam/Turanic
src/pocketmine/block/Fire.php
7147
<?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 TuranicTeam * @link https://github.com/TuranicTeam/Turanic * */ declare(strict_types=1); namespace pocketmine\block; use pocketmine\entity\Living; use pocketmine\entity\projectile\Arrow; use pocketmine\entity\Effect; use pocketmine\entity\Entity; use pocketmine\event\block\BlockBurnEvent; use pocketmine\event\entity\EntityCombustByBlockEvent; use pocketmine\event\entity\EntityDamageByBlockEvent; use pocketmine\event\entity\EntityDamageEvent; use pocketmine\item\Item; use pocketmine\level\Level; use pocketmine\math\Vector3; use pocketmine\Server; class Fire extends Flowable { protected $id = self::FIRE; /** @var Vector3 */ private $temporalVector = null; public function __construct($meta = 0){ $this->meta = $meta; if($this->temporalVector === null){ $this->temporalVector = new Vector3(0, 0, 0); } } public function hasEntityCollision() : bool{ return true; } public function getName() : string{ return "Fire Block"; } public function getLightLevel() : int{ return 15; } public function isBreakable(Item $item) : bool{ return false; } public function canBeReplaced() : bool{ return true; } public function ticksRandomly(): bool{ return true; } /** * @param Entity $entity */ public function onEntityCollide(Entity $entity){ $ev = new EntityDamageByBlockEvent($this, $entity, EntityDamageEvent::CAUSE_FIRE, 1); $entity->attack($ev); $ev = new EntityCombustByBlockEvent($this, $entity, 8); if($entity instanceof Arrow){ $ev->setCancelled(); } Server::getInstance()->getPluginManager()->callEvent($ev); if(!$ev->isCancelled()){ $entity->setOnFire($ev->getDuration()); } } public function getDropsForCompatibleTool(Item $item) : array{ return []; } public function onUpdate(int $type){ if($type == Level::BLOCK_UPDATE_NORMAL or $type == Level::BLOCK_UPDATE_RANDOM or $type == Level::BLOCK_UPDATE_SCHEDULED){ if(!$this->getSide(Vector3::SIDE_DOWN)->isTopFacingSurfaceSolid() and !$this->canNeighborBurn()){ $this->getLevel()->setBlock($this, new Air(), true); return Level::BLOCK_UPDATE_NORMAL; }elseif($type == Level::BLOCK_UPDATE_NORMAL or $type == Level::BLOCK_UPDATE_RANDOM){ $this->getLevel()->scheduleDelayedBlockUpdate($this, $this->getTickRate() + mt_rand(0, 10)); }elseif($type == Level::BLOCK_UPDATE_SCHEDULED and $this->getLevel()->getServer()->fireSpread){ $forever = $this->getSide(Vector3::SIDE_DOWN)->getId() == Block::NETHERRACK; //TODO: END if(!$this->getSide(Vector3::SIDE_DOWN)->isTopFacingSurfaceSolid() and !$this->canNeighborBurn()){ $this->getLevel()->setBlock($this, new Air(), true); } if(!$forever and $this->getLevel()->getWeather()->isRainy() and ($this->getLevel()->canBlockSeeSky($this) or $this->getLevel()->canBlockSeeSky($this->getSide(Vector3::SIDE_EAST)) or $this->getLevel()->canBlockSeeSky($this->getSide(Vector3::SIDE_WEST)) or $this->getLevel()->canBlockSeeSky($this->getSide(Vector3::SIDE_SOUTH)) or $this->getLevel()->canBlockSeeSky($this->getSide(Vector3::SIDE_NORTH)) ) ){ $this->getLevel()->setBlock($this, new Air(), true); }else{ $meta = $this->meta; if($meta < 15){ $this->meta = $meta + mt_rand(0, 3); $this->getLevel()->setBlock($this, $this, true); } $this->getLevel()->scheduleDelayedBlockUpdate($this, $this->getTickRate() + mt_rand(0, 10)); if(!$forever and !$this->canNeighborBurn()){ if(!$this->getSide(Vector3::SIDE_DOWN)->isTopFacingSurfaceSolid() or $meta > 3){ $this->getLevel()->setBlock($this, new Air(), true); } }elseif(!$forever && !($this->getSide(Vector3::SIDE_DOWN)->getBurnAbility() > 0) && $meta >= 15 && mt_rand(0, 4) == 0){ $this->getLevel()->setBlock($this, new Air(), true); }else{ $o = 0; //TODO: decrease the o if the rainfall values are high $this->tryToCatchBlockOnFire($this->getSide(Vector3::SIDE_EAST), 300 + $o, $meta); $this->tryToCatchBlockOnFire($this->getSide(Vector3::SIDE_WEST), 300 + $o, $meta); $this->tryToCatchBlockOnFire($this->getSide(Vector3::SIDE_DOWN), 250 + $o, $meta); $this->tryToCatchBlockOnFire($this->getSide(Vector3::SIDE_UP), 250 + $o, $meta); $this->tryToCatchBlockOnFire($this->getSide(Vector3::SIDE_SOUTH), 300 + $o, $meta); $this->tryToCatchBlockOnFire($this->getSide(Vector3::SIDE_NORTH), 300 + $o, $meta); for($x = ($this->x - 1); $x <= ($this->x + 1); ++$x){ for($z = ($this->z - 1); $z <= ($this->z + 1); ++$z){ for($y = ($this->y - 1); $y <= ($this->y + 4); ++$y){ $k = 100; if($y > $this->y + 1){ $k += ($y - ($this->y + 1)) * 100; } $chance = $this->getChanceOfNeighborsEncouragingFire($this->getLevel()->getBlockAt($x, $y, $z)); if($chance > 0){ $t = ($chance + 40 + $this->getLevel()->getServer()->getDifficulty() * 7); //TODO: decrease t if the rainfall values are high if($t > 0 and mt_rand(0, $k) <= $t){ $damage = min(15, $meta + mt_rand(0, 5) / 4); $this->getLevel()->setBlock($this->temporalVector->setComponents($x, $y, $z), new Fire($damage), true); $this->getLevel()->scheduleDelayedBlockUpdate($this->temporalVector, $this->getTickRate()); } } } } } } } } } return 0; } /** * @return int */ public function getTickRate() : int{ return 30; } /** * @param Block $block * @param int $bound * @param int $damage */ private function tryToCatchBlockOnFire(Block $block, int $bound, int $damage){ $burnAbility = $block->getBurnAbility(); if(mt_rand(0, $bound) < $burnAbility){ if(mt_rand(0, $damage + 10) < 5){ $meta = max(15, $damage + mt_rand(0, 4) / 4); $this->getLevel()->getServer()->getPluginManager()->callEvent($ev = new BlockBurnEvent($block)); if(!$ev->isCancelled()){ $this->getLevel()->setBlock($block, $fire = new Fire($meta), true); $this->getLevel()->scheduleDelayedBlockUpdate($block, $fire->getTickRate()); } }else{ $this->getLevel()->setBlock($this, new Air(), true); } if($block instanceof TNT){ $block->prime(); } } } /** * @param Block $block * * @return int|mixed */ private function getChanceOfNeighborsEncouragingFire(Block $block){ if($block->getId() !== self::AIR){ return 0; }else{ $chance = 0; for($i = 0; $i < 5; $i++){ $chance = max($chance, $block->getSide($i)->getBurnChance()); } return $chance; } } }
lgpl-3.0
gallettigr/cypress
core/assets/js/libs/loader.js
17368
jQuery.cyloader = function() { var a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X = [].slice, Y = {}.hasOwnProperty, Z = function (a, b) { function c() { this.constructor = a } for (var d in b) Y.call(b, d) && (a[d] = b[d]); return c.prototype = b.prototype, a.prototype = new c, a.__super__ = b.prototype, a }, $ = [].indexOf || function (a) { for (var b = 0, c = this.length; c > b; b++) if (b in this && this[b] === a) return b; return -1 }; for (u = { catchupTime: 100, initialRate: .03, minTime: 250, ghostTime: 100, maxProgressPerFrame: 20, easeFactor: 1.25, startOnPageLoad: !0, restartOnPushState: !0, restartOnRequestAfter: 500, target: "body", elements: { checkInterval: 100, selectors: ["body"] }, eventLag: { minSamples: 10, sampleCount: 3, lagThreshold: 3 }, ajax: { trackMethods: ["GET"], trackWebSockets: !0, ignoreURLs: [] } }, C = function () { var a; return null != (a = "undefined" != typeof performance && null !== performance && "function" == typeof performance.now ? performance.now() : void 0) ? a : +new Date }, E = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame, t = window.cancelAnimationFrame || window.mozCancelAnimationFrame, null == E && (E = function (a) { return setTimeout(a, 50) }, t = function (a) { return clearTimeout(a) }), G = function (a) { var b, c; return b = C(), (c = function () { var d; return d = C() - b, d >= 33 ? (b = C(), a(d, function () { return E(c) })) : setTimeout(c, 33 - d) })() }, F = function () { var a, b, c; return c = arguments[0], b = arguments[1], a = 3 <= arguments.length ? X.call(arguments, 2) : [], "function" == typeof c[b] ? c[b].apply(c, a) : c[b] }, v = function () { var a, b, c, d, e, f, g; for (b = arguments[0], d = 2 <= arguments.length ? X.call(arguments, 1) : [], f = 0, g = d.length; g > f; f++) if (c = d[f]) for (a in c) Y.call(c, a) && (e = c[a], null != b[a] && "object" == typeof b[a] && null != e && "object" == typeof e ? v(b[a], e) : b[a] = e); return b }, q = function (a) { var b, c, d, e, f; for (c = b = 0, e = 0, f = a.length; f > e; e++) d = a[e], c += Math.abs(d), b++; return c / b }, x = function (a, b) { var c, d, e; if (null == a && (a = "options"), null == b && (b = !0), e = document.querySelector("[data-loader-" + a + "]")) { if (c = e.getAttribute("data-loader-" + a), !b) return c; try { return JSON.parse(c) } catch (f) { return d = f, "undefined" != typeof console && null !== console ? console.error("Error parsing inline loader options.", d) : void 0 } } }, g = function () { function a() {} return a.prototype.on = function (a, b, c, d) { var e; return null == d && (d = !1), null == this.bindings && (this.bindings = {}), null == (e = this.bindings)[a] && (e[a] = []), this.bindings[a].push({ handler: b, ctx: c, once: d }) }, a.prototype.once = function (a, b, c) { return this.on(a, b, c, !0) }, a.prototype.off = function (a, b) { var c, d, e; if (null != (null != (d = this.bindings) ? d[a] : void 0)) { if (null == b) return delete this.bindings[a]; for (c = 0, e = []; c < this.bindings[a].length;) e.push(this.bindings[a][c].handler === b ? this.bindings[a].splice(c, 1) : c++); return e } }, a.prototype.trigger = function () { var a, b, c, d, e, f, g, h, i; if (c = arguments[0], a = 2 <= arguments.length ? X.call(arguments, 1) : [], null != (g = this.bindings) ? g[c] : void 0) { for (e = 0, i = []; e < this.bindings[c].length;) h = this.bindings[c][e], d = h.handler, b = h.ctx, f = h.once, d.apply(null != b ? b : this, a), i.push(f ? this.bindings[c].splice(e, 1) : e++); return i } }, a }(), j = window.CyLoader || {}, window.CyLoader = j, v(j, g.prototype), D = j.options = v({}, u, window.cyloaderOptions, x()), U = ["ajax", "document", "eventLag", "elements"], Q = 0, S = U.length; S > Q; Q++) K = U[Q], D[K] === !0 && (D[K] = u[K]); i = function (a) { function b() { return V = b.__super__.constructor.apply(this, arguments) } return Z(b, a), b }(Error), b = function () { function a() { this.progress = 0 } return a.prototype.getElement = function () { var a; if (null == this.el) { if (a = document.querySelector(D.target), !a) throw new i; this.el = document.createElement("div"), this.el.className = "loader", document.body.className = document.body.className.replace('loaded', 'loading'), document.body.className += " loading", this.el.innerHTML = '<div class="progress">\n<div class="inner"></div>\n</div>', null != a.firstChild ? a.insertBefore(this.el, a.firstChild) : a.appendChild(this.el) } return this.el }, a.prototype.finish = function () { var a; return a = this.getElement(), document.body.className = document.body.className.replace("loading", "loaded") }, a.prototype.update = function (a) { return this.progress = a, this.render() }, a.prototype.destroy = function () { try { this.getElement() .parentNode.removeChild(this.getElement()) } catch (a) { i = a } return this.el = void 0 }, a.prototype.render = function () { var a, b, c, d, e, f, g; if (null == document.querySelector(D.target)) return !1; for (a = this.getElement(), d = "translate3d(" + this.progress + "%, 0, 0)", g = ["webkitTransform", "msTransform", "transform"], e = 0, f = g.length; f > e; e++) b = g[e], a.children[0].style[b] = d; return (!this.lastRenderedProgress || this.lastRenderedProgress | 0 !== this.progress | 0) && (a.children[0].setAttribute("data-percentage", "" + (0 | this.progress) + "%"), this.progress >= 100 ? c = "99" : (c = this.progress < 10 ? "0" : "", c += 0 | this.progress), a.children[0].setAttribute("data-progress", "" + c)), this.lastRenderedProgress = this.progress }, a.prototype.done = function () { return this.progress >= 100 }, a }(), h = function () { function a() { this.bindings = {} } return a.prototype.trigger = function (a, b) { var c, d, e, f, g; if (null != this.bindings[a]) { for (f = this.bindings[a], g = [], d = 0, e = f.length; e > d; d++) c = f[d], g.push(c.call(this, b)); return g } }, a.prototype.on = function (a, b) { var c; return null == (c = this.bindings)[a] && (c[a] = []), this.bindings[a].push(b) }, a }(), P = window.XMLHttpRequest, O = window.XDomainRequest, N = window.WebSocket, w = function (a, b) { var c, d, e, f; f = []; for (d in b.prototype) try { e = b.prototype[d], f.push(null == a[d] && "function" != typeof e ? a[d] = e : void 0) } catch (g) { c = g } return f }, A = [], j.ignore = function () { var a, b, c; return b = arguments[0], a = 2 <= arguments.length ? X.call(arguments, 1) : [], A.unshift("ignore"), c = b.apply(null, a), A.shift(), c }, j.track = function () { var a, b, c; return b = arguments[0], a = 2 <= arguments.length ? X.call(arguments, 1) : [], A.unshift("track"), c = b.apply(null, a), A.shift(), c }, J = function (a) { var b; if (null == a && (a = "GET"), "track" === A[0]) return "force"; if (!A.length && D.ajax) { if ("socket" === a && D.ajax.trackWebSockets) return !0; if (b = a.toUpperCase(), $.call(D.ajax.trackMethods, b) >= 0) return !0 } return !1 }, k = function (a) { function b() { var a, c = this; b.__super__.constructor.apply(this, arguments), a = function (a) { var b; return b = a.open, a.open = function (d, e) { return J(d) && c.trigger("request", { type: d, url: e, request: a }), b.apply(a, arguments) } }, window.XMLHttpRequest = function (b) { var c; return c = new P(b), a(c), c }; try { w(window.XMLHttpRequest, P) } catch (d) {} if (null != O) { window.XDomainRequest = function () { var b; return b = new O, a(b), b }; try { w(window.XDomainRequest, O) } catch (d) {} } if (null != N && D.ajax.trackWebSockets) { window.WebSocket = function (a, b) { var d; return d = null != b ? new N(a, b) : new N(a), J("socket") && c.trigger("request", { type: "socket", url: a, protocols: b, request: d }), d }; try { w(window.WebSocket, N) } catch (d) {} } } return Z(b, a), b }(h), R = null, y = function () { return null == R && (R = new k), R }, I = function (a) { var b, c, d, e; for (e = D.ajax.ignoreURLs, c = 0, d = e.length; d > c; c++) if (b = e[c], "string" == typeof b) { if (-1 !== a.indexOf(b)) return !0 } else if (b.test(a)) return !0; return !1 }, y() .on("request", function (b) { var c, d, e, f, g; return f = b.type, e = b.request, g = b.url, I(g) ? void 0 : j.running || D.restartOnRequestAfter === !1 && "force" !== J(f) ? void 0 : (d = arguments, c = D.restartOnRequestAfter || 0, "boolean" == typeof c && (c = 0), setTimeout(function () { var b, c, g, h, i, k; if (b = "socket" === f ? e.readyState < 2 : 0 < (h = e.readyState) && 4 > h) { for (j.restart(), i = j.sources, k = [], c = 0, g = i.length; g > c; c++) { if (K = i[c], K instanceof a) { K.watch.apply(K, d); break } k.push(void 0) } return k } }, c)) }), a = function () { function a() { var a = this; this.elements = [], y() .on("request", function () { return a.watch.apply(a, arguments) }) } return a.prototype.watch = function (a) { var b, c, d, e; return d = a.type, b = a.request, e = a.url, I(e) ? void 0 : (c = "socket" === d ? new n(b) : new o(b), this.elements.push(c)) }, a }(), o = function () { function a(a) { var b, c, d, e, f, g, h = this; if (this.progress = 0, null != window.ProgressEvent) for (c = null, a.addEventListener("progress", function (a) { return h.progress = a.lengthComputable ? 100 * a.loaded / a.total : h.progress + (100 - h.progress) / 2 }, !1), g = ["load", "abort", "timeout", "error"], d = 0, e = g.length; e > d; d++) b = g[d], a.addEventListener(b, function () { return h.progress = 100 }, !1); else f = a.onreadystatechange, a.onreadystatechange = function () { var b; return 0 === (b = a.readyState) || 4 === b ? h.progress = 100 : 3 === a.readyState && (h.progress = 50), "function" == typeof f ? f.apply(null, arguments) : void 0 } } return a }(), n = function () { function a(a) { var b, c, d, e, f = this; for (this.progress = 0, e = ["error", "open"], c = 0, d = e.length; d > c; c++) b = e[c], a.addEventListener(b, function () { return f.progress = 100 }, !1) } return a }(), d = function () { function a(a) { var b, c, d, f; for (null == a && (a = {}), this.elements = [], null == a.selectors && (a.selectors = []), f = a.selectors, c = 0, d = f.length; d > c; c++) b = f[c], this.elements.push(new e(b)) } return a }(), e = function () { function a(a) { this.selector = a, this.progress = 0, this.check() } return a.prototype.check = function () { var a = this; return document.querySelector(this.selector) ? this.done() : setTimeout(function () { return a.check() }, D.elements.checkInterval) }, a.prototype.done = function () { return this.progress = 100 }, a }(), c = function () { function a() { var a, b, c = this; this.progress = null != (b = this.states[document.readyState]) ? b : 100, a = document.onreadystatechange, document.onreadystatechange = function () { return null != c.states[document.readyState] && (c.progress = c.states[document.readyState]), "function" == typeof a ? a.apply(null, arguments) : void 0 } } return a.prototype.states = { loading: 0, interactive: 50, complete: 100 }, a }(), f = function () { function a() { var a, b, c, d, e, f = this; this.progress = 0, a = 0, e = [], d = 0, c = C(), b = setInterval(function () { var g; return g = C() - c - 50, c = C(), e.push(g), e.length > D.eventLag.sampleCount && e.shift(), a = q(e), ++d >= D.eventLag.minSamples && a < D.eventLag.lagThreshold ? (f.progress = 100, clearInterval(b)) : f.progress = 100 * (3 / (a + 3)) }, 50) } return a }(), m = function () { function a(a) { this.source = a, this.last = this.sinceLastUpdate = 0, this.rate = D.initialRate, this.catchup = 0, this.progress = this.lastProgress = 0, null != this.source && (this.progress = F(this.source, "progress")) } return a.prototype.tick = function (a, b) { var c; return null == b && (b = F(this.source, "progress")), b >= 100 && (this.done = !0), b === this.last ? this.sinceLastUpdate += a : (this.sinceLastUpdate && (this.rate = (b - this.last) / this.sinceLastUpdate), this.catchup = (b - this.progress) / D.catchupTime, this.sinceLastUpdate = 0, this.last = b), b > this.progress && (this.progress += this.catchup * a), c = 1 - Math.pow(this.progress / 100, D.easeFactor), this.progress += c * this.rate * a, this.progress = Math.min(this.lastProgress + D.maxProgressPerFrame, this.progress), this.progress = Math.max(0, this.progress), this.progress = Math.min(100, this.progress), this.lastProgress = this.progress, this.progress }, a }(), L = null, H = null, r = null, M = null, p = null, s = null, j.running = !1, z = function () { return D.restartOnPushState ? j.restart() : void 0 }, null != window.history.pushState && (T = window.history.pushState, window.history.pushState = function () { return z(), T.apply(window.history, arguments) }), null != window.history.replaceState && (W = window.history.replaceState, window.history.replaceState = function () { return z(), W.apply(window.history, arguments) }), l = { ajax: a, elements: d, document: c, eventLag: f }, (B = function () { var a, c, d, e, f, g, h, i; for (j.sources = L = [], g = ["ajax", "elements", "document", "eventLag"], c = 0, e = g.length; e > c; c++) a = g[c], D[a] !== !1 && L.push(new l[a](D[a])); for (i = null != (h = D.extraSources) ? h : [], d = 0, f = i.length; f > d; d++) K = i[d], L.push(new K(D)); return j.bar = r = new b, H = [], M = new m })(), j.stop = function () { return j.trigger("stop"), j.running = !1, r.destroy(), s = !0, null != p && ("function" == typeof t && t(p), p = null), B() }, j.restart = function () { return j.trigger("restart"), j.stop(), j.start() }, j.go = function () { var a; return j.running = !0, r.render(), a = C(), s = !1, p = G(function (b, c) { var d, e, f, g, h, i, k, l, n, o, p, q, t, u, v, w; for (l = 100 - r.progress, e = p = 0, f = !0, i = q = 0, u = L.length; u > q; i = ++q) for (K = L[i], o = null != H[i] ? H[i] : H[i] = [], h = null != (w = K.elements) ? w : [K], k = t = 0, v = h.length; v > t; k = ++t) g = h[k], n = null != o[k] ? o[k] : o[k] = new m(g), f &= n.done, n.done || (e++, p += n.tick(b)); return d = p / e, r.update(M.tick(b, d)), r.done() || f || s ? (r.update(100), j.trigger("done"), setTimeout(function () { return r.finish(), j.running = !1, j.trigger("hide") }, Math.max(D.ghostTime, Math.max(D.minTime - (C() - a), 0)))) : c() }) }, j.start = function (a) { v(D, a), j.running = !0; try { r.render() } catch (b) { i = b } return document.querySelector(".loader") ? (j.trigger("start"), j.go()) : setTimeout(j.start, 50) }, "function" == typeof define && define.amd ? define(function () { return j }) : "object" == typeof exports ? module.exports = j : D.startOnPageLoad && j.start() }
lgpl-3.0
liuhongchao/GATE_Developer_7.0
src/gate/jape/Compiler.java
6084
/* * Compiler.java - compile .jape files * * Copyright (c) 1995-2012, The University of Sheffield. See the file * COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt * * This file is part of GATE (see http://gate.ac.uk/), and is free * software, licenced under the GNU Library General Public License, * Version 2, June 1991 (in the distribution as file licence.html, * and also available at http://gate.ac.uk/gate/licence.html). * * Hamish Cunningham, 23/02/2000 * * $Id: Compiler.java 15333 2012-02-07 13:18:33Z ian_roberts $ */ package gate.jape; import java.io.*; import java.util.ArrayList; import java.util.Iterator; import gate.Factory; import gate.jape.parser.ParseCpsl; import gate.util.Err; import gate.util.Out; /** * Compiler for JAPE files. */ public class Compiler { /** Debug flag */ private static final boolean DEBUG = false; /** How much noise to make. */ static private boolean verbose = false; static String defaultEncoding = "UTF-8"; /** Take a list of .jape files names and compile them to .ser. * Also recognises a -v option which makes it chatty. */ static public void main(String[] args) { // process options int argsIndex = 0; while(args[argsIndex].toCharArray()[0] == '-') if(args[argsIndex++].equals("-v")) verbose = true; // construct list of the files ArrayList fileNames = new ArrayList(); for( ; argsIndex<args.length; argsIndex++) fileNames.add(args[argsIndex]); // compile the files compile(fileNames); message("done"); } // main /** The main compile method, taking a file name. */ static public void compile(String japeFileName, String encoding) { // parse message("parsing " + japeFileName); Transducer transducer = null; try { transducer = parseJape(japeFileName, encoding); } catch(JapeException e) { emessage("couldn't compile " + japeFileName + ": " + e); return; } // save message("saving " + japeFileName); try { saveJape(japeFileName, transducer); } catch (JapeException e) { emessage("couldn't save " + japeFileName + ": " + e); } message("finished " + japeFileName); } // compile(String japeFileName) /** The main compile method, taking a list of file names. */ static public void compile(ArrayList fileNames) { // for each file, compile and save for(Iterator i = fileNames.iterator(); i.hasNext(); ) compile((String) i.next(), defaultEncoding); } // compile /** Parse a .jape and return a transducer, or throw exception. */ static public Transducer parseJape(String japeFileName, String encoding) throws JapeException { Transducer transducer = null; try { ParseCpsl cpslParser = Factory.newJapeParser(new File(japeFileName).toURI().toURL(), encoding); transducer = cpslParser.MultiPhaseTransducer(); } catch(gate.jape.parser.ParseException e) { throw(new JapeException(e.toString())); } catch(IOException e) { throw(new JapeException(e.toString())); } return transducer; } // parseJape /** Save a .jape, or throw exception. */ static public void saveJape(String japeFileName, Transducer transducer) throws JapeException { String saveName = japeNameToSaveName(japeFileName); try { FileOutputStream fos = new FileOutputStream(saveName); ObjectOutputStream oos = new ObjectOutputStream (fos); oos.writeObject(transducer); oos.close(); } catch (IOException e) { throw(new JapeException(e.toString())); } } // saveJape /** Convert a .jape file name to a .ser file name. */ static String japeNameToSaveName(String japeFileName) { String base = japeFileName; if(japeFileName.endsWith(".jape") || japeFileName.endsWith(".JAPE")) base = japeFileName.substring(0, japeFileName.length() - 5); return base + ".ser"; } // japeNameToSaveName /** Hello? Anybody there?? */ public static void message(String mess) { if(verbose) Out.println("JAPE compiler: " + mess); } // message /** Ooops. */ public static void emessage(String mess) { Err.println("JAPE compiler error: " + mess); } // emessage } // class Compiler // $Log$ // Revision 1.11 2005/06/21 14:09:51 valyt // Ken Williams's patch for Factory and JAPE tranducers // // Revision 1.10 2005/01/11 13:51:36 ian // Updating copyrights to 1998-2005 in preparation for v3.0 // // Revision 1.9 2004/07/21 17:10:07 akshay // Changed copyright from 1998-2001 to 1998-2004 // // Revision 1.8 2004/03/25 13:01:14 valyt // Imports optimisation throughout the Java sources // (to get rid of annoying warnings in Eclipse) // // Revision 1.7 2001/09/13 12:09:49 kalina // Removed completely the use of jgl.objectspace.Array and such. // Instead all sources now use the new Collections, typically ArrayList. // I ran the tests and I ran some documents and compared with keys. // JAPE seems to work well (that's where it all was). If there are problems // maybe look at those new structures first. // // Revision 1.6 2001/02/08 13:46:06 valyt // Added full Unicode support for the gazetteer and Jape // converted the gazetteer files to UTF-8 // // Revision 1.5 2000/11/08 16:35:02 hamish // formatting // // Revision 1.4 2000/10/26 10:45:30 oana // Modified in the code style // // Revision 1.3 2000/10/16 16:44:33 oana // Changed the comment of DEBUG variable // // Revision 1.2 2000/10/10 15:36:35 oana // Changed System.out in Out and System.err in Err; // Added the DEBUG variable seted on false; // Added in the header the licence; // // Revision 1.1 2000/02/23 13:46:04 hamish // added // // Revision 1.1.1.1 1999/02/03 16:23:01 hamish // added gate2 // // Revision 1.3 1998/10/29 12:07:27 hamish // added compile method taking a file name // // Revision 1.2 1998/09/21 16:19:27 hamish // don't catch *all* exceptions! // // Revision 1.1 1998/09/18 15:07:41 hamish // a functioning compiler in two shakes of a rats tail
lgpl-3.0
cordobagamejam/web2016
index.js
542
// Setup basic express server var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); var port = process.env.PORT || 3000; var realtime = require('./server/realtime'); server.listen(port, function () { console.log('Server listening at port %d', port); }); // Routing app.use(express.static(__dirname + '/dist')); app.get('*', function(req, res){ res.sendfile(__dirname + '/dist/index.html'); }); // Chatroom var numUsers = 0; realtime(io, numUsers);
lgpl-3.0
Norgat/stocksharp
Samples/Testing/SampleHistoryTesting/MainWindow.xaml.cs
19162
namespace SampleHistoryTesting { using System; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Collections.Generic; using Ecng.Xaml; using Ecng.Common; using Ecng.Collections; using Ecng.Localization; using Ookii.Dialogs.Wpf; using StockSharp.Algo; using StockSharp.Algo.Candles; using StockSharp.Algo.Candles.Compression; using StockSharp.Algo.Commissions; using StockSharp.Algo.History; using StockSharp.Algo.History.Russian.Finam; using StockSharp.Algo.Storages; using StockSharp.Algo.Testing; using StockSharp.Algo.Indicators; using StockSharp.BusinessEntities; using StockSharp.Logging; using StockSharp.Messages; using StockSharp.Xaml.Charting; using StockSharp.Localization; public partial class MainWindow { private class TradeCandleBuilderSourceEx : TradeCandleBuilderSource { public TradeCandleBuilderSourceEx(IConnector connector) : base(connector) { } protected override void RegisterSecurity(Security security) { } protected override void UnRegisterSecurity(Security security) { } } private class FinamSecurityStorage : CollectionSecurityProvider, ISecurityStorage { public FinamSecurityStorage(Security security) : base(new[] { security }) { } void ISecurityStorage.Save(Security security) { } void ISecurityStorage.Delete(Security security) { throw new NotSupportedException(); } void ISecurityStorage.DeleteBy(Security criteria) { throw new NotSupportedException(); } IEnumerable<string> ISecurityStorage.GetSecurityIds() { return Enumerable.Empty<string>(); } } // emulation settings private sealed class EmulationInfo { public bool UseTicks { get; set; } public bool UseMarketDepth { get; set; } public TimeSpan? UseCandleTimeFrame { get; set; } public Color CurveColor { get; set; } public string StrategyName { get; set; } public bool UseOrderLog { get; set; } public bool UseLevel1 { get; set; } public Func<DateTimeOffset, IEnumerable<Message>> HistorySource { get; set; } } private readonly List<ProgressBar> _progressBars = new List<ProgressBar>(); private readonly List<CheckBox> _checkBoxes = new List<CheckBox>(); private readonly List<HistoryEmulationConnector> _connectors = new List<HistoryEmulationConnector>(); private readonly BufferedChart _bufferedChart; private DateTime _startEmulationTime; private ChartCandleElement _candlesElem; private ChartTradeElement _tradesElem; private ChartIndicatorElement _shortElem; private SimpleMovingAverage _shortMa; private ChartIndicatorElement _longElem; private SimpleMovingAverage _longMa; private ChartArea _area; private readonly FinamHistorySource _finamHistorySource = new FinamHistorySource(); public MainWindow() { InitializeComponent(); _bufferedChart = new BufferedChart(Chart); HistoryPath.Text = @"..\..\..\HistoryData\".ToFullPath(); if (LocalizedStrings.ActiveLanguage == Languages.Russian) { SecId.Text = "RIZ2@FORTS"; From.Value = new DateTime(2012, 10, 1); To.Value = new DateTime(2012, 10, 25); TimeFrame.SelectedIndex = 1; } else { SecId.Text = "@ES#@CMEMINI"; From.Value = new DateTime(2015, 8, 1); To.Value = new DateTime(2015, 8, 31); TimeFrame.SelectedIndex = 0; } _progressBars.AddRange(new[] { TicksProgress, TicksAndDepthsProgress, DepthsProgress, CandlesProgress, CandlesAndDepthsProgress, OrderLogProgress, Level1Progress, FinamCandlesProgress, YahooCandlesProgress }); _checkBoxes.AddRange(new[] { TicksCheckBox, TicksAndDepthsCheckBox, DepthsCheckBox, CandlesCheckBox, CandlesAndDepthsCheckBox, OrderLogCheckBox, Level1CheckBox, FinamCandlesCheckBox, YahooCandlesCheckBox, }); } private void FindPathClick(object sender, RoutedEventArgs e) { var dlg = new VistaFolderBrowserDialog(); if (!HistoryPath.Text.IsEmpty()) dlg.SelectedPath = HistoryPath.Text; if (dlg.ShowDialog(this) == true) { HistoryPath.Text = dlg.SelectedPath; } } private void StartBtnClick(object sender, RoutedEventArgs e) { InitChart(); if (HistoryPath.Text.IsEmpty() || !Directory.Exists(HistoryPath.Text)) { MessageBox.Show(this, LocalizedStrings.Str3014); return; } if (_connectors.Any(t => t.State != EmulationStates.Stopped)) { MessageBox.Show(this, LocalizedStrings.Str3015); return; } var secGen = new SecurityIdGenerator(); var secIdParts = secGen.Split(SecId.Text); //if (secIdParts.Length != 2) //{ // MessageBox.Show(this, LocalizedStrings.Str3016); // return; //} var timeFrame = TimeSpan.FromMinutes(TimeFrame.SelectedIndex == 0 ? 1 : 5); var secCode = secIdParts.Item1; var board = ExchangeBoard.GetOrCreateBoard(secIdParts.Item2); // create test security var security = new Security { Id = SecId.Text, // sec id has the same name as folder with historical data Code = secCode, Board = board, }; if (FinamCandlesCheckBox.IsChecked == true) { _finamHistorySource.Refresh(new FinamSecurityStorage(security), security, s => {}, () => false); } // create backtesting modes var settings = new[] { Tuple.Create( TicksCheckBox, TicksProgress, TicksParameterGrid, // ticks new EmulationInfo {UseTicks = true, CurveColor = Colors.DarkGreen, StrategyName = LocalizedStrings.Ticks}), Tuple.Create( TicksAndDepthsCheckBox, TicksAndDepthsProgress, TicksAndDepthsParameterGrid, // ticks + order book new EmulationInfo {UseTicks = true, UseMarketDepth = true, CurveColor = Colors.Red, StrategyName = LocalizedStrings.XamlStr757}), Tuple.Create( DepthsCheckBox, DepthsProgress, DepthsParameterGrid, // order book new EmulationInfo {UseMarketDepth = true, CurveColor = Colors.OrangeRed, StrategyName = LocalizedStrings.MarketDepths}), Tuple.Create( CandlesCheckBox, CandlesProgress, CandlesParameterGrid, // candles new EmulationInfo {UseCandleTimeFrame = timeFrame, CurveColor = Colors.DarkBlue, StrategyName = LocalizedStrings.Candles}), Tuple.Create( CandlesAndDepthsCheckBox, CandlesAndDepthsProgress, CandlesAndDepthsParameterGrid, // candles + orderbook new EmulationInfo {UseMarketDepth = true, UseCandleTimeFrame = timeFrame, CurveColor = Colors.Cyan, StrategyName = LocalizedStrings.XamlStr635}), Tuple.Create( OrderLogCheckBox, OrderLogProgress, OrderLogParameterGrid, // order log new EmulationInfo {UseOrderLog = true, CurveColor = Colors.CornflowerBlue, StrategyName = LocalizedStrings.OrderLog}), Tuple.Create( Level1CheckBox, Level1Progress, Level1ParameterGrid, // order log new EmulationInfo {UseLevel1 = true, CurveColor = Colors.Aquamarine, StrategyName = LocalizedStrings.Level1}), Tuple.Create( FinamCandlesCheckBox, FinamCandlesProgress, FinamCandlesParameterGrid, // candles new EmulationInfo {UseCandleTimeFrame = timeFrame, HistorySource = d => _finamHistorySource.GetCandles(security, timeFrame, d.Date, d.Date).Select(c => c.ToMessage()), CurveColor = Colors.DarkBlue, StrategyName = LocalizedStrings.FinamCandles}), Tuple.Create( YahooCandlesCheckBox, YahooCandlesProgress, YahooCandlesParameterGrid, // candles new EmulationInfo {UseCandleTimeFrame = timeFrame, HistorySource = d => new YahooHistorySource().GetCandles(security, timeFrame, d.Date, d.Date).Select(c => c.ToMessage()), CurveColor = Colors.DarkBlue, StrategyName = LocalizedStrings.YahooCandles}), }; // storage to historical data var storageRegistry = new StorageRegistry { // set historical path DefaultDrive = new LocalMarketDataDrive(HistoryPath.Text) }; var startTime = ((DateTime)From.Value).ChangeKind(DateTimeKind.Utc); var stopTime = ((DateTime)To.Value).ChangeKind(DateTimeKind.Utc); // (ru only) ОЛ необходимо загружать с 18.45 пред дня, чтобы стаканы строились правильно if (OrderLogCheckBox.IsChecked == true) startTime = startTime.Subtract(TimeSpan.FromDays(1)).AddHours(18).AddMinutes(45).AddTicks(1); // ProgressBar refresh step var progressStep = ((stopTime - startTime).Ticks / 100).To<TimeSpan>(); // set ProgressBar bounds _progressBars.ForEach(p => { p.Value = 0; p.Maximum = 100; }); var logManager = new LogManager(); var fileLogListener = new FileLogListener("sample.log"); logManager.Listeners.Add(fileLogListener); //logManager.Listeners.Add(new DebugLogListener()); // for track logs in output window in Vusial Studio (poor performance). var generateDepths = GenDepthsCheckBox.IsChecked == true; var maxDepth = MaxDepth.Text.To<int>(); var maxVolume = MaxVolume.Text.To<int>(); foreach (var set in settings) { if (set.Item1.IsChecked == false) continue; var progressBar = set.Item2; var statistic = set.Item3; var emulationInfo = set.Item4; var level1Info = new Level1ChangeMessage { SecurityId = security.ToSecurityId(), ServerTime = startTime, } .TryAdd(Level1Fields.PriceStep, secIdParts.Item1 == "RIZ2" ? 10m : 1) .TryAdd(Level1Fields.StepPrice, 6m) .TryAdd(Level1Fields.MinPrice, 10m) .TryAdd(Level1Fields.MaxPrice, 1000000m) .TryAdd(Level1Fields.MarginBuy, 10000m) .TryAdd(Level1Fields.MarginSell, 10000m); // test portfolio var portfolio = new Portfolio { Name = "test account", BeginValue = 1000000, }; // create backtesting connector var connector = new HistoryEmulationConnector( new[] { security }, new[] { portfolio }) { EmulationAdapter = { Emulator = { Settings = { // match order if historical price touched our limit order price. // It is terned off, and price should go through limit order price level // (more "severe" test mode) MatchOnTouch = false, } } }, UseExternalCandleSource = emulationInfo.UseCandleTimeFrame != null, CreateDepthFromOrdersLog = emulationInfo.UseOrderLog, CreateTradesFromOrdersLog = emulationInfo.UseOrderLog, HistoryMessageAdapter = { StorageRegistry = storageRegistry, // set history range StartDate = startTime, StopDate = stopTime, }, // set market time freq as time frame MarketTimeChangedInterval = timeFrame, }; ((ILogSource)connector).LogLevel = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info; logManager.Sources.Add(connector); var candleManager = emulationInfo.UseCandleTimeFrame == null ? new CandleManager(new TradeCandleBuilderSourceEx(connector)) : new CandleManager(connector); var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame); _shortMa = new SimpleMovingAverage { Length = 10 }; _shortElem = new ChartIndicatorElement { Color = Colors.Coral, ShowAxisMarker = false, FullTitle = _shortMa.ToString() }; _bufferedChart.AddElement(_area, _shortElem); _longMa = new SimpleMovingAverage { Length = 80 }; _longElem = new ChartIndicatorElement { ShowAxisMarker = false, FullTitle = _longMa.ToString() }; _bufferedChart.AddElement(_area, _longElem); // create strategy based on 80 5-min и 10 5-min var strategy = new SmaStrategy(_bufferedChart, _candlesElem, _tradesElem, _shortMa, _shortElem, _longMa, _longElem, series) { Volume = 1, Portfolio = portfolio, Security = security, Connector = connector, LogLevel = DebugLogCheckBox.IsChecked == true ? LogLevels.Debug : LogLevels.Info, // by default interval is 1 min, // it is excessively for time range with several months UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To<TimeSpan>() }; logManager.Sources.Add(strategy); connector.NewSecurities += securities => { if (securities.All(s => s != security)) return; // fill level1 values connector.SendInMessage(level1Info); if (emulationInfo.HistorySource != null) { if (emulationInfo.UseCandleTimeFrame != null) { connector.RegisterHistorySource(security, MarketDataTypes.CandleTimeFrame, emulationInfo.UseCandleTimeFrame.Value, emulationInfo.HistorySource); } if (emulationInfo.UseTicks) { connector.RegisterHistorySource(security, MarketDataTypes.Trades, null, emulationInfo.HistorySource); } if (emulationInfo.UseLevel1) { connector.RegisterHistorySource(security, MarketDataTypes.Level1, null, emulationInfo.HistorySource); } if (emulationInfo.UseMarketDepth) { connector.RegisterHistorySource(security, MarketDataTypes.MarketDepth, null, emulationInfo.HistorySource); } } else { if (emulationInfo.UseMarketDepth) { connector.RegisterMarketDepth(security); if ( // if order book will be generated generateDepths || // of backtesting will be on candles emulationInfo.UseCandleTimeFrame != TimeSpan.Zero ) { // if no have order book historical data, but strategy is required, // use generator based on last prices connector.RegisterMarketDepth(new TrendMarketDepthGenerator(connector.GetSecurityId(security)) { Interval = TimeSpan.FromSeconds(1), // order book freq refresh is 1 sec MaxAsksDepth = maxDepth, MaxBidsDepth = maxDepth, UseTradeVolume = true, MaxVolume = maxVolume, MinSpreadStepCount = 2, // min spread generation is 2 pips MaxSpreadStepCount = 5, // max spread generation size (prevent extremely size) MaxPriceStepCount = 3 // pips size, }); } } if (emulationInfo.UseOrderLog) { connector.RegisterOrderLog(security); } if (emulationInfo.UseTicks) { connector.RegisterTrades(security); } if (emulationInfo.UseLevel1) { connector.RegisterSecurity(security); } } // start strategy before emulation started strategy.Start(); candleManager.Start(series); // start historical data loading when connection established successfully and all data subscribed connector.Start(); }; // fill parameters panel statistic.Parameters.Clear(); statistic.Parameters.AddRange(strategy.StatisticManager.Parameters); var pnlCurve = Curve.CreateCurve(LocalizedStrings.PnL + " " + emulationInfo.StrategyName, emulationInfo.CurveColor, EquityCurveChartStyles.Area); var unrealizedPnLCurve = Curve.CreateCurve(LocalizedStrings.PnLUnreal + emulationInfo.StrategyName, Colors.Black); var commissionCurve = Curve.CreateCurve(LocalizedStrings.Str159 + " " + emulationInfo.StrategyName, Colors.Red, EquityCurveChartStyles.DashedLine); var posItems = PositionCurve.CreateCurve(emulationInfo.StrategyName, emulationInfo.CurveColor); strategy.PnLChanged += () => { var pnl = new EquityData { Time = strategy.CurrentTime, Value = strategy.PnL - strategy.Commission ?? 0 }; var unrealizedPnL = new EquityData { Time = strategy.CurrentTime, Value = strategy.PnLManager.UnrealizedPnL }; var commission = new EquityData { Time = strategy.CurrentTime, Value = strategy.Commission ?? 0 }; pnlCurve.Add(pnl); unrealizedPnLCurve.Add(unrealizedPnL); commissionCurve.Add(commission); }; strategy.PositionChanged += () => posItems.Add(new EquityData { Time = strategy.CurrentTime, Value = strategy.Position }); var nextTime = startTime + progressStep; // handle historical time for update ProgressBar connector.MarketTimeChanged += d => { if (connector.CurrentTime < nextTime && connector.CurrentTime < stopTime) return; var steps = (connector.CurrentTime - startTime).Ticks / progressStep.Ticks + 1; nextTime = startTime + (steps * progressStep.Ticks).To<TimeSpan>(); this.GuiAsync(() => progressBar.Value = steps); }; connector.StateChanged += () => { if (connector.State == EmulationStates.Stopped) { candleManager.Stop(series); strategy.Stop(); logManager.Dispose(); _connectors.Clear(); SetIsEnabled(false); this.GuiAsync(() => { if (connector.IsFinished) { progressBar.Value = progressBar.Maximum; MessageBox.Show(this, LocalizedStrings.Str3024.Put(DateTime.Now - _startEmulationTime)); } else MessageBox.Show(this, LocalizedStrings.cancelled); }); } else if (connector.State == EmulationStates.Started) { SetIsEnabled(true); } }; if (ShowDepth.IsChecked == true) { MarketDepth.UpdateFormat(security); connector.NewMessage += message => { var quoteMsg = message as QuoteChangeMessage; if (quoteMsg != null) MarketDepth.UpdateDepth(quoteMsg); }; } _connectors.Add(connector); progressBar.Value = 0; } _startEmulationTime = DateTime.Now; // start emulation foreach (var connector in _connectors) { // raise NewSecurities and NewPortfolio for full fill strategy properties connector.Connect(); // 1 cent commission for trade connector.SendInMessage(new CommissionRuleMessage { Rule = new CommissionPerTradeRule { Value = 0.01m } }); } TabControl.Items.Cast<TabItem>().First(i => i.Visibility == Visibility.Visible).IsSelected = true; } private void CheckBoxClick(object sender, RoutedEventArgs e) { var isEnabled = _checkBoxes.Any(c => c.IsChecked == true); StartBtn.IsEnabled = isEnabled; TabControl.Visibility = isEnabled ? Visibility.Visible : Visibility.Collapsed; } private void StopBtnClick(object sender, RoutedEventArgs e) { foreach (var connector in _connectors) { connector.Disconnect(); } } private void InitChart() { _bufferedChart.ClearAreas(); Curve.Clear(); PositionCurve.Clear(); _area = new ChartArea(); _bufferedChart.AddArea(_area); _candlesElem = new ChartCandleElement { ShowAxisMarker = false }; _bufferedChart.AddElement(_area, _candlesElem); _tradesElem = new ChartTradeElement { FullTitle = "Сделки" }; _bufferedChart.AddElement(_area, _tradesElem); } private void SetIsEnabled(bool started) { this.GuiAsync(() => { StopBtn.IsEnabled = started; StartBtn.IsEnabled = !started; foreach (var checkBox in _checkBoxes) { checkBox.IsEnabled = !started; } _bufferedChart.IsAutoRange = started; }); } } }
lgpl-3.0
The-Fireplace-Minecraft-Mods/Mechanical-Soldiers
src/main/java/the_fireplace/mechsoldiers/client/ClientEvents.java
9740
package the_fireplace.mechsoldiers.client; import com.google.common.collect.Lists; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.resources.IResource; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.client.event.GuiScreenEvent; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.event.RenderTooltipEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.fml.client.config.GuiUtils; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.io.IOUtils; import the_fireplace.mechsoldiers.MechSoldiers; import the_fireplace.mechsoldiers.entity.EntityMechSkeleton; import the_fireplace.mechsoldiers.network.PacketDispatcher; import the_fireplace.mechsoldiers.network.packets.RequestPartsMessage; import the_fireplace.mechsoldiers.util.StainedItemUtil; import the_fireplace.overlord.Overlord; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Random; @Mod.EventBusSubscriber(Side.CLIENT) @SideOnly(Side.CLIENT) public final class ClientEvents { private static Random rand = new Random(); private static final ResourceLocation SPLASH_TEXTS = new ResourceLocation("texts/splashes.txt"); public static int splashOffsetCount = 0; public static final int finalSplashOffsetCount; private static final List<String> mySplashes = Lists.newArrayList( "I'm sorry, Dave. I'm afraid I can't do that.", "...Painted?" ); static { splashOffsetCount += mySplashes.size(); //Using this system allows other mods using the system to know how many mod-added splashes there are. Not perfect, but Forge doesn't have a system in place, so this will have to do. try{ File file = new File(".splashes"); if(file.exists()) { byte[] encoded = Files.readAllBytes(file.toPath()); try { splashOffsetCount += Integer.parseInt(new String(encoded, "UTF-8")); } catch (NumberFormatException e) { e.printStackTrace(); } if(!file.delete()) Overlord.logWarn("Splashes file could not be deleted"); } file.createNewFile(); file.deleteOnExit(); FileWriter fw = new FileWriter(file); fw.write(String.valueOf(splashOffsetCount)); fw.close(); }catch(IOException e){ Overlord.logWarn(e.getLocalizedMessage()); } finalSplashOffsetCount = splashOffsetCount; } @SubscribeEvent public static void screenload(GuiScreenEvent.InitGuiEvent event) { if (event.getGui() instanceof GuiMainMenu) { IResource iresource = null; try { List<String> defaultSplashes = Lists.newArrayList(); iresource = Minecraft.getMinecraft().getResourceManager().getResource(SPLASH_TEXTS); BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(iresource.getInputStream(), StandardCharsets.UTF_8)); String s; while ((s = bufferedreader.readLine()) != null) { s = s.trim(); if (!s.isEmpty()) { defaultSplashes.add(s); } } int splashNum = rand.nextInt(defaultSplashes.size() + finalSplashOffsetCount); if (splashNum >= defaultSplashes.size()+finalSplashOffsetCount-mySplashes.size()) ReflectionHelper.setPrivateValue(GuiMainMenu.class, (GuiMainMenu) event.getGui(), mySplashes.get(splashNum - (defaultSplashes.size()+finalSplashOffsetCount-mySplashes.size())), "splashText", "field_73975_c"); } catch (IOException e) { Overlord.logWarn(e.getLocalizedMessage()); } finally { IOUtils.closeQuietly(iresource); } } } @SubscribeEvent public static void modelRegister(ModelRegistryEvent event){ MechSoldiers.registerItemRenders(); } @SubscribeEvent public static void renderTooltip(ItemTooltipEvent event) { if (event.getItemStack().hasTagCompound() && event.getItemStack().getTagCompound().hasKey("StainColor")) event.getToolTip().add(Overlord.proxy.translateToLocal("stained")); } @SubscribeEvent public static void renderTooltip(RenderTooltipEvent.Pre event) { if (event.getStack().hasTagCompound() && event.getStack().getTagCompound().hasKey("StainColor")) { int mouseX = event.getX(); int mouseY = event.getY(); int screenWidth = event.getScreenWidth(); int screenHeight = event.getScreenHeight(); int maxTextWidth = event.getMaxWidth(); FontRenderer font = event.getFontRenderer(); List<String> textLines = event.getLines(); GlStateManager.disableRescaleNormal(); RenderHelper.disableStandardItemLighting(); GlStateManager.disableLighting(); GlStateManager.disableDepth(); int tooltipTextWidth = 0; int color = -1; for (String line : event.getLines()) { int textLineWidth = font.getStringWidth(line); if (textLineWidth > tooltipTextWidth) tooltipTextWidth = textLineWidth; } boolean needsWrap = false; int titleLinesCount = 1; int tooltipX = mouseX + 12; if (tooltipX + tooltipTextWidth + 4 > screenWidth) { tooltipX = mouseX - 16 - tooltipTextWidth; if (tooltipX < 4) // if the tooltip doesn't fit on the screen { if (mouseX > screenWidth / 2) tooltipTextWidth = mouseX - 12 - 8; else tooltipTextWidth = screenWidth - 16 - mouseX; needsWrap = true; } } if (maxTextWidth > 0 && tooltipTextWidth > maxTextWidth) { tooltipTextWidth = maxTextWidth; needsWrap = true; } if (needsWrap) { int wrappedTooltipWidth = 0; List<String> wrappedTextLines = new ArrayList<>(); for (int i = 0; i < event.getLines().size(); i++) { String textLine = event.getLines().get(i); List<String> wrappedLine = font.listFormattedStringToWidth(textLine, tooltipTextWidth); if (i == 0) titleLinesCount = wrappedLine.size(); for (String line : wrappedLine) { int lineWidth = font.getStringWidth(line); if (lineWidth > wrappedTooltipWidth) wrappedTooltipWidth = lineWidth; wrappedTextLines.add(line); } } tooltipTextWidth = wrappedTooltipWidth; textLines = wrappedTextLines; if (mouseX > screenWidth / 2) tooltipX = mouseX - 16 - tooltipTextWidth; else tooltipX = mouseX + 12; } int tooltipY = mouseY - 12; int tooltipHeight = 8; if (textLines.size() > 1) { tooltipHeight += (textLines.size() - 1) * 10; if (textLines.size() > titleLinesCount) tooltipHeight += 2; } if (tooltipY + tooltipHeight + 6 > screenHeight) tooltipY = screenHeight - tooltipHeight - 6; final int zLevel = 300; final int backgroundColor = 0xF0100010; GuiUtils.drawGradientRect(zLevel, tooltipX - 3, tooltipY - 4, tooltipX + tooltipTextWidth + 3, tooltipY - 3, backgroundColor, backgroundColor); GuiUtils.drawGradientRect(zLevel, tooltipX - 3, tooltipY + tooltipHeight + 3, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 4, backgroundColor, backgroundColor); GuiUtils.drawGradientRect(zLevel, tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor); GuiUtils.drawGradientRect(zLevel, tooltipX - 4, tooltipY - 3, tooltipX - 3, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor); GuiUtils.drawGradientRect(zLevel, tooltipX + tooltipTextWidth + 3, tooltipY - 3, tooltipX + tooltipTextWidth + 4, tooltipY + tooltipHeight + 3, backgroundColor, backgroundColor); final int borderColorStart = 0x505000FF; final int borderColorEnd = (borderColorStart & 0xFEFEFE) >> 1 | borderColorStart & 0xFF000000; GuiUtils.drawGradientRect(zLevel, tooltipX - 3, tooltipY - 3 + 1, tooltipX - 3 + 1, tooltipY + tooltipHeight + 3 - 1, borderColorStart, borderColorEnd); GuiUtils.drawGradientRect(zLevel, tooltipX + tooltipTextWidth + 2, tooltipY - 3 + 1, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3 - 1, borderColorStart, borderColorEnd); GuiUtils.drawGradientRect(zLevel, tooltipX - 3, tooltipY - 3, tooltipX + tooltipTextWidth + 3, tooltipY - 3 + 1, borderColorStart, borderColorStart); GuiUtils.drawGradientRect(zLevel, tooltipX - 3, tooltipY + tooltipHeight + 2, tooltipX + tooltipTextWidth + 3, tooltipY + tooltipHeight + 3, borderColorEnd, borderColorEnd); for (int lineNumber = 0; lineNumber < textLines.size(); ++lineNumber) { String line = textLines.get(lineNumber); if (line == null) continue; if (TextFormatting.getTextWithoutFormattingCodes(line).equals(Overlord.proxy.translateToLocal("stained"))) { color = StainedItemUtil.getColor(event.getStack()).getRGB(); line = TextFormatting.getTextWithoutFormattingCodes(line); } else color = -1; font.drawStringWithShadow(line, (float) tooltipX, (float) tooltipY, color); if (lineNumber + 1 == titleLinesCount) tooltipY += 2; tooltipY += 10; } GlStateManager.enableLighting(); GlStateManager.enableDepth(); RenderHelper.enableStandardItemLighting(); GlStateManager.enableRescaleNormal(); event.setCanceled(true); } } @SubscribeEvent public static void entityDamage(LivingHurtEvent e){ if(e.getEntityLiving() instanceof EntityMechSkeleton) PacketDispatcher.sendToServer(new RequestPartsMessage((EntityMechSkeleton)e.getEntityLiving())); } }
lgpl-3.0
subes/invesdwin-util
invesdwin-util-parent/invesdwin-util/src/main/java/de/invesdwin/util/swing/Fonts.java
631
package de.invesdwin.util.swing; import java.awt.Component; import java.awt.Font; import javax.annotation.concurrent.Immutable; @Immutable public final class Fonts { private Fonts() {} public static Font resizeFont(final Font font, final int size) { if (font.getSize() != size) { return font.deriveFont((float) size); } else { return font; } } public static void resizeFont(final Component component, final int size) { if (component.getFont().getSize() != size) { component.setFont(resizeFont(component.getFont(), size)); } } }
lgpl-3.0
Borisbee1/Kopernicus
Kopernicus/Kopernicus/Utility.cs
51738
/** * Kopernicus Planetary System Modifier * ==================================== * Created by: BryceSchroeder and Teknoman117 (aka. Nathaniel R. Lewis) * Maintained by: Thomas P., NathanKell and KillAshley * Additional Content by: Gravitasi, aftokino, KCreator, Padishar, Kragrathea, OvenProofMars, zengei, MrHappyFace * ------------------------------------------------------------- * 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 3 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 * * This library is intended to be used as a plugin for Kerbal Space Program * which is copyright 2011-2015 Squad. Your usage of Kerbal Space Program * itself is governed by the terms of its EULA, not the license above. * * https://kerbalspaceprogram.com */ using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.IO; using UnityEngine; namespace Kopernicus { public class Utility { /** * @return LocalSpace game object */ public static GameObject LocalSpace { get { return GameObject.Find(PSystemManager.Instance.localSpaceName); } } // Static object representing the deactivator private static GameObject deactivator; /** * Get an object which is deactivated, essentially, and children are prefabs * @return shared deactivated object for making prefabs */ public static Transform Deactivator { get { if (deactivator == null) { deactivator = new GameObject("__deactivator"); deactivator.SetActive(false); UnityEngine.Object.DontDestroyOnLoad(deactivator); } return deactivator.transform; } } /** * Copy one objects fields to another object via reflection * @param source Object to copy fields from * @param destination Object to copy fields to **/ public static void CopyObjectFields<T>(T source, T destination, bool log = true) { // Reflection based copy foreach (FieldInfo field in (typeof(T)).GetFields()) { // Only copy non static fields if (!field.IsStatic) { if (log) { Logger.Active.Log("Copying \"" + field.Name + "\": " + (field.GetValue(destination) ?? "<NULL>") + " => " + (field.GetValue(source) ?? "<NULL>")); } field.SetValue(destination, field.GetValue(source)); } } } /** * Recursively searches for a named transform in the Transform heirarchy. The requirement of * such a function is sad. This should really be in the Unity3D API. Transform.Find() only * searches in the immediate children. * * @param transform Transform in which is search for named child * @param name Name of child to find * * @return Desired transform or null if it could not be found */ public static Transform FindInChildren(Transform transform, string name) { // Is this null? if (transform == null) { return null; } // Are the names equivalent if (transform.name == name) { return transform; } // If we did not find a transform, search through the children foreach (Transform child in transform) { // Recurse into the child Transform t = FindInChildren(child, name); if (t != null) { return t; } } // Return the transform (will be null if it was not found) return null; } // Dump an object by reflection public static void DumpObjectFields(object o, string title = "---------") { // Dump the raw PQS of Dres (by reflection) Logger.Active.Log("---------" + title + "------------"); foreach (FieldInfo field in o.GetType().GetFields()) { if (!field.IsStatic) { Logger.Active.Log(field.Name + " = " + field.GetValue(o)); } } Logger.Active.Log("--------------------------------------"); } public static void DumpObjectProperties(object o, string title = "---------") { // Iterate through all of the properties Logger.Active.Log("--------- " + title + " ------------"); foreach (PropertyInfo property in o.GetType().GetProperties()) { if (property.CanRead) Logger.Active.Log(property.Name + " = " + property.GetValue(o, null)); } Logger.Active.Log("--------------------------------------"); } /** * Recursively searches for a named PSystemBody * * @param body Parent body to begin search in * @param name Name of body to find * * @return Desired body or null if not found */ public static PSystemBody FindBody(PSystemBody body, string name) { // Is this the body wer are looking for? if (body.celestialBody.bodyName == name) return body; // Otherwise search children foreach (PSystemBody child in body.children) { PSystemBody b = FindBody(child, name); if (b != null) return b; } // Return null because we didn't find shit return null; } // Copy of above, but finds homeworld public static PSystemBody FindHomeBody(PSystemBody body) { // Is this the body wer are looking for? if (body.celestialBody.isHomeWorld) return body; // Otherwise search children foreach (PSystemBody child in body.children) { PSystemBody b = FindHomeBody(child); if (b != null) return b; } // Return null because we didn't find shit return null; } // Print out a tree containing all the objects in the game public static void PerformObjectDump() { Logger.Active.Log("--------- Object Dump -----------"); foreach (GameObject b in GameObject.FindObjectsOfType(typeof(GameObject))) { // Essentially, we iterate through all game objects currently alive and search for // the ones without a parent. Extrememly inefficient and terrible, but its just for // exploratory purposes if (b.transform.parent == null) { // Print out the tree of child objects GameObjectWalk(b, ""); } } Logger.Active.Log("---------------------------------"); } public static void PrintTransform(Transform t, string title = "") { Logger.Active.Log("------" + title + "------"); Logger.Active.Log("Position: " + t.localPosition); Logger.Active.Log("Rotation: " + t.localRotation); Logger.Active.Log("Scale: " + t.localScale); Logger.Active.Log("------------------"); } // Print out the tree of components public static void GameObjectWalk(GameObject o, String prefix = "") { // If null, don't do anything if (o == null) return; // Print this object Logger.Active.Log(prefix + o); Logger.Active.Log(prefix + " >>> Components <<< "); foreach (Component c in o.GetComponents(typeof(Component))) { Logger.Active.Log(prefix + " " + c); } Logger.Active.Log(prefix + " >>> ---------- <<< "); // Game objects are related to each other via transforms in Unity3D. foreach (Transform b in o.transform) { if (b != null) GameObjectWalk(b.gameObject, " " + prefix); } } // Print out the celestial bodies public static void PSystemBodyWalk(PSystemBody b, String prefix = "") { Logger.Active.Log(prefix + b.celestialBody.bodyName + ":" + b.flightGlobalsIndex); foreach (PSystemBody c in b.children) { PSystemBodyWalk(c, prefix + " "); } } // slightly different: static public void DumpUpwards(Transform t, string prefix, bool useKLog = true) { string str = prefix + "Transform " + t.name; if (useKLog) Logger.Default.Log(str); else Debug.Log(str); foreach (Component c in t.GetComponents<Component>()) { str = prefix + " has component " + c.name + " of type " + c.GetType().FullName; if (useKLog) Logger.Default.Log(str); else Debug.Log(str); } if (t.parent != null) DumpUpwards(t.parent, prefix + " "); } static public void DumpDownwards(Transform t, string prefix, bool useKLog = true) { string str = prefix + "Transform " + t.name; if (useKLog) Logger.Default.Log(str); else Debug.Log(str); foreach (Component c in t.GetComponents<Component>()) { str = prefix + " has component " + c.name + " of type " + c.GetType().FullName; if (useKLog) Logger.Default.Log(str); else Debug.Log(str); } if (t.childCount > 0) for (int i = 0; i < t.childCount; ++i) DumpDownwards(t.GetChild(i), prefix + " "); } public static void UpdateScaledMesh(GameObject scaledVersion, PQS pqs, CelestialBody body, string path, string cacheFile, bool exportBin, bool useSpherical) { const double rJool = 6000000.0; const float rScaled = 1000.0f; // Compute scale between Jool and this body float scale = (float)(body.Radius / rJool); scaledVersion.transform.localScale = new Vector3(scale, scale, scale); Mesh scaledMesh; // Attempt to load a cached version of the scale space string CacheDirectory = KSPUtil.ApplicationRootPath + path; string CacheFile = CacheDirectory + "/" + body.name + ".bin"; if (!string.IsNullOrEmpty(cacheFile)) { CacheFile = Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), cacheFile); CacheDirectory = Path.GetDirectoryName(CacheFile); Logger.Active.Log(string.Format("[Kopernicus]: {0} is using custom cache file '{1}' in '{2}'", body.name, CacheFile, CacheDirectory)); } Directory.CreateDirectory(CacheDirectory); if (File.Exists(CacheFile) && exportBin) { Logger.Active.Log("[Kopernicus]: Body.PostApply(ConfigNode): Loading cached scaled space mesh: " + body.name); scaledMesh = Utility.DeserializeMesh(CacheFile); Utility.RecalculateTangents(scaledMesh); scaledVersion.GetComponent<MeshFilter>().sharedMesh = scaledMesh; } // Otherwise we have to generate the mesh else { Logger.Active.Log("[Kopernicus]: Body.PostApply(ConfigNode): Generating scaled space mesh: " + body.name); scaledMesh = ComputeScaledSpaceMesh(body, useSpherical ? null : pqs); Utility.RecalculateTangents(scaledMesh); scaledVersion.GetComponent<MeshFilter>().sharedMesh = scaledMesh; if (exportBin) Utility.SerializeMesh(scaledMesh, CacheFile); } // Apply mesh to the body SphereCollider collider = scaledVersion.GetComponent<SphereCollider>(); if (collider != null) collider.radius = rScaled; if (pqs != null && scaledVersion.gameObject != null && scaledVersion.gameObject.transform != null) { scaledVersion.gameObject.transform.localScale = Vector3.one * (float)(pqs.radius / rJool); } } // Generate the scaled space mesh using PQS (all results use scale of 1) public static Mesh ComputeScaledSpaceMesh(CelestialBody body, PQS pqs) { // We need to get the body for Jool (to steal it's mesh) const double rScaledJool = 1000.0f; double rMetersToScaledUnits = (float)(rScaledJool / body.Radius); // Generate a duplicate of the Jool mesh Mesh mesh = Utility.DuplicateMesh(Templates.ReferenceGeosphere); // If this body has a PQS, we can create a more detailed object if (pqs != null) { // first we enable all maps OnDemand.OnDemandStorage.EnableBody(body.bodyName); // In order to generate the scaled space we have to enable the mods. Since this is // a prefab they don't get disabled as kill game performance. To resolve this we // clone the PQS, use it, and then delete it when done GameObject pqsVersionGameObject = UnityEngine.Object.Instantiate(pqs.gameObject) as GameObject; PQS pqsVersion = pqsVersionGameObject.GetComponent<PQS>(); Type[] blacklist = new Type[] { typeof(OnDemand.PQSMod_OnDemandHandler) }; // Deactivate blacklisted Mods foreach (PQSMod mod in pqsVersion.GetComponentsInChildren<PQSMod>(true).Where(m => blacklist.Contains(m.GetType()))) { mod.modEnabled = false; } // Find the PQS mods and enable the PQS-sphere IEnumerable<PQSMod> mods = pqsVersion.GetComponentsInChildren<PQSMod>(true).Where(m => m.modEnabled).OrderBy(m => m.order); pqsVersion.StartUpSphere(); pqsVersion.isBuildingMaps = true; // If we were able to find PQS mods if (mods.Count() > 0) { // Generate the PQS modifications Vector3[] vertices = mesh.vertices; for (int i = 0; i < mesh.vertexCount; i++) { // Get the UV coordinate of this vertex Vector2 uv = mesh.uv[i]; // Since this is a geosphere, normalizing the vertex gives the direction from center center Vector3 direction = vertices[i]; direction.Normalize(); // Build the vertex data object for the PQS mods PQS.VertexBuildData vertex = new PQS.VertexBuildData(); vertex.directionFromCenter = direction; vertex.vertHeight = body.Radius; vertex.u = uv.x; vertex.v = uv.y; // Build from the PQS foreach (PQSMod mod in mods) { mod.OnVertexBuild(vertex); // Why in heaven are there mods who modify height in OnVertexBuild() rather than OnVertexBuildHeight()?!?! mod.OnVertexBuildHeight(vertex); } // Check for sea level if (body.ocean && vertex.vertHeight < body.Radius) vertex.vertHeight = body.Radius; // Adjust the displacement vertices[i] = direction * (float)(vertex.vertHeight * rMetersToScaledUnits); } mesh.vertices = vertices; mesh.RecalculateNormals(); mesh.RecalculateBounds(); } // Cleanup pqsVersion.isBuildingMaps = false; pqsVersion.DeactivateSphere(); UnityEngine.Object.Destroy(pqsVersionGameObject); } // Return the generated scaled space mesh return mesh; } public static void CopyMesh(Mesh source, Mesh dest) { //ProfileTimer.Push("CopyMesh"); Vector3[] verts = new Vector3[source.vertexCount]; source.vertices.CopyTo(verts, 0); dest.vertices = verts; int[] tris = new int[source.triangles.Length]; source.triangles.CopyTo(tris, 0); dest.triangles = tris; Vector2[] uvs = new Vector2[source.uv.Length]; source.uv.CopyTo(uvs, 0); dest.uv = uvs; Vector2[] uv2s = new Vector2[source.uv2.Length]; source.uv2.CopyTo(uv2s, 0); dest.uv2 = uv2s; Vector3[] normals = new Vector3[source.normals.Length]; source.normals.CopyTo(normals, 0); dest.normals = normals; Vector4[] tangents = new Vector4[source.tangents.Length]; source.tangents.CopyTo(tangents, 0); dest.tangents = tangents; Color[] colors = new Color[source.colors.Length]; source.colors.CopyTo(colors, 0); dest.colors = colors; Color32[] colors32 = new Color32[source.colors32.Length]; source.colors32.CopyTo(colors32, 0); dest.colors32 = colors32; //ProfileTimer.Pop("CopyMesh"); } public static Mesh DuplicateMesh(Mesh source) { // Create new mesh object Mesh dest = new Mesh(); //ProfileTimer.Push("CopyMesh"); Vector3[] verts = new Vector3[source.vertexCount]; source.vertices.CopyTo(verts, 0); dest.vertices = verts; int[] tris = new int[source.triangles.Length]; source.triangles.CopyTo(tris, 0); dest.triangles = tris; Vector2[] uvs = new Vector2[source.uv.Length]; source.uv.CopyTo(uvs, 0); dest.uv = uvs; Vector2[] uv2s = new Vector2[source.uv2.Length]; source.uv2.CopyTo(uv2s, 0); dest.uv2 = uv2s; Vector3[] normals = new Vector3[source.normals.Length]; source.normals.CopyTo(normals, 0); dest.normals = normals; Vector4[] tangents = new Vector4[source.tangents.Length]; source.tangents.CopyTo(tangents, 0); dest.tangents = tangents; Color[] colors = new Color[source.colors.Length]; source.colors.CopyTo(colors, 0); dest.colors = colors; Color32[] colors32 = new Color32[source.colors32.Length]; source.colors32.CopyTo(colors32, 0); dest.colors32 = colors32; //ProfileTimer.Pop("CopyMesh"); return dest; } // Taken from Nathankell's RSS Utils.cs; uniformly scaled vertices public static void ScaleVerts(Mesh mesh, float scaleFactor) { //ProfileTimer.Push("ScaleVerts"); Vector3[] vertices = new Vector3[mesh.vertexCount]; for (int i = 0; i < mesh.vertexCount; i++) { Vector3 v = mesh.vertices[i]; v *= scaleFactor; vertices[i] = v; } mesh.vertices = vertices; //ProfileTimer.Pop("ScaleVerts"); } public static void RecalculateTangents(Mesh theMesh) { int vertexCount = theMesh.vertexCount; Vector3[] vertices = theMesh.vertices; Vector3[] normals = theMesh.normals; Vector2[] texcoords = theMesh.uv; int[] triangles = theMesh.triangles; int triangleCount = triangles.Length / 3; var tangents = new Vector4[vertexCount]; var tan1 = new Vector3[vertexCount]; var tan2 = new Vector3[vertexCount]; int tri = 0; for (int i = 0; i < (triangleCount); i++) { int i1 = triangles[tri]; int i2 = triangles[tri + 1]; int i3 = triangles[tri + 2]; Vector3 v1 = vertices[i1]; Vector3 v2 = vertices[i2]; Vector3 v3 = vertices[i3]; Vector2 w1 = texcoords[i1]; Vector2 w2 = texcoords[i2]; Vector2 w3 = texcoords[i3]; float x1 = v2.x - v1.x; float x2 = v3.x - v1.x; float y1 = v2.y - v1.y; float y2 = v3.y - v1.y; float z1 = v2.z - v1.z; float z2 = v3.z - v1.z; float s1 = w2.x - w1.x; float s2 = w3.x - w1.x; float t1 = w2.y - w1.y; float t2 = w3.y - w1.y; float r = 1.0f / (s1 * t2 - s2 * t1); var sdir = new Vector3((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); var tdir = new Vector3((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); tan1[i1] += sdir; tan1[i2] += sdir; tan1[i3] += sdir; tan2[i1] += tdir; tan2[i2] += tdir; tan2[i3] += tdir; tri += 3; } for (int i = 0; i < (vertexCount); i++) { Vector3 n = normals[i]; Vector3 t = tan1[i]; // Gram-Schmidt orthogonalize Vector3.OrthoNormalize(ref n, ref t); tangents[i].x = t.x; tangents[i].y = t.y; tangents[i].z = t.z; // Calculate handedness tangents[i].w = (Vector3.Dot(Vector3.Cross(n, t), tan2[i]) < 0.0f) ? -1.0f : 1.0f; } theMesh.tangents = tangents; } // Serialize a mesh to disk public static void SerializeMesh(Mesh mesh, string path) { // Open an output filestream System.IO.FileStream outputStream = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(outputStream); // Write the vertex count of the mesh writer.Write(mesh.vertices.Length); foreach (Vector3 vertex in mesh.vertices) { writer.Write(vertex.x); writer.Write(vertex.y); writer.Write(vertex.z); } writer.Write(mesh.uv.Length); foreach (Vector2 uv in mesh.uv) { writer.Write(uv.x); writer.Write(uv.y); } writer.Write(mesh.triangles.Length); foreach (int triangle in mesh.triangles) { writer.Write(triangle); } // Finish writing writer.Close(); outputStream.Close(); } // Deserialize a mesh from disk public static Mesh DeserializeMesh(string path) { System.IO.FileStream inputStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader reader = new System.IO.BinaryReader(inputStream); // Get the vertices int count = reader.ReadInt32(); Vector3[] vertices = new Vector3[count]; for (int i = 0; i < count; i++) { Vector3 vertex; vertex.x = reader.ReadSingle(); vertex.y = reader.ReadSingle(); vertex.z = reader.ReadSingle(); vertices[i] = vertex; } // Get the uvs int uv_count = reader.ReadInt32(); Vector2[] uvs = new Vector2[uv_count]; for (int i = 0; i < uv_count; i++) { Vector2 uv; uv.x = reader.ReadSingle(); uv.y = reader.ReadSingle(); uvs[i] = uv; } // Get the triangles int tris_count = reader.ReadInt32(); int[] triangles = new int[tris_count]; for (int i = 0; i < tris_count; i++) triangles[i] = reader.ReadInt32(); // Close reader.Close(); inputStream.Close(); // Create the mesh Mesh m = new Mesh(); m.vertices = vertices; m.triangles = triangles; m.uv = uvs; m.RecalculateNormals(); m.RecalculateBounds(); return m; } // Credit goes to Kragrathea. public static Texture2D BumpToNormalMap(Texture2D source, float strength) { strength = Mathf.Clamp(strength, 0.0F, 10.0F); var result = new Texture2D(source.width, source.height, TextureFormat.ARGB32, true); for (int by = 0; by < result.height; by++) { for (var bx = 0; bx < result.width; bx++) { var xLeft = source.GetPixel(bx - 1, by).grayscale * strength; var xRight = source.GetPixel(bx + 1, by).grayscale * strength; var yUp = source.GetPixel(bx, by - 1).grayscale * strength; var yDown = source.GetPixel(bx, by + 1).grayscale * strength; var xDelta = ((xLeft - xRight) + 1) * 0.5f; var yDelta = ((yUp - yDown) + 1) * 0.5f; result.SetPixel(bx, by, new Color(yDelta, yDelta, yDelta, xDelta)); } } result.Apply(); return result; } // Convert latitude-longitude-altitude with body radius to a vector. public static Vector3 LLAtoECEF(double lat, double lon, double alt, double radius) { const double degreesToRadians = Math.PI / 180.0; lat = (lat - 90) * degreesToRadians; lon *= degreesToRadians; double x, y, z; double n = radius; // for now, it's still a sphere, so just the radius x = (n + alt) * -1.0 * Math.Sin(lat) * Math.Cos(lon); y = (n + alt) * Math.Cos(lat); // for now, it's still a sphere, so no eccentricity z = (n + alt) * -1.0 * Math.Sin(lat) * Math.Sin(lon); return new Vector3((float)x, (float)y, (float)z); } public static bool TextureExists(string path) { path = KSPUtil.ApplicationRootPath + "GameData/" + path; return System.IO.File.Exists(path); } public static Texture2D LoadTexture(string path, bool compress, bool upload, bool unreadable) { Texture2D map = null; path = KSPUtil.ApplicationRootPath + "GameData/" + path; if (System.IO.File.Exists(path)) { bool uncaught = true; try { if (path.ToLower().EndsWith(".dds")) { // Borrowed from stock KSP 1.0 DDS loader (hi Mike!) // Also borrowed the extra bits from Sarbian. byte[] buffer = System.IO.File.ReadAllBytes(path); System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(new System.IO.MemoryStream(buffer)); uint num = binaryReader.ReadUInt32(); if (num == DDSHeaders.DDSValues.uintMagic) { DDSHeaders.DDSHeader dDSHeader = new DDSHeaders.DDSHeader(binaryReader); if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10) { new DDSHeaders.DDSHeaderDX10(binaryReader); } bool alpha = (dDSHeader.dwFlags & 0x00000002) != 0; bool fourcc = (dDSHeader.dwFlags & 0x00000004) != 0; bool rgb = (dDSHeader.dwFlags & 0x00000040) != 0; bool alphapixel = (dDSHeader.dwFlags & 0x00000001) != 0; bool luminance = (dDSHeader.dwFlags & 0x00020000) != 0; bool rgb888 = dDSHeader.ddspf.dwRBitMask == 0x000000ff && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x00ff0000; //bool bgr888 = dDSHeader.ddspf.dwRBitMask == 0x00ff0000 && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x000000ff; bool rgb565 = dDSHeader.ddspf.dwRBitMask == 0x0000F800 && dDSHeader.ddspf.dwGBitMask == 0x000007E0 && dDSHeader.ddspf.dwBBitMask == 0x0000001F; bool argb4444 = dDSHeader.ddspf.dwABitMask == 0x0000f000 && dDSHeader.ddspf.dwRBitMask == 0x00000f00 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x0000000f; bool rbga4444 = dDSHeader.ddspf.dwABitMask == 0x0000000f && dDSHeader.ddspf.dwRBitMask == 0x0000f000 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x00000f00; bool mipmap = (dDSHeader.dwCaps & DDSHeaders.DDSPixelFormatCaps.MIPMAP) != (DDSHeaders.DDSPixelFormatCaps)0u; bool isNormalMap = ((dDSHeader.ddspf.dwFlags & 524288u) != 0u || (dDSHeader.ddspf.dwFlags & 2147483648u) != 0u); if (fourcc) { if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT1) { map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT1, mipmap); map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT3) { map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap); map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT5) { map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT5, mipmap); map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT2) { Debug.Log("[Kopernicus]: DXT2 not supported" + path); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT4) { Debug.Log("[Kopernicus]: DXT4 not supported: " + path); } else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10) { Debug.Log("[Kopernicus]: DX10 dds not supported: " + path); } else fourcc = false; } if(!fourcc) { TextureFormat textureFormat = TextureFormat.ARGB32; bool ok = true; if (rgb && (rgb888 /*|| bgr888*/)) { // RGB or RGBA format textureFormat = alphapixel ? TextureFormat.RGBA32 : TextureFormat.RGB24; } else if (rgb && rgb565) { // Nvidia texconv B5G6R5_UNORM textureFormat = TextureFormat.RGB565; } else if (rgb && alphapixel && argb4444) { // Nvidia texconv B4G4R4A4_UNORM textureFormat = TextureFormat.ARGB4444; } else if (rgb && alphapixel && rbga4444) { textureFormat = TextureFormat.RGBA4444; } else if (!rgb && alpha != luminance) { // A8 format or Luminance 8 textureFormat = TextureFormat.Alpha8; } else { ok = false; Debug.Log("[Kopernicus]: Only DXT1, DXT5, A8, RGB24, RGBA32, RGB565, ARGB4444 and RGBA4444 are supported"); } if (ok) { map = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap); map.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position))); } } if (map != null) if (upload) map.Apply(false, unreadable); } else Debug.Log("[Kopernicus]: Bad DDS header."); } else { map = new Texture2D(2, 2); map.LoadImage(System.IO.File.ReadAllBytes(path)); if (compress) map.Compress(true); if (upload) map.Apply(false, unreadable); } } catch (Exception e) { uncaught = false; Debug.Log("[Kopernicus]: failed to load " + path + " with exception " + e.Message); } if (map == null && uncaught) { Debug.Log("[Kopernicus]: failed to load " + path); } map.name = path.Remove(0, (KSPUtil.ApplicationRootPath + "GameData/").Length); } else Debug.Log("[Kopernicus]: texture does not exist! " + path); return map; } public static MapSO FindMapSO(string url, bool cbMap) { if (cbMap) { string name = url.Replace("BUILTIN/", ""); CBAttributeMapSO map = Resources.FindObjectsOfTypeAll<CBAttributeMapSO>().First(m => m.MapName == name); return map; } MapSO retVal = null; bool modFound = false; string trim = url.Replace("BUILTIN/", ""); string mBody = Regex.Replace(trim, @"/.*", ""); trim = Regex.Replace(trim, mBody + "/", ""); string mTypeName = Regex.Replace(trim, @"/.*", ""); string mName = Regex.Replace(trim, mTypeName + "/", ""); PSystemBody body = FindBody(PSystemManager.Instance.systemPrefab.rootBody, mBody); if (body != null && body.pqsVersion != null) { Type mType = null; try { mType = Type.GetType(mTypeName + ", Assembly-CSharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); } catch (Exception e) { Logger.Active.Log("MapSO grabber: Tried to grab " + url + " but type not found. VertexHeight type for reference = " + typeof(PQSMod_VertexHeightMap).FullName + ". Exception: " + e); } if (mType != null) { PQSMod[] mods = body.pqsVersion.GetComponentsInChildren<PQSMod>(true).Where(m => m.GetType() == mType).ToArray(); foreach (PQSMod m in mods) { if (m.name != mName) continue; modFound = true; foreach (FieldInfo fi in m.GetType().GetFields()) { if (fi.FieldType.Equals(typeof(MapSO))) { retVal = fi.GetValue(m) as MapSO; break; } } } } } else Logger.Active.Log("MapSO grabber: Tried to grab " + url + " but body not found."); if (retVal == null) { if (modFound) Logger.Active.Log("MapSO grabber: Tried to grab " + url + " but mods of correct name and type lack MapSO."); else Logger.Active.Log("MapSO grabber: Tried to grab " + url + " but could not find PQSMod of that type of the given name"); } retVal.name = url; return retVal; } /// <summary> /// Will remove all mods of given types (or all, if types null) /// </summary> /// <param name="types">If null, will remove all mods except blacklisted mods</param> /// <param name="p">PQS to remove from</param> /// <param name="blacklist">list of mod types to not remove (optional)</param> public static void RemoveModsOfType(List<Type> types, PQS p, List<Type> blacklist = null) { Logger.Active.Log("Removing mods from pqs " + p.name); List<PQSMod> cpMods = p.GetComponentsInChildren<PQSMod>(true).ToList(); bool addTypes = (types == null); if(addTypes) types = new List<Type>(); if (blacklist == null) { Logger.Active.Log("Creating blacklist"); blacklist = new List<Type>(); if(!types.Contains(typeof(PQSMod_CelestialBodyTransform))) blacklist.Add(typeof(PQSMod_CelestialBodyTransform)); if(!types.Contains(typeof(PQSMod_MaterialSetDirection))) blacklist.Add(typeof(PQSMod_MaterialSetDirection)); if(!types.Contains(typeof(PQSMod_UVPlanetRelativePosition))) blacklist.Add(typeof(PQSMod_UVPlanetRelativePosition)); if(!types.Contains(typeof(PQSMod_QuadMeshColliders))) blacklist.Add(typeof(PQSMod_QuadMeshColliders)); Logger.Active.Log("Blacklist count = " + blacklist.Count); } if (addTypes) { Logger.Active.Log("Adding all found PQSMods in pqs " + p.name); foreach(PQSMod m in cpMods) { Type mType = m.GetType(); if (!types.Contains(mType) && !blacklist.Contains(mType)) { Logger.Active.Log("Adding to removelist: " + mType); types.Add(mType); } } } List<GameObject> toCheck = new List<GameObject>(); foreach (Type mType in types) { List<PQSMod> mods = cpMods.Where(m => m.GetType() == mType).ToList(); foreach (PQSMod delMod in mods) { if (delMod != null) { Logger.Active.Log("Removed mod " + mType.ToString()); if (!toCheck.Contains(delMod.gameObject)) toCheck.Add(delMod.gameObject); delMod.sphere = null; cpMods.Remove(delMod); PQSMod.DestroyImmediate(delMod); } } } RemoveEmptyGO(toCheck); } static public void RemoveEmptyGO(List<GameObject> toCheck) { int oCount = toCheck.Count; int nCount = oCount; List<GameObject> toDestroy = new List<GameObject>(); do { oCount = nCount; foreach (GameObject go in toCheck) { if (go.transform.childCount == 0) { Component[] comps = go.GetComponents<Component>(); if (comps.Length == 0 || (comps.Length == 1 && comps[0].GetType() == typeof(Transform))) toDestroy.Add(go); } } foreach (GameObject go in toDestroy) { toCheck.Remove(go); GameObject.DestroyImmediate(go); } toDestroy.Clear(); nCount = toCheck.Count; } while (nCount != oCount && nCount > 0); } static public void CBTCheck(PSystemBody body) { if (body.pqsVersion != null) { if (body.pqsVersion.GetComponentsInChildren<PQSMod_CelestialBodyTransform>().Length > 0) Logger.Default.Log("Body " + body.name + " has CBT."); else { PQSMod_CelestialBodyTransform cbt = body.pqsVersion.GetComponentsInChildren(typeof(PQSMod_CelestialBodyTransform), true).FirstOrDefault() as PQSMod_CelestialBodyTransform; if (cbt == null) { Logger.Default.Log("Body " + body.name + " *** LACKS CBT ***"); DumpDownwards(body.pqsVersion.transform, "*"); } else { cbt.enabled = true; cbt.modEnabled = true; cbt.sphere = body.pqsVersion; Logger.Default.Log("Body " + body.name + " lacks active CBT, activated."); } } } if (body.children != null) foreach (PSystemBody b in body.children) CBTCheck(b); } // Converts an unreadable texture into a readable one public static Texture2D CreateReadable(Texture2D original) { // Checks if (original == null) return null; if (original.width == 0 || original.height == 0) return null; // Create the new texture Texture2D finalTexture = new Texture2D(original.width, original.height); // isn't read or writeable ... we'll have to get tricksy RenderTexture rt = RenderTexture.GetTemporary(original.width, original.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB, 1); Graphics.Blit(original, rt); RenderTexture.active = rt; // Load new texture finalTexture.ReadPixels(new Rect(0, 0, finalTexture.width, finalTexture.height), 0, 0); // Kill the old one RenderTexture.active = null; RenderTexture.ReleaseTemporary(rt); // Return return finalTexture; } // Runs a function recursively public static TOut DoRecursive<TIn, TOut>(TIn start, Func<TIn, IEnumerable<TIn>> selector, Func<TOut, bool> check, Func<TIn, TOut> action) { TOut tout = action(start); if (check(tout)) return tout; foreach (TIn tin in selector(start)) { tout = DoRecursive(tin, selector, check, action); if (check(tout)) return tout; } return default(TOut); } // Runs a function recursively public static void DoRecursive<T>(T start, Func<T, IEnumerable<T>> selector, Action<T> action) { DoRecursive<T, object>(start, selector, tout => false, tin => { action(tin); return null; }); } /** * Enumerable class to iterate over parents. Defined to allow us to use Linq * and predicates. * * See examples: http://msdn.microsoft.com/en-us/library/78dfe2yb(v=vs.110).aspx **/ public class ParentEnumerator : IEnumerable<GameObject> { // The game object who and whose parents are going to be enumerated private GameObject initial; // Enumerator class public class Enumerator : IEnumerator<GameObject> { public GameObject original; public GameObject current; public Enumerator(GameObject initial) { this.original = initial; this.current = this.original; } public bool MoveNext() { if (current.transform.parent != null && current.transform.parent == current.transform) { current = current.transform.parent.gameObject; return true; } else { return false; } } public void Reset() { current = original; } void IDisposable.Dispose() { } public GameObject Current { get { return current; } } object IEnumerator.Current { get { return Current; } } } public Enumerator GetEnumerator() { return new Enumerator(initial); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } IEnumerator<GameObject> IEnumerable<GameObject>.GetEnumerator() { return (IEnumerator<GameObject>)GetEnumerator(); } public ParentEnumerator(GameObject initial) { this.initial = initial; } } /** * Enumerable class to iterate over parents. Defined to allow us to use Linq * and predicates. Allows this fun operation to find a sun closest to us under * the tree * * Utility.ReferenceBodyEnumerator e = new Utility.ReferenceBodyEnumerator(FlightGlobals.currentMainBody); * CelestialBody sun = e.First(p => p.GetComponentsInChildren(typeof (ScaledSun), true).Length > 0); * * See examples: http://msdn.microsoft.com/en-us/library/78dfe2yb(v=vs.110).aspx **/ public class ReferenceBodyEnumerator : IEnumerable<CelestialBody> { // The game object who and whose parents are going to be enumerated private CelestialBody initial; // Enumerator class public class Enumerator : IEnumerator<CelestialBody> { public CelestialBody original; public CelestialBody current; public Enumerator(CelestialBody initial) { this.original = initial; this.current = this.original; } public bool MoveNext() { if (current.referenceBody != null) { current = current.referenceBody; return true; } return false; } public void Reset() { current = original; } void IDisposable.Dispose() { } public CelestialBody Current { get { return current; } } object IEnumerator.Current { get { return Current; } } } public Enumerator GetEnumerator() { return new Enumerator(initial); } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } IEnumerator<CelestialBody> IEnumerable<CelestialBody>.GetEnumerator() { return (IEnumerator<CelestialBody>)GetEnumerator(); } public ReferenceBodyEnumerator(CelestialBody initial) { this.initial = initial; } } public static void Log(object s) { Logger.Active.Log(s); } } }
lgpl-3.0
opensagres/xdocreport.samples
samples/fr.opensagres.xdocreport.samples.docx.converters/src/fr/opensagres/xdocreport/samples/docx/converters/xhtml/ConvertDocxResumeToXHTML.java
9503
/** * GNU LESSER GENERAL PUBLIC LICENSE * Version 3, 29 June 2007 * * Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> * Everyone is permitted to copy and distribute verbatim copies * of this license document, but changing it is not allowed. * * * This version of the GNU Lesser General Public License incorporates * the terms and conditions of version 3 of the GNU General Public * License, supplemented by the additional permissions listed below. * * 0. Additional Definitions. * * As used herein, "this License" refers to version 3 of the GNU Lesser * General Public License, and the "GNU GPL" refers to version 3 of the GNU * General Public License. * * "The Library" refers to a covered work governed by this License, * other than an Application or a Combined Work as defined below. * * An "Application" is any work that makes use of an interface provided * by the Library, but which is not otherwise based on the Library. * Defining a subclass of a class defined by the Library is deemed a mode * of using an interface provided by the Library. * * A "Combined Work" is a work produced by combining or linking an * Application with the Library. The particular version of the Library * with which the Combined Work was made is also called the "Linked * Version". * * The "Minimal Corresponding Source" for a Combined Work means the * Corresponding Source for the Combined Work, excluding any source code * for portions of the Combined Work that, considered in isolation, are * based on the Application, and not on the Linked Version. * * The "Corresponding Application Code" for a Combined Work means the * object code and/or source code for the Application, including any data * and utility programs needed for reproducing the Combined Work from the * Application, but excluding the System Libraries of the Combined Work. * * 1. Exception to Section 3 of the GNU GPL. * * You may convey a covered work under sections 3 and 4 of this License * without being bound by section 3 of the GNU GPL. * * 2. Conveying Modified Versions. * * If you modify a copy of the Library, and, in your modifications, a * facility refers to a function or data to be supplied by an Application * that uses the facility (other than as an argument passed when the * facility is invoked), then you may convey a copy of the modified * version: * * a) under this License, provided that you make a good faith effort to * ensure that, in the event an Application does not supply the * function or data, the facility still operates, and performs * whatever part of its purpose remains meaningful, or * * b) under the GNU GPL, with none of the additional permissions of * this License applicable to that copy. * * 3. Object Code Incorporating Material from Library Header Files. * * The object code form of an Application may incorporate material from * a header file that is part of the Library. You may convey such object * code under terms of your choice, provided that, if the incorporated * material is not limited to numerical parameters, data structure * layouts and accessors, or small macros, inline functions and templates * (ten or fewer lines in length), you do both of the following: * * a) Give prominent notice with each copy of the object code that the * Library is used in it and that the Library and its use are * covered by this License. * * b) Accompany the object code with a copy of the GNU GPL and this license * document. * * 4. Combined Works. * * You may convey a Combined Work under terms of your choice that, * taken together, effectively do not restrict modification of the * portions of the Library contained in the Combined Work and reverse * engineering for debugging such modifications, if you also do each of * the following: * * a) Give prominent notice with each copy of the Combined Work that * the Library is used in it and that the Library and its use are * covered by this License. * * b) Accompany the Combined Work with a copy of the GNU GPL and this license * document. * * c) For a Combined Work that displays copyright notices during * execution, include the copyright notice for the Library among * these notices, as well as a reference directing the user to the * copies of the GNU GPL and this license document. * * d) Do one of the following: * * 0) Convey the Minimal Corresponding Source under the terms of this * License, and the Corresponding Application Code in a form * suitable for, and under terms that permit, the user to * recombine or relink the Application with a modified version of * the Linked Version to produce a modified Combined Work, in the * manner specified by section 6 of the GNU GPL for conveying * Corresponding Source. * * 1) Use a suitable shared library mechanism for linking with the * Library. A suitable mechanism is one that (a) uses at run time * a copy of the Library already present on the user's computer * system, and (b) will operate properly with a modified version * of the Library that is interface-compatible with the Linked * Version. * * e) Provide Installation Information, but only if you would otherwise * be required to provide such information under section 6 of the * GNU GPL, and only to the extent that such information is * necessary to install and execute a modified version of the * Combined Work produced by recombining or relinking the * Application with a modified version of the Linked Version. (If * you use option 4d0, the Installation Information must accompany * the Minimal Corresponding Source and Corresponding Application * Code. If you use option 4d1, you must provide the Installation * Information in the manner specified by section 6 of the GNU GPL * for conveying Corresponding Source.) * * 5. Combined Libraries. * * You may place library facilities that are a work based on the * Library side by side in a single library together with other library * facilities that are not Applications and are not covered by this * License, and convey such a combined library under terms of your * choice, if you do both of the following: * * a) Accompany the combined library with a copy of the same work based * on the Library, uncombined with any other library facilities, * conveyed under the terms of this License. * * b) Give prominent notice with the combined library that part of it * is a work based on the Library, and explaining where to find the * accompanying uncombined form of the same work. * * 6. Revised Versions of the GNU Lesser General Public License. * * The Free Software Foundation may publish revised and/or new versions * of the GNU Lesser General Public License from time to time. Such new * versions will be similar in spirit to the present version, but may * differ in detail to address new problems or concerns. * * Each version is given a distinguishing version number. If the * Library as you received it specifies that a certain numbered version * of the GNU Lesser General Public License "or any later version" * applies to it, you have the option of following the terms and * conditions either of that published version or of any later version * published by the Free Software Foundation. If the Library as you * received it does not specify a version number of the GNU Lesser * General Public License, you may choose any version of the GNU Lesser * General Public License ever published by the Free Software Foundation. * * If the Library as you received it specifies that a proxy can decide * whether future versions of the GNU Lesser General Public License shall * apply, that proxy's public statement of acceptance of any version is * permanent authorization for you to choose that version for the * Library. */ package fr.opensagres.xdocreport.samples.docx.converters.xhtml; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import org.apache.poi.xwpf.usermodel.XWPFDocument; import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter; import fr.opensagres.xdocreport.samples.docx.converters.Data; public class ConvertDocxResumeToXHTML { public static void main( String[] args ) { long startTime = System.currentTimeMillis(); try { // 1) Load docx with POI XWPFDocument XWPFDocument document = new XWPFDocument( Data.class.getResourceAsStream( "DocxResume.docx" ) ); // 2) Convert POI XWPFDocument 2 PDF with iText File outFile = new File( "target/DocxResume.htm" ); outFile.getParentFile().mkdirs(); OutputStream out = new FileOutputStream( outFile ); XHTMLConverter.getInstance().convert( document, out, null ); } catch ( Throwable e ) { e.printStackTrace(); } System.out.println( "Generate DocxResume.htm with " + ( System.currentTimeMillis() - startTime ) + " ms." ); } }
lgpl-3.0
waterguo/antsdb
fish-server/src/main/java/com/antsdb/saltedfish/nosql/MemTablet.java
64195
/*------------------------------------------------------------------------------------------------- _______ __ _ _______ _______ ______ ______ |_____| | \ | | |______ | \ |_____] | | | \_| | ______| |_____/ |_____] Copyright (c) 2016, antsdb.com and/or its affiliates. All rights reserved. *-xguo0<@ This program is free software: you can redistribute it and/or modify it under the terms of the GNU GNU Lesser General Public License, version 3, as published by the Free Software Foundation. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/lgpl-3.0.en.html> -------------------------------------------------------------------------------------------------*/ package com.antsdb.saltedfish.nosql; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiPredicate; import java.util.function.IntPredicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import com.antsdb.saltedfish.cpp.BluntHeap; import com.antsdb.saltedfish.cpp.FileOffset; import com.antsdb.saltedfish.cpp.FishSkipList; import com.antsdb.saltedfish.cpp.KeyBytes; import com.antsdb.saltedfish.cpp.OutOfHeapException; import com.antsdb.saltedfish.cpp.SkipListScanner; import com.antsdb.saltedfish.cpp.Unsafe; import com.antsdb.saltedfish.cpp.VariableLengthLongComparator; import com.antsdb.saltedfish.nosql.Gobbler.DeleteEntry2; import com.antsdb.saltedfish.nosql.Gobbler.DeleteRowEntry2; import com.antsdb.saltedfish.nosql.Gobbler.IndexEntry2; import com.antsdb.saltedfish.nosql.Gobbler.InsertEntry2; import com.antsdb.saltedfish.nosql.Gobbler.LogEntry; import com.antsdb.saltedfish.nosql.Gobbler.PutEntry2; import com.antsdb.saltedfish.nosql.Gobbler.RowUpdateEntry2; import com.antsdb.saltedfish.nosql.Gobbler.UpdateEntry2; import com.antsdb.saltedfish.util.AtomicUtil; import com.antsdb.saltedfish.util.BytesUtil; import com.antsdb.saltedfish.util.CodingError; import com.antsdb.saltedfish.util.ConsoleHelper; import com.antsdb.saltedfish.util.LatencyDetector; import com.antsdb.saltedfish.util.LongLong; import static com.antsdb.saltedfish.util.UberFormatter.*; import com.antsdb.saltedfish.util.UberTimer; import com.antsdb.saltedfish.util.UberUtil; /** * a tablet is a wrapper of skiplist and a composing piece of memtable * * @author wgu0 */ public final class MemTablet implements ConsoleHelper, Recycable, Closeable, LogSpan, LogDependency { static Logger _log = UberUtil.getThisLogger(); static Pattern _ptn = Pattern.compile("^([0-9a-fA-F]{8})-([0-9a-fA-F]{8})\\.tbl$"); static final VariableLengthLongComparator _comp = new VariableLengthLongComparator(); final static long SIG = 0x73746e61; final static byte VERSION = 0; public final static int HEADER_SIZE = 0x100; final static int OFFSET_SIG = 0; final static int OFFSET_CARBONFROZEN = 8; final static int OFFSET_DELETE_MARK = 9; final static int OFFSET_VERSION = 0x10; //final static int OFFSET_START_TRXID = 0x20; //final static int OFFSET_END_TRXID = 0x28; final static int OFFSET_START_ROW = 0x30; final static int OFFSET_END_ROW = 0x38; final static int OFFSET_PARENT = 0x40; final static int MARK_ROLLED_BACK = -1; final static int MARK_ROW_LOCK = -3; /** indicate this is a tomb stone */ protected final static byte TYPE_ROW = 0; /** indicate this is a tomb stone */ protected final static byte TYPE_DELETE = 1; /** indicate this is a locked records */ protected final static byte TYPE_LOCK = 2; /** indicate this is a locked records */ protected final static byte TYPE_INDEX = 3; BluntHeap heap; int size; Humpback humpback; private AtomicInteger gate = new AtomicInteger(); private AtomicLong casRetries = new AtomicLong(); private AtomicLong lockwaits = new AtomicLong(); private AtomicLong errorConcurrencies = new AtomicLong(); private boolean isMutable = true; FishSkipList slist; long base; TrxMan trxman; File file; MemoryMappedFile mmap; AtomicLong startTrx = new AtomicLong(Long.MIN_VALUE); AtomicLong endTrx = new AtomicLong(0); AtomicLong spStart = new AtomicLong(); AtomicLong spEnd = new AtomicLong(); int tableId; int tabletId; StorageTable mtable; SpaceManager sm; public final static class ListNode { private final static int OFFSET_SPACE_POINTER = 0; private final static int OFFSET_TRX_VERSION = 8; private final static int OFFSET_NEXT = 0x10; private final static int OFFSET_TYPE = 0x14; private final static int OFFSET_MISC = 0x15; private final static int OFFSET_ROW_KEY = 0x16; private final static int OFFSET_END = 0x16; private long base; private int offset; public ListNode(long base, int offset) { this.base = base; this.offset = offset; } public long getAddress() { return this.base + this.offset; } public static ListNode create(long base, int offset) { if (offset == 0) { return null; } return new ListNode(base, offset); } static ListNode alloc(BluntHeap heap, long version, long value, int next) { int result = heap.allocOffset(OFFSET_END); ListNode node = new ListNode(heap.getAddress(0), result); node.setVersion(version); node.setSpacePointer(value); node.setNext(next); heap.putByteVolatile(node.offset + OFFSET_TYPE, TYPE_ROW); return node; } public static ListNode allocIndex(BluntHeap heap, long version, long pRowKey, int next) { int keySize = (pRowKey != 0) ? KeyBytes.getRawSize(pRowKey) : 0; int offset = heap.allocOffset(OFFSET_END + keySize); ListNode node = new ListNode(heap.getAddress(0), offset); node.setVersion(version); node.setSpacePointer(Long.MIN_VALUE); node.setNext(next); heap.putByteVolatile(node.offset + OFFSET_TYPE, TYPE_INDEX); Unsafe.copyMemory(pRowKey, heap.getAddress(node.getOffset() + OFFSET_ROW_KEY), keySize); return node; } static long getRowKeyAddress(long base, int offset) { return base + offset + OFFSET_ROW_KEY; } public long getRowKeyAddress() { return this.base + this.offset + OFFSET_ROW_KEY; } long getVersion() { return Unsafe.getLongVolatile(this.base + this.offset + OFFSET_TRX_VERSION); } void setVersion(long trxts) { Unsafe.putLongVolatile(this.base + this.offset + OFFSET_TRX_VERSION, trxts); } long getSpacePointer() { return Unsafe.getLongVolatile(this.base + this.offset + OFFSET_SPACE_POINTER); } void setSpacePointer(long value) { Unsafe.putLongVolatile(this.base + this.offset + OFFSET_SPACE_POINTER, value); } int getNext() { return Unsafe.getIntVolatile(this.base + this.offset + OFFSET_NEXT); } void setNext(int value) { Unsafe.putIntVolatile(this.base + this.offset + OFFSET_NEXT, value); } public ListNode getNextNode() { int next = getNext(); ListNode node = create(this.base, next); return node; } boolean casNext(int oldValue, int newValue) { return Unsafe.compareAndSwapInt(this.base + this.offset + OFFSET_NEXT, oldValue, newValue); } public int getOffset() { return this.offset; } boolean isDeleted() { return getType() == TYPE_DELETE; } void setDeleted(boolean b) { Unsafe.putByteVolatile(this.base + this.offset + OFFSET_TYPE, b ? TYPE_DELETE : TYPE_ROW); } boolean isLocked() { return getType() == TYPE_LOCK; } void setLocked(boolean b) { Unsafe.putByteVolatile(this.base + this.offset + OFFSET_TYPE, TYPE_LOCK); } public boolean isRow() { return getType() == TYPE_ROW; } byte getType() { byte type = Unsafe.getByteVolatile(this.base + this.offset + OFFSET_TYPE); return type; } byte getMisc() { byte misc = Unsafe.getByteVolatile(this.base + this.offset + OFFSET_MISC); return misc; } void setMisc(byte value) { Unsafe.putByteVolatile(this.base + this.offset + OFFSET_MISC, value); } @Override public String toString() { String str = String.format( " %08x [version=%d, sprow=%08x, type=%02x]", this.offset, getVersion(), getSpacePointer(), getType()); return str; } public int copy(BluntHeap heap) { int size = OFFSET_END; if (getType() == TYPE_INDEX) { size = size + KeyBytes.getRawSize(getRowKeyAddress()); } int offset = heap.allocOffset(OFFSET_END + size); long pTarget = heap.getAddress(offset); Unsafe.copyMemory(getAddress(), pTarget, size); ListNode copy = new ListNode(heap.getAddress(0), offset); copy.setNext(0); return offset; } } public static class Scanner extends ScanResult { MemTablet tablet; SkipListScanner upstream; long version; long trxid; long base; TrxMan trxman; private int oNext; private long spNextRow; long spfilterStart; long spfilterEnd; private boolean eof = false; @Override public long getVersion() { ListNode node = new ListNode(base, oNext); long result = node.getVersion(); if (result < -10) { result = this.trxman.getTimestamp(result); } return result; } @Override public long getRowPointer() { if (this.spNextRow <= 1) { return this.spNextRow; } else { return this.tablet.sm.toMemory(this.spNextRow); } } public long getLogSpacePointer() { return this.spNextRow; } @Override public long getKeyPointer() { return this.upstream.getKeyPointer(); } @Override public long getIndexRowKeyPointer() { return ListNode.getRowKeyAddress(base, oNext); } @Override public void rewind() { this.upstream.rewind(); this.oNext = 0; } @Override public boolean eof() { if (this.eof) { return true; } return this.upstream.eof(); } @Override public boolean next() { for (;;) { if (!this.upstream.next()) { this.oNext = 0; return false; } long pHead = this.upstream.getValuePointer(); int oNode = getVersionNode(this.base, trxman, pHead, this.trxid, this.version); if (oNode != 0) { ListNode node = new ListNode(this.base, oNode); long sp = 0; for (;;) { sp = node.getSpacePointer(); // racing condition if (sp != Long.MIN_VALUE) { break; } } if (this.spfilterStart != 0) { if ((sp < this.spfilterStart) || (sp > this.spfilterEnd)) { continue; } } if (!node.isDeleted()) { this.spNextRow = sp; } else { this.spNextRow = 1; } this.oNext = oNode; return true; } } } @Override public long getIndexSuffix() { long pKey = getKeyPointer(); if (pKey == 0) { return 0; } long suffix = KeyBytes.create(pKey).getSuffix(); return suffix; } @Override public byte getMisc() { ListNode node = new ListNode(base, oNext); return node.getMisc(); } @Override public void close() { this.eof = true; } @Override public String toString() { String result = this.tablet.getRowLocation(this.oNext, this.spNextRow, getKeyPointer()); return result; } } public MemTablet(File file) { this.file = file; this.tableId = getTableId(file); this.tabletId = getTabletId(file); this.heap = new BluntHeap(this.base, 0); this.heap.freeze(); } /** * construct a writable instance * @param ns * @param tableId * @param tabletId * @param baseTabletId * @param size * @throws IOException */ MemTablet(File ns, int tableId, int tabletId, int size) throws IOException { this(new File(ns, getFileName(tableId, tabletId))); this.tableId = tableId; this.tabletId = tabletId; this.file = getFile(ns, tableId, tabletId); this.size = size; } void setTransactionManager(TrxMan value) { this.trxman = value; } void setSpaceManager(SpaceManager value) { this.sm = value; } static int getVersionNode(long base, TrxMan trxman, long pHead, long trxid, long version) { int head = Unsafe.getInt(pHead); if (head == 0) { return 0; } for (ListNode i=ListNode.create(base, head); i!=null; i=i.getNextNode()) { long versionInList = i.getVersion(); // first trying to matched version if (versionInList < 0) { if (trxid != versionInList) { if (trxman != null) { versionInList = trxman.getTimestamp(versionInList); } // found a rolled back version, skip if (versionInList == MARK_ROLLED_BACK) { continue; } // found a pending update by another trx, skip if (versionInList < 0) { continue; } } } if (version < versionInList) { // this version is too new, skip continue; } // found a match. make sure this is not row lock if (i.isLocked()) { continue; } // finally found a qualified version return i.getOffset(); } return 0; } /** * * @param pKey * @param trxid * @param version * @param missing * @return space pointer to the row. 0 means not found. 1 means tomb stone */ public long get(long trxid, long version, long pKey, long missing) { long sp = getsp(trxid, version, pKey, missing); return (sp < 10) ? sp : this.sm.toMemory(sp); } long getsp(long trxid, long version, long pKey, long missing) { long pHead = this.slist.get(pKey); if (pHead == 0) { return 0; } int versionNode = getVersionNode(this.base, this.trxman, pHead, trxid, version); if (versionNode == 0) { return missing; } ListNode node = new ListNode(this.base, versionNode); if (node.isDeleted()) { return 1; } else { for (;;) { long result = node.getSpacePointer(); // racing condition if (result != Long.MIN_VALUE) { return result; } } } } public List<ListNode> getVersions(long trxid, long version, long pKey) { List<ListNode> list = new ArrayList<>(); long pHead = this.slist.get(pKey); if (pHead == 0) { return list; } int oHead = Unsafe.getInt(pHead); for (ListNode i=ListNode.create(this.base, oHead); i!=null; i=i.getNextNode()) { list.add(i); } return list; } public int getRow(RowKeeper keeper, long trxid, long version, long pKey) { ListNode node = getListNode(trxid, version, pKey); if (node == null) { return 0; } if (!node.isDeleted()) { long spRow = 0; for (;;) { spRow = node.getSpacePointer(); // racing condition if (spRow != Long.MIN_VALUE) { break; } } long rowVersion = node.getVersion(); if (rowVersion < 0) { rowVersion = this.trxman.getTimestamp(rowVersion); } keeper.pRow = this.sm.toMemory(spRow); keeper.version = rowVersion; if (!Row.checkSignature(keeper.pRow)) { String msg = String.format("invalid row %s", getRowLocation(node.getOffset(), spRow, pKey)); throw new IllegalArgumentException(msg); } return 1; } else { return -1; } } public long getIndex(long trxid, long version, long pKey) { ListNode node = getListNode(trxid, version, pKey); if (node == null) { return 0; } return (!node.isDeleted()) ? node.getRowKeyAddress() : 1; } private ListNode getListNode(long trxid, long version, long pKey) { long pHead = this.slist.get(pKey); if (pHead == 0) { return null; } int oVersion = getVersionNode(this.base, this.trxman, pHead, trxid, version); if (oVersion == 0) { return null; } ListNode node = new ListNode(this.base, oVersion); return node; } Scanner scanAll() { SkipListScanner upstream = null; upstream = this.slist.scan(0, true, 0, true); if (upstream == null) { return null; } Scanner scanner = new Scanner(); scanner.tablet = this; scanner.upstream = upstream; scanner.base = base; scanner.trxman = this.trxman; scanner.version = Long.MAX_VALUE; scanner.trxid = 0; return scanner; } Scanner scanDelta(long spStart, long spEnd) { LongLong span = getLogSpan(); if (span == null) { return null; } if ((spStart > span.y) || (spEnd < span.x)) { return null; } SkipListScanner upstream = null; upstream = this.slist.scan(0, true, 0, true); if (upstream == null) { return null; } Scanner scanner = new Scanner(); scanner.tablet = this; scanner.upstream = upstream; scanner.base = base; scanner.trxman = this.trxman; scanner.version = Long.MAX_VALUE; scanner.trxid = 0; scanner.spfilterStart = spStart; scanner.spfilterEnd = spEnd; return scanner; } Scanner scan(long trxid, long version, long pKeyStart, long pKeyEnd, long options) { boolean includeStart = ScanOptions.includeStart(options); boolean includeEnd = ScanOptions.includeEnd(options); boolean isAscending = ScanOptions.isAscending(options); SkipListScanner upstream = null; if (isAscending) { upstream = this.slist.scan(pKeyStart, includeStart, pKeyEnd, includeEnd); } else { upstream = this.slist.scanReverse(pKeyStart, includeStart, pKeyEnd, includeEnd); } if (upstream == null) { return null; } Scanner scanner = new Scanner(); scanner.tablet = this; scanner.upstream = upstream; scanner.base = base; scanner.trxman = this.trxman; scanner.version = version; scanner.trxid = trxid; return scanner; } void scan(BiPredicate<Long, ListNode> predicate) { SkipListScanner scanner = this.slist.scan(0, true, 0, true); if (scanner == null) { return; } while (scanner.next()) { long pHead = scanner.getValuePointer(); if (pHead == 0) { continue; } int oHead = Unsafe.getInt(pHead); if (oHead == 0) { continue; } ListNode node=ListNode.create(this.base, oHead); if (!predicate.test(scanner.getKeyPointer(), node)) { break; } } } void scanAllVersion(IntPredicate predicate) { SkipListScanner scanner = this.slist.scan(0, true, 0, true); if (scanner == null) { return; } while (scanner.next()) { long pHead = scanner.getValuePointer(); if (pHead == 0) { continue; } int oHead = Unsafe.getInt(pHead); if (oHead == 0) { continue; } for (ListNode i=ListNode.create(this.base, oHead); i!=null; i=i.getNextNode()) { boolean cont = predicate.test(i.getOffset()); if (!cont) { return; } } } } byte getVersion() { return Unsafe.getByte(this.mmap.getAddress() + OFFSET_VERSION); } long getSig() { return Unsafe.getLong(this.mmap.getAddress() + OFFSET_SIG); } /** * * @return Long.MIN_VALUE when there is no pending data */ public long getStartTrxId() { long result = this.startTrx.get(); return result; } /** * * @return 0 means there is no data under transaction */ public long getEndTrxId() { long result = this.endTrx.get(); return result; } public File getFile() { return this.file; } public boolean isPureEmpty() { return this.slist.isEmpty(); } public FishSkipList getSkipList() { return this.slist; } int size() { return this.slist.size(); } boolean validate() { _log.debug("validating {} ...", this.file); AtomicBoolean result = new AtomicBoolean(true); long now = this.trxman.getNewVersion(); scanAllVersion(oVersion -> { ListNode node = new ListNode(this.base, oVersion); long version = node.getVersion(); long value = node.getSpacePointer(); int next = node.getNext(); if (version < -10) { _log.error("negtive version {}:{} [version={} value={} next={}]", this.file.getName(), oVersion, version, value, next); result.set(false); } if (version > 0) { if (version > now) { _log.error("version is larger than it is supposed to be {} [version={} value={} next={}]", this.file.getName(), oVersion, version, value, next); result.set(false); } } return true; }); return result.get(); } String dumpVersions(long pHead) { StringBuilder buf = new StringBuilder(); buf.append(pHead); buf.append(" "); int head = Unsafe.getInt(pHead); buf.append(head); buf.append("\n"); if (head != 0) { for (ListNode i=ListNode.create(this.base, head); i!=null; i=i.getNextNode()) { long version = i.getVersion(); long value = i.getSpacePointer(); int next = i.getNext(); buf.append(i); buf.append("[version="); buf.append(version); buf.append(" value="); buf.append(value); buf.append(" next="); buf.append(next); buf.append("]\n"); } } return buf.toString(); } String dumpKey(long pKey) { byte[] key = KeyBytes.create(pKey).get(); return BytesUtil.toHex(key); } public boolean isClosed() { return this.mmap == null; } protected int getRowStateForWrite( long pKey, int oHead, long trxid, long trxts, Collection<MemTablet> pastTablets) { int state = getRowStateForWrite(oHead, trxid, trxts); if (state != RowState.NONEXIST) { return state; } state = getRowStateForWrite(pKey, trxid, trxts, pastTablets); return state; } private int getRowStateForWrite( long pKey, long trxid, long compare, Collection<MemTablet> pastTablets) { // check history tablets for (MemTablet i:pastTablets) { if (i == this) { continue; } long pHead = i.slist.get(pKey); if (pHead == 0) { continue; } int oHead = Unsafe.getInt(pHead); int rowState = i.getRowStateForWrite(oHead, trxid, compare); if (rowState != RowState.NONEXIST) { return rowState; } } // check minke StorageTable mtable = getMinkeTable(); if (mtable != null) { boolean exist = mtable.exist(pKey); return exist ? RowState.EXIST : RowState.NONEXIST; } return RowState.NONEXIST; } private StorageTable getMinkeTable() { return this.mtable; } private int getRowStateForWrite(int oHead, long trxid, long compare) { for (ListNode i=ListNode.create(this.base, oHead); i!=null; i=i.getNextNode()) { long currentRawVersion; long currentVersion; currentRawVersion = i.getVersion(); // realize the version if this is a trxid if (currentRawVersion < -10) { if (this.trxman != null) { currentVersion = this.trxman.getTimestamp(currentRawVersion); } else { // happens extremely rarely when trxman crashes currentVersion = TrxMan.MARK_ROLLED_BACK; } } else { currentVersion = currentRawVersion; } // skip if it is rolled back if (currentVersion == -1) { // rolled back updates, skip currentVersion = 0; continue; } // lock detection if ((trxid < 0) && (currentVersion < 0)) { if (trxid != currentVersion) { // row is locked by another trx return HumpbackError.LOCK_COMPETITION.ordinal(); } } // compare and update check if (compare != 0) { // expired lock record. skip because it doesn't tell the state. we need the node with data for the // subsequent checks. keep in mind, a key can't be locked without data. if (i.getType() == TYPE_LOCK) { continue; } if ((compare != currentVersion) && (compare != currentRawVersion) && (trxid != currentVersion)) { return HumpbackError.CONCURRENT_UPDATE.ordinal(); } } // found it if (!i.isDeleted()) { return (currentVersion != trxid) ? RowState.EXIST : RowState.EXIST_AND_LOCKED; } else { return RowState.TOMBSTONE; } } return RowState.NONEXIST; } public int getTabletId() { return this.tabletId; } int getTableId() { return this.tableId; } static int getTableId(File file) { Matcher m = _ptn.matcher(file.getName()); if (!m.find()) { return -1; } int tableId = Long.decode("0x" + m.group(1)).intValue(); return tableId; } static int getTabletId(File file) { Matcher m = _ptn.matcher(file.getName()); if (!m.find()) { return -1; } int tabletId = Long.decode("0x" + m.group(2)).intValue(); return tabletId; } @Override public String toString() { return this.file.toString(); } public synchronized void drop() { if (this.file == null) { return; } if (!isClosed()) { if (isMutable && !isCarbonfrozen()) { setDeleted(true); setCarbonfrozen(true); } } close(); _log.debug("deleting file {} ...", this.file); HumpbackUtil.deleteHumpbackFile(this.file); } public long getBaseAddress() { return this.base; } @Override public LongLong getLogSpan() { if (this.spStart.get() == Long.MAX_VALUE) { return null; } LongLong result = new LongLong(this.spStart.get(), this.spEnd.get()); return result; } MemTablet(Humpback humpback, File ns, int tableId, int tabletId, int size) throws IOException { this(ns, tableId, tabletId, size); this.humpback = humpback; if (humpback.getStorageEngine() != null) { this.mtable = humpback.getStorageEngine().getTable(tableId); } setTransactionManager(humpback.trxMan); setSpaceManager(humpback.getSpaceManager()); } void open() throws IOException { if (this.isMutable) { openMutable(); } else { openImmutable(); } } private void openMutable() throws IOException { // creating new file _log.debug("creating new tablet {} ...", file); this.mmap = new MemoryMappedFile(file, size, "rw"); this.base = this.mmap.getAddress(); this.heap = new BluntHeap(this.base, size); this.heap.alloc(HEADER_SIZE); initFile(); // init variables setCarbonfrozen(false); this.spStart.set(Long.MAX_VALUE); this.slist = FishSkipList.alloc(heap, _comp); } private void openImmutable() throws IOException { if (this.file.length() <= (HEADER_SIZE + 8)) { throw new IOException("file " + file + " has incorrect length"); } this.mmap = new MemoryMappedFile(file, "r"); this.base = this.mmap.getAddress(); this.slist = new FishSkipList(this.base, HEADER_SIZE, _comp); this.tableId = getTableId(); if (getSig() != SIG) { throw new IOException("SIG is not found: " + file); } if (getVersion() != VERSION) { throw new IOException("incorrect version is found: " + file); } this.spStart.set(Unsafe.getLong(this.mmap.getAddress() + OFFSET_START_ROW)); this.spEnd.set(Unsafe.getLong(this.mmap.getAddress() + OFFSET_END_ROW)); } void setMutable(boolean value) { if (!isClosed()) { throw new IllegalArgumentException(); } this.isMutable = value; } static File getFile(File ns, int tableId, int tabletId) { File file = new File(ns, getFileName(tableId, tabletId)); return file; } static String getFileName(int tableId, int tabletId) { String name = String.format("%08x-%08x.tbl", tableId, tabletId); return name; } private void initFile() { setSig(SIG); setVersion(VERSION); this.spStart.set(Long.MAX_VALUE); this.spEnd.set(Long.MIN_VALUE); } /** * * @param version * @param pKey * @param row null if this is mark-delete * @return */ HumpbackError put(HumpbackSession hsession, VaporizingRow row, Collection<MemTablet> past, int timeout) { ensureMutable(); try { UberTimer timer = new UberTimer(timeout); this.gate.incrementAndGet(); long version = row.getVersion(); long pKey = row.getKeyAddress(); for (;;) { long pHead = this.slist.put(pKey); int oHeadValue = Unsafe.getIntVolatile(pHead); int rowState = getRowStateForWrite(pKey, oHeadValue, version, 0, past); HumpbackError error = check(pKey, rowState, false, false); if (error == HumpbackError.SUCCESS) { ListNode node = alloc(version, Long.MIN_VALUE, oHeadValue); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } long spRow = 0; if ((rowState == RowState.EXIST) || (rowState == RowState.EXIST_AND_LOCKED)) { spRow = this.humpback.getGobbler().logUpdate(hsession, row, this.tableId); node.setSpacePointer(spRow); } else if ((rowState == RowState.NONEXIST) || (rowState == RowState.TOMBSTONE)) { spRow = this.humpback.getGobbler().logInsert(hsession, row, this.tableId); node.setSpacePointer(spRow); } else { throw new IllegalArgumentException(String.valueOf(rowState)); } trackTrxId(version, node.getOffset()); trackSp(spRow - Gobbler.PutEntry2.getHeaderSize()); return HumpbackError.SUCCESS; } if (!lockWait(error, timer, pKey, oHeadValue, version)) { return error; } } } finally { this.gate.decrementAndGet(); } } /** * recover the operation from the log entry * * @param lpLogEntry not 0 * @return */ HumpbackError recover(long lpLogEntry) { ensureMutable(); try { this.gate.incrementAndGet(); long pLogEntry = this.getSpaceMan().toMemory(lpLogEntry); LogEntry entry = LogEntry.getEntry(lpLogEntry, pLogEntry); if (entry instanceof InsertEntry2) { recover((InsertEntry2)entry); } else if (entry instanceof PutEntry2) { recover((PutEntry2)entry); } else if (entry instanceof UpdateEntry2) { recover((UpdateEntry2)entry); } else if (entry instanceof DeleteRowEntry2) { recover((DeleteRowEntry2)entry); } else if (entry instanceof IndexEntry2) { recover((IndexEntry2)entry); } else if (entry instanceof DeleteEntry2) { recover((DeleteEntry2)entry); } else { UberUtil.error("unable to handle log entry {}", entry); } } finally { this.gate.decrementAndGet(); } return HumpbackError.SUCCESS; } private void recover(IndexEntry2 entry) { long pIndexKey = entry.getIndexKeyAddress(); long pRowKey = entry.getRowKeyAddress(); long version = entry.getTrxid(); byte misc = entry.getMisc(); long lpIndexData = entry.getSpacePointer() + IndexEntry2.getHeaderSize(); for (;;) { long pHead = this.slist.put(pIndexKey); int oHeadValue = Unsafe.getIntVolatile(pHead); ListNode node = ListNode.allocIndex(heap, version, pRowKey, oHeadValue); node.setMisc(misc); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } node.setSpacePointer(lpIndexData); trackTrxId(version, node.getOffset()); trackSp(entry.getSpacePointer()); break; } } private void recover(DeleteEntry2 entry) { long pKey = entry.getKeyAddress(); long version = entry.getTrxid(); long lpEntry = entry.getSpacePointer(); for (;;) { long pHead = this.slist.put(pKey); int oHeadValue = Unsafe.getIntVolatile(pHead); ListNode node = alloc(version, lpEntry, oHeadValue); node.setDeleted(true); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } trackTrxId(version, node.getOffset()); trackSp(lpEntry); break; } } private void recover(DeleteRowEntry2 entry) { recover(entry, true); } private void recover(RowUpdateEntry2 entry) { recover(entry, false); } private void recover(RowUpdateEntry2 entry, boolean isDelete) { long pRow = entry.getRowPointer(); long pKey = Row.getKeyAddress(pRow); long version = entry.getTrxId(); long lpRow = entry.getRowSpacePointer(); for (;;) { long pHead = this.slist.put(pKey); int oHeadValue = Unsafe.getIntVolatile(pHead); ListNode node = alloc(version, lpRow, oHeadValue); node.setDeleted(isDelete); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } trackTrxId(version, node.getOffset()); trackSp(entry.getSpacePointer()); break; } } /** * it is only here for TestMemTableConcurrency * * @deprecated */ HumpbackError recoverPut(long pKey, long version, long sp, Collection<MemTablet> past) { ensureMutable(); try { this.gate.incrementAndGet(); for (;;) { long pHead = this.slist.put(pKey); int oHeadValue = Unsafe.getIntVolatile(pHead); ListNode node = alloc(version, sp, oHeadValue); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } trackTrxId(version, node.getOffset()); trackSp(sp - Gobbler.PutEntry2.getHeaderSize()); return HumpbackError.SUCCESS; } } finally { this.gate.decrementAndGet(); } } HumpbackError insert(HumpbackSession hsession, VaporizingRow row, Collection<MemTablet> pastTablets, int timeout) { ensureMutable(); try { this.gate.incrementAndGet(); UberTimer timer = new UberTimer(timeout); long pKey = row.getKeyAddress(); long version = row.getVersion(); if (version == 0) { throw new IllegalArgumentException(); } for (;;) { long pHead = this.slist.put(pKey); int oHeadValue = Unsafe.getIntVolatile(pHead); int rowState = getRowStateForWrite(pKey, oHeadValue, version, 0, pastTablets); HumpbackError error = check(pKey, rowState, false, true); if (error == HumpbackError.SUCCESS) { ListNode node = alloc(version, Long.MIN_VALUE, oHeadValue); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } long spRow = LatencyDetector.run(_log, "logInsert", ()->{ return this.humpback.getGobbler().logInsert(hsession, row, this.tableId); }); node.setSpacePointer(spRow); trackTrxId(version, node.getOffset()); trackSp(spRow - Gobbler.InsertEntry2.getHeaderSize()); return HumpbackError.SUCCESS; } if (!lockWait(error, timer, pKey, oHeadValue, version)) { return error; } } } finally { this.gate.decrementAndGet(); } } HumpbackError insertIndex( HumpbackSession hsession, long pIndexKey, long version, long pRowKey, Collection<MemTablet> pastTablets, byte misc, int timeout) { if (version == 0) { throw new IllegalArgumentException(); } ensureMutable(); try { this.gate.incrementAndGet(); UberTimer timer = new UberTimer(timeout); for (;;) { long pHead = this.slist.put(pIndexKey); int oHeadValue = Unsafe.getIntVolatile(pHead); int rowState = getRowStateForWrite(pIndexKey, oHeadValue, version, 0, pastTablets); HumpbackError error = check(pIndexKey, rowState, false, true); if (error == HumpbackError.SUCCESS) { ListNode node = ListNode.allocIndex(heap, version, pRowKey, oHeadValue); node.setMisc(misc); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } long sp = this.humpback.getGobbler().logIndex(hsession, tableId, version, pIndexKey, pRowKey, misc); node.setSpacePointer(sp); trackTrxId(version, node.getOffset()); trackSp(sp - Gobbler.IndexEntry2.getHeaderSize()); return HumpbackError.SUCCESS; } if (!lockWait(error, timer, pIndexKey, oHeadValue, version)) { return error; } } } finally { this.gate.decrementAndGet(); } } /** * lock a row * @param trxid * @param pKey */ public HumpbackError lock(long trxid, long pKey, Collection<MemTablet> pastTablets, int timeout) { if (trxid == 0) { throw new IllegalArgumentException(); } try { this.gate.incrementAndGet(); UberTimer timer = new UberTimer(timeout); for (;;) { long pHead = this.slist.put(pKey); int oHeadValue = Unsafe.getIntVolatile(pHead); int rowState = getRowStateForWrite(pKey, oHeadValue, trxid, 0, pastTablets); HumpbackError error = check(pKey, rowState, true, false); if (error == HumpbackError.SUCCESS) { if (rowState == RowState.EXIST_AND_LOCKED) { // avoid repeating locking return HumpbackError.SUCCESS; } ListNode node = alloc(trxid, 0, oHeadValue); node.setLocked(true); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } trackTrxId(trxid, node.getOffset()); return HumpbackError.SUCCESS; } if (!lockWait(error, timer, pKey, oHeadValue, trxid)) { return error; } } } finally { this.gate.decrementAndGet(); } } HumpbackError update(HumpbackSession hsession, VaporizingRow row, long compare, Collection<MemTablet> pastTablets, int timeout) { try { this.gate.incrementAndGet(); UberTimer timer = new UberTimer(timeout); long pKey = row.getKeyAddress(); long version = row.getVersion(); for (;;) { long pHead = this.slist.put(pKey); int oHeadValue = Unsafe.getIntVolatile(pHead); int rowState = getRowStateForWrite(pKey, oHeadValue, version, compare, pastTablets); HumpbackError error = check(pKey, rowState, true, false); if (error == HumpbackError.SUCCESS) { ListNode node = alloc(version, Long.MIN_VALUE, oHeadValue); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } long spRow = this.humpback.getGobbler().logUpdate(hsession, row, this.tableId); node.setSpacePointer(spRow); trackTrxId(version, node.getOffset()); trackSp(spRow - Gobbler.UpdateEntry2.getHeaderSize()); return HumpbackError.SUCCESS; } if (!lockWait(error, timer, pKey, oHeadValue, version)) { return error; } } } finally { this.gate.decrementAndGet(); } } HumpbackError delete(HumpbackSession hsession, long pKey, long trxid, Collection<MemTablet> pastTablets, int timeout) { if (trxid == 0) { throw new IllegalArgumentException(); } ensureMutable(); try { this.gate.incrementAndGet(); UberTimer timer = new UberTimer(timeout); for (;;) { long pHead = this.slist.put(pKey); int oHeadValue = Unsafe.getIntVolatile(pHead); int rowState = getRowStateForWrite(pKey, oHeadValue, trxid, 0, pastTablets); HumpbackError error = check(pKey, rowState, true, false); if (error == HumpbackError.SUCCESS) { ListNode node = alloc(trxid, Long.MIN_VALUE, oHeadValue); node.setDeleted(true); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } int length = KeyBytes.getRawSize(pKey); long lpLogEntry = getGobbler().logDelete(hsession, trxid, this.tableId, pKey, length); node.setSpacePointer(lpLogEntry); trackTrxId(trxid, node.getOffset()); trackSp(lpLogEntry); return HumpbackError.SUCCESS; } if (!lockWait(error, timer, pKey, oHeadValue, trxid)) { return error; } } } finally { this.gate.decrementAndGet(); } } private Gobbler getGobbler() { return this.humpback.getGobbler(); } public HumpbackError deleteRow(HumpbackSession hsession, long pRow, long trxid, ConcurrentLinkedList<MemTablet> tablets, int timeout) { if (trxid == 0) { throw new IllegalArgumentException(); } ensureMutable(); try { long pKey = Row.getKeyAddress(pRow); this.gate.incrementAndGet(); UberTimer timer = new UberTimer(timeout); for (;;) { long pHead = this.slist.put(pKey); int oHeadValue = Unsafe.getIntVolatile(pHead); int rowState = getRowStateForWrite(pKey, oHeadValue, trxid, 0, tablets); HumpbackError error = check(pKey, rowState, true, false); if (error == HumpbackError.SUCCESS) { ListNode node = alloc(trxid, Long.MIN_VALUE, oHeadValue); node.setDeleted(true); if (!casHead(pHead, oHeadValue, node.getOffset())) { this.casRetries.incrementAndGet(); continue; } long sprow = this.humpback.getGobbler().logDeleteRow(hsession, trxid, this.tableId, pRow); node.setSpacePointer(sprow); trackTrxId(trxid, node.getOffset()); trackSp(sprow - Gobbler.DeleteRowEntry2.getHeaderSize()); return HumpbackError.SUCCESS; } if (!lockWait(error, timer, pKey, oHeadValue, trxid)) { return error; } } } finally { this.gate.decrementAndGet(); } } private HumpbackError check(long pKey, int rowState, boolean mustExist, boolean mustNotExist) { if (rowState == HumpbackError.CONCURRENT_UPDATE.ordinal()) { return HumpbackError.CONCURRENT_UPDATE; } else if (rowState == HumpbackError.LOCK_COMPETITION.ordinal()) { return HumpbackError.LOCK_COMPETITION; } if (mustExist) { if ((rowState != RowState.EXIST) && (rowState != RowState.EXIST_AND_LOCKED)) { return HumpbackError.MISSING; } } if (mustNotExist) { if ((rowState != RowState.NONEXIST) && (rowState != RowState.TOMBSTONE)) { return HumpbackError.EXISTS; } } return HumpbackError.SUCCESS; } private String getKeySpec(long pKey) { String result = String.valueOf(this.tableId) + ":" + KeyBytes.toString(pKey); return result; } private boolean casHead(long pHead, int oOldValue, int oNewValue) { return Unsafe.compareAndSwapInt(pHead, oOldValue, oNewValue); } public void testEscape(VaporizingRow row) { this.slist.testEscape(row); } /** * convert trx id to trx timestamp * * @param force force rendering even if the tablet is not frozen * @return */ synchronized void render(long lastClosed) { if (isCarbonfrozen()) { return; } // check if there is any data available for rendering long startTrxId = this.startTrx.get(); if ((startTrxId == Long.MIN_VALUE) || (startTrxId < lastClosed)) { return; } // reset startTrx and endTrx _log.trace("rendering {} from trxid {} ...", this.file, lastClosed); this.startTrx.set(Long.MIN_VALUE); this.endTrx.set(0); AtomicLong minTrxId = new AtomicLong(0); AtomicLong maxTrxId = new AtomicLong(Long.MIN_VALUE); // scan all values and realize trx id AtomicInteger count = new AtomicInteger(); long now = this.trxman.getCurrentVersion(); scanAllVersion(offset -> { // track start sprow and end sprow ListNode node = new ListNode(this.base, offset); long version = node.getVersion(); // skip if this node is already rendered if (version >= -10) { return true; } // render it if (version >= lastClosed) { long trxts = this.trxman.getTimestamp(version); if (trxts >= -10) { if (trxts <= now) { node.setVersion(trxts); count.incrementAndGet(); return true; } else { _log.warn("trxts is newer than current timestamp: ", trxts); } } else { node.setVersion(MARK_ROLLED_BACK); _log.warn("trxts not found for trxid: {} sp {} is set to rollback", version, hex(node.getSpacePointer())); } } else { AtomicUtil.max(maxTrxId, version); AtomicUtil.min(minTrxId, version); } return true; }); // update AtomicUtil.max(this.startTrx, maxTrxId.get()); AtomicUtil.min(this.endTrx, minTrxId.get()); _log.trace("rendering {} ended with startTrxId={} count={}", this.file, this.startTrx.get(), count); } /** * write the tablet to storage * * @param oldestTrxid oldest active trxid in the system * @param force forcing carbonfreeze even if the tablet is not filled up * @return true if success. false if there are pending transactions or already carbonfrozen * @return */ public synchronized boolean carbonfreeze(long oldestTrxid, boolean force) { if (isCarbonfrozen()) { return false; } if (this.mmap.isReadOnly()) { throw new CodingError(this.toString()); } // must be frozen. cant freeze a moving wheel if (!isFrozen()) { if (!force) { return false; } this.heap.freeze(); } // wait until there is no write operations UberTimer timer = new UberTimer(1000); while (this.gate.get() > 1) { if (timer.isExpired()) { return false; } } // if the tablet trx window is beyond the oldest active trx if (getEndTrxId() < oldestTrxid) { return false; } render(oldestTrxid); Unsafe.putLong(this.mmap.getAddress() + OFFSET_START_ROW, this.spStart.get()); Unsafe.putLong(this.mmap.getAddress() + OFFSET_END_ROW, this.spEnd.get()); setCarbonfrozen(true); // write to disk if (this.mmap.isReadOnly()) { throw new CodingError(); } this.mmap.force(); _log.debug("{} is carbonfrozen {} - {}", this.file.getName(), hex(this.spStart.get()), hex(this.spEnd.get())); return true; } @Override public synchronized void close() { if (isClosed()) { return; } boolean isReadOnly = this.mmap.isReadOnly(); this.mmap.close(); this.mmap = null; this.slist = null; this.base = 0; // shrink the file if this is new file if (!isReadOnly) { long fileSize = this.heap.position() + HEADER_SIZE; try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) { raf.setLength(fileSize); } catch (IOException x) { _log.warn("unable to close file {}", this.file, x); } } this.heap = null; } @Override public void recycle() { drop(); } private ListNode alloc(long version, long value, int next) { ListNode result = ListNode.alloc(heap, version, value, next); return result; } private void setVersion(byte v) { Unsafe.putByte(this.mmap.getAddress() + OFFSET_VERSION, v); } private void setSig(long n) { Unsafe.putLong(this.mmap.getAddress() + OFFSET_SIG, n); } void setCarbonfrozen(boolean b) { Unsafe.putByteVolatile(this.mmap.getAddress() + OFFSET_CARBONFROZEN, (byte)(b ? 1 : 0)); } /** * * @return true if the tablet is carbonzied */ public boolean isCarbonfrozen() { byte result = Unsafe.getByteVolatile(this.mmap.getAddress() + OFFSET_CARBONFROZEN); return result != 0; } private void setDeleted(boolean value) { Unsafe.putByteVolatile(this.mmap.getAddress() + OFFSET_DELETE_MARK, (byte)(value ? 1 : 0)); } boolean isDeleted() { byte result = Unsafe.getByteVolatile(this.mmap.getAddress() + OFFSET_DELETE_MARK); return result != 0; } /** * * @return true if the tablet is frozen */ public boolean isFrozen() { return this.heap.isFull() && (this.gate.get() == 0); } @SuppressWarnings("unused") private final SpaceManager getSpaceMan() { return this.humpback.getSpaceManager(); } private boolean lockWait(HumpbackError error, UberTimer timer, long pKey, int oHeadValue, long trxid) { if (Thread.interrupted()) { throw new HumpbackException("thread killed"); } if (error == HumpbackError.LOCK_COMPETITION) { this.lockwaits.incrementAndGet(); if (!timer.isExpired()) { try { ListNode node = new ListNode(this.base, oHeadValue); registerLock(trxid, node.getVersion(), pKey, oHeadValue); Thread.sleep(0, 10000); } catch (InterruptedException e) { throw new HumpbackException("thread killed"); } return true; } else { ListNode node = new ListNode(this.base, oHeadValue); throw new HumpbackException("failed to acquire lock {} oHeadValue={} timeout={} trxid={} node={}", getKeySpec(pKey), hex(oHeadValue), timer.getTimeOut(), trxid, node.toString()); } } else if (error == HumpbackError.CONCURRENT_UPDATE) { this.errorConcurrencies.incrementAndGet(); } return false; } private void registerLock(long requestTrxId, long lockTrxId, long pKey, long pos) { RowLockMonitor monitor = this.humpback.getRowLockMonitor(); if (monitor == null) { return; } monitor.register(requestTrxId, lockTrxId, pKey, this.file, pos); } /** * track the beginning and ending trxid * * @param version */ private void trackTrxId(long trxid, int offset) { // _log.debug("tracking trxid {} {} @{}", getFile(), trxid, offset); if (trxid >= -10) { // if this is not trxid, just return. it is an autonomous trx return; } AtomicUtil.max(this.startTrx, trxid); AtomicUtil.min(this.endTrx, trxid); } /** * track space pointer * @param sp */ private void trackSp(long value) { if (value == 0) { return; } AtomicUtil.min(this.spStart, value); AtomicUtil.max(this.spEnd, value); } public long getCasRetries() { return this.casRetries.get(); } public long getLockWaits() { return this.lockwaits.get(); } public long getCurrentUpdates() { return this.errorConcurrencies.get(); } /** * @param x * @param y */ public void merge(MemTablet x, MemTablet y) { if (x.getTabletId() < y.getTabletId()) { // x must be newer than y in order to must sure version of the same key is following descending order MemTablet t = x; x = y; y = t; } y.scan((Long pKey, ListNode node) -> { copy(pKey, node); return true; }); x.scan((Long pKey, ListNode node) -> { copy(pKey, node); return true; }); } private void copy(Long pKey, ListNode node) { // skip rolled back rows if (node.getVersion() == -1) { return; } // skip lock holder if (node.isLocked()) { return; } // just do it int oCopy = node.copy(this.heap); long pHead = this.slist.put(pKey); Unsafe.putInt(pHead, oCopy); } void setMinkeTable(StorageTable value) { this.mtable = value; } private void ensureMutable() { if (!this.isMutable) { throw new OutOfHeapException(); } } public boolean isMutable() { return this.isMutable; } int getFileSize() { return this.size; } public String getLocation(long trxid, long version, long pKey) { ListNode node = getListNode(trxid, version, pKey); if (node == null) { return null; } long sp = node.getSpacePointer(); return getRowLocation(node.getOffset(), sp, pKey); } private String getRowLocation(int offset, long sp, long pKey) { String result = this.toString() + ":" + hex(offset); result += "->" + this.sm.getLocation(sp); result += " " + KeyBytes.toString(pKey); return result; } public boolean traceIo(long pKey, List<FileOffset> lines) { long pOffset = this.slist.traceIo(pKey, this.file, this.base, lines); if (pOffset == 0) { return false; } int head = Unsafe.getInt(pOffset); if (head == 0) { return false; } for (ListNode i=ListNode.create(base, head); i!=null; i=i.getNextNode()) { lines.add(new FileOffset(this.file, i.getOffset(), "version")); long versionInList = i.getVersion(); if (versionInList < 0) { continue; } long sp = i.getSpacePointer(); lines.add(this.sm.getFileOffset(sp).setNote("row")); return true; } return false; } @Override public long getLogPointer() { LongLong span = this.getLogSpan(); return span!=null ? span.x : Long.MAX_VALUE; } @Override public String getName() { return this.file.getName(); } @Override public List<LogDependency> getChildren() { return null; } }
lgpl-3.0
pcolby/libqtaws
src/wafregional/deletepermissionpolicyresponse.cpp
4553
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "deletepermissionpolicyresponse.h" #include "deletepermissionpolicyresponse_p.h" #include <QDebug> #include <QNetworkReply> #include <QXmlStreamReader> namespace QtAws { namespace WAFRegional { /*! * \class QtAws::WAFRegional::DeletePermissionPolicyResponse * \brief The DeletePermissionPolicyResponse class provides an interace for WAFRegional DeletePermissionPolicy responses. * * \inmodule QtAwsWAFRegional * * <note> * * This is <b>AWS WAF Classic Regional</b> documentation. For more information, see <a * href="https://docs.aws.amazon.com/waf/latest/developerguide/classic-waf-chapter.html">AWS WAF Classic</a> in the * developer * * guide> * * <b>For the latest version of AWS WAF</b>, use the AWS WAFV2 API and see the <a * href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">AWS WAF Developer Guide</a>. With the * latest version, AWS WAF has a single set of endpoints for regional and global use. * * </p </note> * * This is the <i>AWS WAF Regional Classic API Reference</i> for using AWS WAF Classic with the AWS resources, Elastic Load * Balancing (ELB) Application Load Balancers and API Gateway APIs. The AWS WAF Classic actions and data types listed in * the reference are available for protecting Elastic Load Balancing (ELB) Application Load Balancers and API Gateway APIs. * You can use these actions and data types by means of the endpoints listed in <a * href="https://docs.aws.amazon.com/general/latest/gr/rande.html#waf_region">AWS Regions and Endpoints</a>. This guide is * for developers who need detailed information about the AWS WAF Classic API actions, data types, and errors. For detailed * information about AWS WAF Classic features and an overview of how to use the AWS WAF Classic API, see the <a * href="https://docs.aws.amazon.com/waf/latest/developerguide/classic-waf-chapter.html">AWS WAF Classic</a> in the * developer * * \sa WAFRegionalClient::deletePermissionPolicy */ /*! * Constructs a DeletePermissionPolicyResponse object for \a reply to \a request, with parent \a parent. */ DeletePermissionPolicyResponse::DeletePermissionPolicyResponse( const DeletePermissionPolicyRequest &request, QNetworkReply * const reply, QObject * const parent) : WAFRegionalResponse(new DeletePermissionPolicyResponsePrivate(this), parent) { setRequest(new DeletePermissionPolicyRequest(request)); setReply(reply); } /*! * \reimp */ const DeletePermissionPolicyRequest * DeletePermissionPolicyResponse::request() const { Q_D(const DeletePermissionPolicyResponse); return static_cast<const DeletePermissionPolicyRequest *>(d->request); } /*! * \reimp * Parses a successful WAFRegional DeletePermissionPolicy \a response. */ void DeletePermissionPolicyResponse::parseSuccess(QIODevice &response) { //Q_D(DeletePermissionPolicyResponse); QXmlStreamReader xml(&response); /// @todo } /*! * \class QtAws::WAFRegional::DeletePermissionPolicyResponsePrivate * \brief The DeletePermissionPolicyResponsePrivate class provides private implementation for DeletePermissionPolicyResponse. * \internal * * \inmodule QtAwsWAFRegional */ /*! * Constructs a DeletePermissionPolicyResponsePrivate object with public implementation \a q. */ DeletePermissionPolicyResponsePrivate::DeletePermissionPolicyResponsePrivate( DeletePermissionPolicyResponse * const q) : WAFRegionalResponsePrivate(q) { } /*! * Parses a WAFRegional DeletePermissionPolicy response element from \a xml. */ void DeletePermissionPolicyResponsePrivate::parseDeletePermissionPolicyResponse(QXmlStreamReader &xml) { Q_ASSERT(xml.name() == QLatin1String("DeletePermissionPolicyResponse")); Q_UNUSED(xml) ///< @todo } } // namespace WAFRegional } // namespace QtAws
lgpl-3.0
pcolby/libqtaws
src/codecommit/createpullrequestapprovalrulerequest.cpp
15961
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "createpullrequestapprovalrulerequest.h" #include "createpullrequestapprovalrulerequest_p.h" #include "createpullrequestapprovalruleresponse.h" #include "codecommitrequest_p.h" namespace QtAws { namespace CodeCommit { /*! * \class QtAws::CodeCommit::CreatePullRequestApprovalRuleRequest * \brief The CreatePullRequestApprovalRuleRequest class provides an interface for CodeCommit CreatePullRequestApprovalRule requests. * * \inmodule QtAwsCodeCommit * * <fullname>AWS CodeCommit</fullname> * * This is the <i>AWS CodeCommit API Reference</i>. This reference provides descriptions of the operations and data types * for AWS CodeCommit API along with usage * * examples> * * You can use the AWS CodeCommit API to work with the following * * objects> * * Repositories, by calling the * * following> <ul> <li> * * <a>BatchGetRepositories</a>, which returns information about one or more repositories associated with your AWS * * account> </li> <li> * * <a>CreateRepository</a>, which creates an AWS CodeCommit * * repository> </li> <li> * * <a>DeleteRepository</a>, which deletes an AWS CodeCommit * * repository> </li> <li> * * <a>GetRepository</a>, which returns information about a specified * * repository> </li> <li> * * <a>ListRepositories</a>, which lists all AWS CodeCommit repositories associated with your AWS * * account> </li> <li> * * <a>UpdateRepositoryDescription</a>, which sets or updates the description of the * * repository> </li> <li> * * <a>UpdateRepositoryName</a>, which changes the name of the repository. If you change the name of a repository, no other * users of that repository can access it until you send them the new HTTPS or SSH URL to * * use> </li> </ul> * * Branches, by calling the * * following> <ul> <li> * * <a>CreateBranch</a>, which creates a branch in a specified * * repository> </li> <li> * * <a>DeleteBranch</a>, which deletes the specified branch in a repository unless it is the default * * branch> </li> <li> * * <a>GetBranch</a>, which returns information about a specified * * branch> </li> <li> * * <a>ListBranches</a>, which lists all branches for a specified * * repository> </li> <li> * * <a>UpdateDefaultBranch</a>, which changes the default branch for a * * repository> </li> </ul> * * Files, by calling the * * following> <ul> <li> * * <a>DeleteFile</a>, which deletes the content of a specified file from a specified * * branch> </li> <li> * * <a>GetBlob</a>, which returns the base-64 encoded content of an individual Git blob object in a * * repository> </li> <li> * * <a>GetFile</a>, which returns the base-64 encoded content of a specified * * file> </li> <li> * * <a>GetFolder</a>, which returns the contents of a specified folder or * * directory> </li> <li> * * <a>PutFile</a>, which adds or modifies a single file in a specified repository and * * branch> </li> </ul> * * Commits, by calling the * * following> <ul> <li> * * <a>BatchGetCommits</a>, which returns information about one or more commits in a * * repository> </li> <li> * * <a>CreateCommit</a>, which creates a commit for changes to a * * repository> </li> <li> * * <a>GetCommit</a>, which returns information about a commit, including commit messages and author and committer * * information> </li> <li> * * <a>GetDifferences</a>, which returns information about the differences in a valid commit specifier (such as a branch, * tag, HEAD, commit ID, or other fully qualified * * reference)> </li> </ul> * * Merges, by calling the * * following> <ul> <li> * * <a>BatchDescribeMergeConflicts</a>, which returns information about conflicts in a merge between commits in a * * repository> </li> <li> * * <a>CreateUnreferencedMergeCommit</a>, which creates an unreferenced commit between two branches or commits for the * purpose of comparing them and identifying any potential * * conflicts> </li> <li> * * <a>DescribeMergeConflicts</a>, which returns information about merge conflicts between the base, source, and destination * versions of a file in a potential * * merge> </li> <li> * * <a>GetMergeCommit</a>, which returns information about the merge between a source and destination commit. * * </p </li> <li> * * <a>GetMergeConflicts</a>, which returns information about merge conflicts between the source and destination branch in a * pull * * request> </li> <li> * * <a>GetMergeOptions</a>, which returns information about the available merge options between two branches or commit * * specifiers> </li> <li> * * <a>MergeBranchesByFastForward</a>, which merges two branches using the fast-forward merge * * option> </li> <li> * * <a>MergeBranchesBySquash</a>, which merges two branches using the squash merge * * option> </li> <li> * * <a>MergeBranchesByThreeWay</a>, which merges two branches using the three-way merge * * option> </li> </ul> * * Pull requests, by calling the * * following> <ul> <li> * * <a>CreatePullRequest</a>, which creates a pull request in a specified * * repository> </li> <li> * * <a>CreatePullRequestApprovalRule</a>, which creates an approval rule for a specified pull * * request> </li> <li> * * <a>DeletePullRequestApprovalRule</a>, which deletes an approval rule for a specified pull * * request> </li> <li> * * <a>DescribePullRequestEvents</a>, which returns information about one or more pull request * * events> </li> <li> * * <a>EvaluatePullRequestApprovalRules</a>, which evaluates whether a pull request has met all the conditions specified in * its associated approval * * rules> </li> <li> * * <a>GetCommentsForPullRequest</a>, which returns information about comments on a specified pull * * request> </li> <li> * * <a>GetPullRequest</a>, which returns information about a specified pull * * request> </li> <li> * * <a>GetPullRequestApprovalStates</a>, which returns information about the approval states for a specified pull * * request> </li> <li> * * <a>GetPullRequestOverrideState</a>, which returns information about whether approval rules have been set aside * (overriden) for a pull request, and if so, the Amazon Resource Name (ARN) of the user or identity that overrode the * rules and their requirements for the pull * * request> </li> <li> * * <a>ListPullRequests</a>, which lists all pull requests for a * * repository> </li> <li> * * <a>MergePullRequestByFastForward</a>, which merges the source destination branch of a pull request into the specified * destination branch for that pull request using the fast-forward merge * * option> </li> <li> * * <a>MergePullRequestBySquash</a>, which merges the source destination branch of a pull request into the specified * destination branch for that pull request using the squash merge * * option> </li> <li> * * <a>MergePullRequestByThreeWay</a>. which merges the source destination branch of a pull request into the specified * destination branch for that pull request using the three-way merge * * option> </li> <li> * * <a>OverridePullRequestApprovalRules</a>, which sets aside all approval rule requirements for a pull * * request> </li> <li> * * <a>PostCommentForPullRequest</a>, which posts a comment to a pull request at the specified line, file, or * * request> </li> <li> * * <a>UpdatePullRequestApprovalRuleContent</a>, which updates the structure of an approval rule for a pull * * request> </li> <li> * * <a>UpdatePullRequestApprovalState</a>, which updates the state of an approval on a pull * * request> </li> <li> * * <a>UpdatePullRequestDescription</a>, which updates the description of a pull * * request> </li> <li> * * <a>UpdatePullRequestStatus</a>, which updates the status of a pull * * request> </li> <li> * * <a>UpdatePullRequestTitle</a>, which updates the title of a pull * * request> </li> </ul> * * Approval rule templates, by calling the * * following> <ul> <li> * * <a>AssociateApprovalRuleTemplateWithRepository</a>, which associates a template with a specified repository. After the * template is associated with a repository, AWS CodeCommit creates approval rules that match the template conditions on * every pull request created in the specified * * repository> </li> <li> * * <a>BatchAssociateApprovalRuleTemplateWithRepositories</a>, which associates a template with one or more specified * repositories. After the template is associated with a repository, AWS CodeCommit creates approval rules that match the * template conditions on every pull request created in the specified * * repositories> </li> <li> * * <a>BatchDisassociateApprovalRuleTemplateFromRepositories</a>, which removes the association between a template and * specified repositories so that approval rules based on the template are not automatically created when pull requests are * created in those * * repositories> </li> <li> * * <a>CreateApprovalRuleTemplate</a>, which creates a template for approval rules that can then be associated with one or * more repositories in your AWS * * account> </li> <li> * * <a>DeleteApprovalRuleTemplate</a>, which deletes the specified template. It does not remove approval rules on pull * requests already created with the * * template> </li> <li> * * <a>DisassociateApprovalRuleTemplateFromRepository</a>, which removes the association between a template and a repository * so that approval rules based on the template are not automatically created when pull requests are created in the * specified * * repository> </li> <li> * * <a>GetApprovalRuleTemplate</a>, which returns information about an approval rule * * template> </li> <li> * * <a>ListApprovalRuleTemplates</a>, which lists all approval rule templates in the AWS Region in your AWS * * account> </li> <li> * * <a>ListAssociatedApprovalRuleTemplatesForRepository</a>, which lists all approval rule templates that are associated * with a specified * * repository> </li> <li> * * <a>ListRepositoriesForApprovalRuleTemplate</a>, which lists all repositories associated with the specified approval rule * * template> </li> <li> * * <a>UpdateApprovalRuleTemplateDescription</a>, which updates the description of an approval rule * * template> </li> <li> * * <a>UpdateApprovalRuleTemplateName</a>, which updates the name of an approval rule * * template> </li> <li> * * <a>UpdateApprovalRuleTemplateContent</a>, which updates the content of an approval rule * * template> </li> </ul> * * Comments in a repository, by calling the * * following> <ul> <li> * * <a>DeleteCommentContent</a>, which deletes the content of a comment on a commit in a * * repository> </li> <li> * * <a>GetComment</a>, which returns information about a comment on a * * commit> </li> <li> * * <a>GetCommentReactions</a>, which returns information about emoji reactions to * * comments> </li> <li> * * <a>GetCommentsForComparedCommit</a>, which returns information about comments on the comparison between two commit * specifiers in a * * repository> </li> <li> * * <a>PostCommentForComparedCommit</a>, which creates a comment on the comparison between two commit specifiers in a * * repository> </li> <li> * * <a>PostCommentReply</a>, which creates a reply to a * * comment> </li> <li> * * <a>PutCommentReaction</a>, which creates or updates an emoji reaction to a * * comment> </li> <li> * * <a>UpdateComment</a>, which updates the content of a comment on a commit in a * * repository> </li> </ul> * * Tags used to tag resources in AWS CodeCommit (not Git tags), by calling the * * following> <ul> <li> * * <a>ListTagsForResource</a>, which gets information about AWS tags for a specified Amazon Resource Name (ARN) in AWS * * CodeCommit> </li> <li> * * <a>TagResource</a>, which adds or updates tags for a resource in AWS * * CodeCommit> </li> <li> * * <a>UntagResource</a>, which removes tags for a resource in AWS * * CodeCommit> </li> </ul> * * Triggers, by calling the * * following> <ul> <li> * * <a>GetRepositoryTriggers</a>, which returns information about triggers configured for a * * repository> </li> <li> * * <a>PutRepositoryTriggers</a>, which replaces all triggers for a repository and can be used to create or delete * * triggers> </li> <li> * * <a>TestRepositoryTriggers</a>, which tests the functionality of a repository trigger by sending data to the trigger * * target> </li> </ul> * * For information about how to use AWS CodeCommit, see the <a * href="https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html">AWS CodeCommit User * * \sa CodeCommitClient::createPullRequestApprovalRule */ /*! * Constructs a copy of \a other. */ CreatePullRequestApprovalRuleRequest::CreatePullRequestApprovalRuleRequest(const CreatePullRequestApprovalRuleRequest &other) : CodeCommitRequest(new CreatePullRequestApprovalRuleRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a CreatePullRequestApprovalRuleRequest object. */ CreatePullRequestApprovalRuleRequest::CreatePullRequestApprovalRuleRequest() : CodeCommitRequest(new CreatePullRequestApprovalRuleRequestPrivate(CodeCommitRequest::CreatePullRequestApprovalRuleAction, this)) { } /*! * \reimp */ bool CreatePullRequestApprovalRuleRequest::isValid() const { return false; } /*! * Returns a CreatePullRequestApprovalRuleResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * CreatePullRequestApprovalRuleRequest::response(QNetworkReply * const reply) const { return new CreatePullRequestApprovalRuleResponse(*this, reply); } /*! * \class QtAws::CodeCommit::CreatePullRequestApprovalRuleRequestPrivate * \brief The CreatePullRequestApprovalRuleRequestPrivate class provides private implementation for CreatePullRequestApprovalRuleRequest. * \internal * * \inmodule QtAwsCodeCommit */ /*! * Constructs a CreatePullRequestApprovalRuleRequestPrivate object for CodeCommit \a action, * with public implementation \a q. */ CreatePullRequestApprovalRuleRequestPrivate::CreatePullRequestApprovalRuleRequestPrivate( const CodeCommitRequest::Action action, CreatePullRequestApprovalRuleRequest * const q) : CodeCommitRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the CreatePullRequestApprovalRuleRequest * class' copy constructor. */ CreatePullRequestApprovalRuleRequestPrivate::CreatePullRequestApprovalRuleRequestPrivate( const CreatePullRequestApprovalRuleRequestPrivate &other, CreatePullRequestApprovalRuleRequest * const q) : CodeCommitRequestPrivate(other, q) { } } // namespace CodeCommit } // namespace QtAws
lgpl-3.0
cooljc/web-dns-server
index.js
969
/* * index.js * * Copyright 2013 Jon Cross <joncross.cooljc@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ var webserver = require('./webserver'); var dnsserver = require('./dnsserver'); var db = require('./records'); webserver.start(db); dnsserver.start(db);
lgpl-3.0
CastMi/mhdlsim
vvp/compile.cc
61106
/* * Copyright (c) 2001-2014 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ # include "config.h" # include "delay.h" # include "arith.h" # include "compile.h" # include "logic.h" # include "resolv.h" # include "udp.h" # include "symbols.h" # include "codes.h" # include "schedule.h" # include "vpi_priv.h" # include "parse_misc.h" # include "statistics.h" # include "schedule.h" # include <iostream> # include <list> # include <cstdlib> # include <cstring> # include <cassert> #ifdef __MINGW32__ #include <windows.h> #endif # include "ivl_alloc.h" unsigned compile_errors = 0; /* * The opcode table lists all the code mnemonics, along with their * opcode and operand types. The table is written sorted by mnemonic * so that it can be searched by binary search. The opcode_compare * function is a helper function for that lookup. */ enum operand_e { /* Place holder for unused operand */ OA_NONE, /* The operand is a number, an immediate unsigned integer */ OA_NUMBER, /* The operand is a pointer to an array. */ OA_ARR_PTR, /* The operand is a thread bit index or short integer */ OA_BIT1, OA_BIT2, /* The operand is a pointer to code space */ OA_CODE_PTR, OA_CODE_PTR2, /* The operand is a variable or net pointer */ OA_FUNC_PTR, /* The operand is a second functor pointer */ OA_FUNC_PTR2, /* The operand is a VPI handle */ OA_VPI_PTR, /* String */ OA_STRING }; struct opcode_table_s { const char*mnemonic; vvp_code_fun opcode; unsigned argc; enum operand_e argt[OPERAND_MAX]; }; static const struct opcode_table_s opcode_table[] = { { "%abs/wr", of_ABS_WR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%add", of_ADD, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%add/wr", of_ADD_WR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%addi", of_ADDI, 3, {OA_BIT1, OA_BIT2, OA_NUMBER} }, { "%alloc", of_ALLOC, 1, {OA_VPI_PTR, OA_NONE, OA_NONE} }, { "%and", of_AND, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%and/r", of_ANDR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%assign/ar",of_ASSIGN_AR,2,{OA_ARR_PTR,OA_BIT1, OA_NONE} }, { "%assign/ar/d",of_ASSIGN_ARD,2,{OA_ARR_PTR,OA_BIT1, OA_NONE} }, { "%assign/ar/e",of_ASSIGN_ARE,1,{OA_ARR_PTR,OA_NONE, OA_NONE} }, { "%assign/vec4", of_ASSIGN_VEC4, 2, {OA_FUNC_PTR, OA_BIT1, OA_NONE} }, { "%assign/vec4/a/d", of_ASSIGN_VEC4_A_D, 3, {OA_ARR_PTR, OA_BIT1, OA_BIT2} }, { "%assign/vec4/a/e", of_ASSIGN_VEC4_A_E, 2, {OA_ARR_PTR, OA_BIT1, OA_NONE} }, { "%assign/vec4/d", of_ASSIGN_VEC4D, 2, {OA_FUNC_PTR, OA_BIT1, OA_NONE} }, { "%assign/vec4/e", of_ASSIGN_VEC4E, 1, {OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%assign/vec4/off/d",of_ASSIGN_VEC4_OFF_D, 3, {OA_FUNC_PTR, OA_BIT1, OA_BIT2} }, { "%assign/vec4/off/e",of_ASSIGN_VEC4_OFF_E, 2, {OA_FUNC_PTR, OA_BIT1, OA_NONE} }, { "%assign/wr", of_ASSIGN_WR, 2,{OA_VPI_PTR, OA_BIT1, OA_NONE} }, { "%assign/wr/d",of_ASSIGN_WRD,2,{OA_VPI_PTR, OA_BIT1, OA_NONE} }, { "%assign/wr/e",of_ASSIGN_WRE,1,{OA_VPI_PTR, OA_NONE, OA_NONE} }, { "%blend", of_BLEND, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%blend/wr", of_BLEND_WR,0, {OA_NONE, OA_NONE, OA_NONE} }, { "%breakpoint", of_BREAKPOINT, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%callf/obj", of_CALLF_OBJ, 2,{OA_CODE_PTR2,OA_VPI_PTR, OA_NONE} }, { "%callf/real", of_CALLF_REAL, 2,{OA_CODE_PTR2,OA_VPI_PTR, OA_NONE} }, { "%callf/str", of_CALLF_STR, 2,{OA_CODE_PTR2,OA_VPI_PTR, OA_NONE} }, { "%callf/vec4", of_CALLF_VEC4, 2,{OA_CODE_PTR2,OA_VPI_PTR, OA_NONE} }, { "%callf/void", of_CALLF_VOID, 2,{OA_CODE_PTR2,OA_VPI_PTR, OA_NONE} }, { "%cassign/link", of_CASSIGN_LINK, 2,{OA_FUNC_PTR,OA_FUNC_PTR2,OA_NONE} }, { "%cassign/vec4", of_CASSIGN_VEC4, 1,{OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%cassign/vec4/off",of_CASSIGN_VEC4_OFF,2,{OA_FUNC_PTR,OA_BIT1, OA_NONE} }, { "%cassign/wr", of_CASSIGN_WR, 1,{OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%cast2", of_CAST2, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cmp/e", of_CMPE, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cmp/ne", of_CMPNE, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cmp/s", of_CMPS, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cmp/str",of_CMPSTR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cmp/u", of_CMPU, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cmp/wr", of_CMPWR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cmp/ws", of_CMPWS, 2, {OA_BIT1, OA_BIT2, OA_NONE} }, { "%cmp/wu", of_CMPWU, 2, {OA_BIT1, OA_BIT2, OA_NONE} }, { "%cmp/x", of_CMPX, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cmp/z", of_CMPZ, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cmpi/e", of_CMPIE, 3, {OA_BIT1, OA_BIT2, OA_NUMBER} }, { "%cmpi/ne",of_CMPINE, 3, {OA_BIT1, OA_BIT2, OA_NUMBER} }, { "%cmpi/s", of_CMPIS, 3, {OA_BIT1, OA_BIT2, OA_NUMBER} }, { "%cmpi/u", of_CMPIU, 3, {OA_BIT1, OA_BIT2, OA_NUMBER} }, { "%concat/str", of_CONCAT_STR, 0,{OA_NONE, OA_NONE, OA_NONE} }, { "%concat/vec4", of_CONCAT_VEC4, 0,{OA_NONE, OA_NONE, OA_NONE} }, { "%concati/str", of_CONCATI_STR, 1,{OA_STRING,OA_NONE, OA_NONE} }, { "%concati/vec4",of_CONCATI_VEC4,3,{OA_BIT1, OA_BIT2, OA_NUMBER} }, { "%cvt/rv", of_CVT_RV, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cvt/rv/s", of_CVT_RV_S,0, {OA_NONE, OA_NONE, OA_NONE} }, { "%cvt/sr", of_CVT_SR, 1, {OA_BIT1, OA_NONE, OA_NONE} }, { "%cvt/ur", of_CVT_UR, 1, {OA_BIT1, OA_NONE, OA_NONE} }, { "%cvt/vr", of_CVT_VR, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%deassign",of_DEASSIGN,3,{OA_FUNC_PTR, OA_BIT1, OA_BIT2} }, { "%deassign/wr",of_DEASSIGN_WR,1,{OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%debug/thr", of_DEBUG_THR, 1,{OA_STRING, OA_NONE, OA_NONE} }, { "%delay", of_DELAY, 2, {OA_BIT1, OA_BIT2, OA_NONE} }, { "%delayx", of_DELAYX, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%delete/obj",of_DELETE_OBJ,1,{OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%disable", of_DISABLE, 1, {OA_VPI_PTR,OA_NONE, OA_NONE} }, { "%disable/fork",of_DISABLE_FORK,0,{OA_NONE,OA_NONE, OA_NONE} }, { "%div", of_DIV, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%div/s", of_DIV_S, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%div/wr", of_DIV_WR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%dup/real", of_DUP_REAL,0, {OA_NONE, OA_NONE, OA_NONE} }, { "%dup/vec4", of_DUP_VEC4,0, {OA_NONE, OA_NONE, OA_NONE} }, { "%end", of_END, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%evctl", of_EVCTL, 2, {OA_FUNC_PTR, OA_BIT1, OA_NONE} }, { "%evctl/c",of_EVCTLC, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%evctl/i",of_EVCTLI, 2, {OA_FUNC_PTR, OA_BIT1, OA_NONE} }, { "%evctl/s",of_EVCTLS, 2, {OA_FUNC_PTR, OA_BIT1, OA_NONE} }, { "%event", of_EVENT, 1, {OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%flag_get/vec4", of_FLAG_GET_VEC4, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%flag_inv", of_FLAG_INV, 1, {OA_BIT1, OA_NONE, OA_NONE} }, { "%flag_mov", of_FLAG_MOV, 2, {OA_BIT1, OA_BIT2, OA_NONE} }, { "%flag_or", of_FLAG_OR, 2, {OA_BIT1, OA_BIT2, OA_NONE} }, { "%flag_set/imm", of_FLAG_SET_IMM, 2, {OA_NUMBER, OA_BIT1, OA_NONE} }, { "%flag_set/vec4", of_FLAG_SET_VEC4, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%force/link", of_FORCE_LINK,2,{OA_FUNC_PTR, OA_FUNC_PTR2, OA_NONE} }, { "%force/vec4", of_FORCE_VEC4, 1,{OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%force/vec4/off",of_FORCE_VEC4_OFF,2,{OA_FUNC_PTR, OA_BIT1, OA_NONE} }, { "%force/wr", of_FORCE_WR, 1,{OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%fork", of_FORK, 2, {OA_CODE_PTR2,OA_VPI_PTR, OA_NONE} }, { "%free", of_FREE, 1, {OA_VPI_PTR, OA_NONE, OA_NONE} }, { "%inv", of_INV, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%ix/add", of_IX_ADD, 3, {OA_NUMBER, OA_BIT1, OA_BIT2} }, { "%ix/getv",of_IX_GETV,2, {OA_BIT1, OA_FUNC_PTR, OA_NONE} }, { "%ix/getv/s",of_IX_GETV_S,2, {OA_BIT1, OA_FUNC_PTR, OA_NONE} }, { "%ix/load",of_IX_LOAD,3, {OA_NUMBER, OA_BIT1, OA_BIT2} }, { "%ix/mov", of_IX_MOV, 2, {OA_BIT1, OA_BIT2, OA_NONE} }, { "%ix/mul", of_IX_MUL, 3, {OA_NUMBER, OA_BIT1, OA_BIT2} }, { "%ix/sub", of_IX_SUB, 3, {OA_NUMBER, OA_BIT1, OA_BIT2} }, { "%ix/vec4", of_IX_VEC4, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%ix/vec4/s",of_IX_VEC4_S,1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%jmp", of_JMP, 1, {OA_CODE_PTR, OA_NONE, OA_NONE} }, { "%jmp/0", of_JMP0, 2, {OA_CODE_PTR, OA_BIT1, OA_NONE} }, { "%jmp/0xz",of_JMP0XZ, 2, {OA_CODE_PTR, OA_BIT1, OA_NONE} }, { "%jmp/1", of_JMP1, 2, {OA_CODE_PTR, OA_BIT1, OA_NONE} }, { "%jmp/1xz",of_JMP1XZ, 2, {OA_CODE_PTR, OA_BIT1, OA_NONE} }, { "%join", of_JOIN, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%join/detach",of_JOIN_DETACH,1,{OA_NUMBER,OA_NONE, OA_NONE} }, { "%load/ar",of_LOAD_AR,2, {OA_ARR_PTR, OA_BIT1, OA_NONE} }, { "%load/dar/r", of_LOAD_DAR_R, 1, {OA_FUNC_PTR, OA_NONE, OA_NONE}}, { "%load/dar/str",of_LOAD_DAR_STR, 1, {OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%load/dar/vec4",of_LOAD_DAR_VEC4,1, {OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%load/obj", of_LOAD_OBJ, 1,{OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%load/obja", of_LOAD_OBJA, 2,{OA_ARR_PTR, OA_BIT1, OA_NONE} }, { "%load/real", of_LOAD_REAL, 1,{OA_VPI_PTR, OA_NONE, OA_NONE} }, { "%load/str", of_LOAD_STR, 1,{OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%load/stra", of_LOAD_STRA, 2,{OA_ARR_PTR, OA_BIT1, OA_NONE} }, { "%load/vec4", of_LOAD_VEC4, 1,{OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%load/vec4a", of_LOAD_VEC4A,2,{OA_ARR_PTR, OA_BIT1, OA_NONE} }, { "%max/wr", of_MAX_WR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%min/wr", of_MIN_WR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%mod", of_MOD, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%mod/s", of_MOD_S, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%mod/wr", of_MOD_WR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%mov/wu", of_MOV_WU, 2, {OA_BIT1, OA_BIT2, OA_NONE} }, { "%mul", of_MUL, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%mul/wr", of_MUL_WR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%muli", of_MULI, 3, {OA_BIT1, OA_BIT2, OA_NUMBER} }, { "%nand", of_NAND, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%nand/r", of_NANDR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%new/cobj", of_NEW_COBJ, 1, {OA_VPI_PTR,OA_NONE, OA_NONE} }, { "%new/darray",of_NEW_DARRAY,2, {OA_BIT1, OA_STRING,OA_NONE} }, { "%noop", of_NOOP, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%nor", of_NOR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%nor/r", of_NORR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%null", of_NULL, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%or", of_OR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%or/r", of_ORR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%pad/s", of_PAD_S, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%pad/u", of_PAD_U, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%part/s", of_PART_S, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%part/u", of_PART_U, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%parti/s",of_PARTI_S,3, {OA_NUMBER, OA_BIT1, OA_BIT2} }, { "%parti/u",of_PARTI_U,3, {OA_NUMBER, OA_BIT1, OA_BIT2} }, { "%pop/obj", of_POP_OBJ, 2, {OA_BIT1, OA_BIT2, OA_NONE} }, { "%pop/real",of_POP_REAL,1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%pop/str", of_POP_STR, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%pop/vec4",of_POP_VEC4,1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%pow", of_POW, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%pow/s", of_POW_S, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%pow/wr", of_POW_WR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%prop/obj",of_PROP_OBJ,2, {OA_NUMBER, OA_BIT1, OA_NONE} }, { "%prop/r", of_PROP_R, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%prop/str",of_PROP_STR,1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%prop/v", of_PROP_V, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%pushi/real",of_PUSHI_REAL,2,{OA_BIT1, OA_BIT2, OA_NONE} }, { "%pushi/str", of_PUSHI_STR, 1,{OA_STRING, OA_NONE, OA_NONE} }, { "%pushi/vec4",of_PUSHI_VEC4,3,{OA_BIT1, OA_BIT2, OA_NUMBER} }, { "%pushv/str", of_PUSHV_STR, 0,{OA_NONE, OA_NONE, OA_NONE} }, { "%putc/str/vec4",of_PUTC_STR_VEC4,2,{OA_FUNC_PTR,OA_BIT1,OA_NONE} }, { "%qpop/b/str",of_QPOP_B_STR,1,{OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%qpop/b/v", of_QPOP_B_V, 1,{OA_FUNC_PTR,OA_NONE, OA_BIT2} }, { "%qpop/f/str",of_QPOP_F_STR,1,{OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%qpop/f/v", of_QPOP_F_V, 1,{OA_FUNC_PTR,OA_NONE, OA_BIT2} }, { "%release/net",of_RELEASE_NET,3,{OA_FUNC_PTR,OA_BIT1,OA_BIT2} }, { "%release/reg",of_RELEASE_REG,3,{OA_FUNC_PTR,OA_BIT1,OA_BIT2} }, { "%release/wr", of_RELEASE_WR, 2,{OA_FUNC_PTR,OA_BIT1,OA_NONE} }, { "%replicate", of_REPLICATE, 1,{OA_NUMBER, OA_NONE,OA_NONE} }, { "%ret/real", of_RET_REAL, 1,{OA_NUMBER, OA_NONE,OA_NONE} }, { "%ret/vec4", of_RET_VEC4, 3,{OA_NUMBER, OA_BIT1,OA_BIT2} }, { "%retload/real",of_RETLOAD_REAL,1,{OA_NUMBER, OA_NONE,OA_NONE} }, { "%retload/vec4",of_RETLOAD_VEC4,1,{OA_NUMBER, OA_NONE,OA_NONE} }, { "%scopy", of_SCOPY, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%set/dar/obj/real",of_SET_DAR_OBJ_REAL,1,{OA_NUMBER,OA_NONE,OA_NONE} }, { "%set/dar/obj/str", of_SET_DAR_OBJ_STR, 1,{OA_NUMBER,OA_NONE,OA_NONE} }, { "%set/dar/obj/vec4",of_SET_DAR_OBJ_VEC4,1,{OA_NUMBER,OA_NONE,OA_NONE} }, { "%shiftl", of_SHIFTL, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%shiftr", of_SHIFTR, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%shiftr/s", of_SHIFTR_S, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%split/vec4", of_SPLIT_VEC4, 1,{OA_NUMBER, OA_NONE, OA_NONE} }, { "%store/dar/r", of_STORE_DAR_R, 1,{OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%store/dar/str", of_STORE_DAR_STR, 1,{OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%store/dar/vec4",of_STORE_DAR_VEC4,1,{OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%store/obj", of_STORE_OBJ, 1, {OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%store/obja", of_STORE_OBJA, 2, {OA_ARR_PTR, OA_BIT1, OA_NONE} }, { "%store/prop/obj",of_STORE_PROP_OBJ,2, {OA_NUMBER, OA_BIT1, OA_NONE} }, { "%store/prop/r", of_STORE_PROP_R, 1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%store/prop/str",of_STORE_PROP_STR,1, {OA_NUMBER, OA_NONE, OA_NONE} }, { "%store/prop/v", of_STORE_PROP_V, 2, {OA_NUMBER, OA_BIT1, OA_NONE} }, { "%store/qb/r", of_STORE_QB_R, 1, {OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%store/qb/str", of_STORE_QB_STR, 1, {OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%store/qb/v", of_STORE_QB_V, 2, {OA_FUNC_PTR, OA_BIT1, OA_NONE} }, { "%store/qf/r", of_STORE_QF_R, 1, {OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%store/qf/str", of_STORE_QF_STR, 1, {OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%store/qf/v", of_STORE_QF_V, 2, {OA_FUNC_PTR, OA_BIT1, OA_NONE} }, { "%store/real", of_STORE_REAL, 1, {OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%store/reala", of_STORE_REALA, 2, {OA_ARR_PTR, OA_BIT1, OA_NONE} }, { "%store/str", of_STORE_STR, 1, {OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%store/stra", of_STORE_STRA, 2, {OA_ARR_PTR, OA_BIT1, OA_NONE} }, { "%store/vec4", of_STORE_VEC4, 3, {OA_FUNC_PTR,OA_BIT1, OA_BIT2} }, { "%store/vec4a", of_STORE_VEC4A, 3, {OA_ARR_PTR, OA_BIT1, OA_BIT2} }, { "%sub", of_SUB, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%sub/wr", of_SUB_WR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%subi", of_SUBI, 3, {OA_BIT1, OA_BIT2, OA_NUMBER} }, { "%substr", of_SUBSTR, 2,{OA_BIT1, OA_BIT2, OA_NONE} }, { "%substr/vec4",of_SUBSTR_VEC4,2,{OA_BIT1, OA_BIT2, OA_NONE} }, { "%test_nul", of_TEST_NUL, 1,{OA_FUNC_PTR,OA_NONE, OA_NONE} }, { "%test_nul/a", of_TEST_NUL_A, 2,{OA_ARR_PTR, OA_BIT1, OA_NONE} }, { "%test_nul/obj", of_TEST_NUL_OBJ, 0,{OA_NONE, OA_NONE, OA_NONE} }, { "%test_nul/prop",of_TEST_NUL_PROP,2,{OA_NUMBER, OA_BIT1, OA_NONE} }, { "%wait", of_WAIT, 1, {OA_FUNC_PTR, OA_NONE, OA_NONE} }, { "%wait/fork",of_WAIT_FORK,0,{OA_NONE, OA_NONE, OA_NONE} }, { "%xnor", of_XNOR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%xnor/r", of_XNORR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%xor", of_XOR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { "%xor/r", of_XORR, 0, {OA_NONE, OA_NONE, OA_NONE} }, { 0, of_NOOP, 0, {OA_NONE, OA_NONE, OA_NONE} } }; static const unsigned opcode_count = sizeof(opcode_table)/sizeof(*opcode_table) - 1; static int opcode_compare(const void*k, const void*r) { const char*kp = (const char*)k; const struct opcode_table_s*rp = (const struct opcode_table_s*)r; return strcmp(kp, rp->mnemonic); } /* * Keep a symbol table of addresses within code space. Labels on * executable opcodes are mapped to their address here. */ static symbol_table_t sym_codespace = 0; /* * Keep a symbol table of functors mentioned in the source. This table * is used to resolve references as they come. */ static symbol_table_t sym_functors = 0; /* * VPI objects are indexed during compile time so that they can be * linked together as they are created. This symbol table matches * labels to vpiHandles. */ static symbol_table_t sym_vpi = 0; /* * If a functor parameter makes a forward reference to a functor, then * I need to save that reference and resolve it after the functors are * created. Use this structure to keep the unresolved references in an * unsorted singly linked list. * * The postpone_functor_input arranges for a functor input to be * resolved and connected at cleanup. This is used if the symbol is * defined after its use in a functor. The ptr parameter is the * complete vvp_input_t for the input port. */ /* * Add a functor to the symbol table */ void define_functor_symbol(const char*label, vvp_net_t*net) { symbol_value_t val; val.net = net; sym_set_value(sym_functors, label, val); } static vvp_net_t*lookup_functor_symbol(const char*label) { assert(sym_functors); symbol_value_t val = sym_get_value(sym_functors, label); return val.net; } vpiHandle vvp_lookup_handle(const char*label) { symbol_value_t val = sym_get_value(sym_vpi, label); if (val.ptr) return (vpiHandle) val.ptr; return 0; } vvp_net_t* vvp_net_lookup(const char*label) { /* First, look to see if the symbol is a vpi object of some sort. If it is, then get the vvp_ipoint_t pointer out of the vpiHandle. */ symbol_value_t val = sym_get_value(sym_vpi, label); if (val.ptr) { vpiHandle vpi = (vpiHandle) val.ptr; switch (vpi->get_type_code()) { case vpiNet: case vpiReg: case vpiBitVar: case vpiByteVar: case vpiShortIntVar: case vpiIntVar: case vpiLongIntVar: case vpiIntegerVar: { __vpiSignal*sig = dynamic_cast<__vpiSignal*>(vpi); return sig->node; } case vpiRealVar: { __vpiRealVar*sig = dynamic_cast<__vpiRealVar*>(vpi); return sig->net; } case vpiStringVar: case vpiArrayVar: case vpiClassVar: { __vpiBaseVar*sig = dynamic_cast<__vpiBaseVar*>(vpi); return sig->get_net(); } case vpiNamedEvent: { __vpiNamedEvent*tmp = dynamic_cast<__vpiNamedEvent*>(vpi); return tmp->funct; } default: fprintf(stderr, "Unsupported type %d.\n", vpi->get_type_code()); assert(0); } } /* Failing that, look for a general functor. */ vvp_net_t*tmp = lookup_functor_symbol(label); return tmp; } /* * The resolv_list_s is the base class for a symbol resolve action, and * the resolv_list is an unordered list of these resolve actions. Some * function creates an instance of a resolv_list_s object that * contains the data pertinent to that resolution request, and * executes it with the resolv_submit function. If the operation can * complete, then the resolv_submit deletes the object. Otherwise, it * pushes it onto the resolv_list for later processing. * * Derived classes implement the resolve function to perform the * actual binding or resolution that the instance requires. If the * function succeeds, the resolve method returns true and the object * can be deleted any time. * * The mes parameter of the resolve method tells the resolver that * this call is its last chance. If it cannot complete the operation, * it must print an error message and return false. */ static resolv_list_s*resolv_list = 0; resolv_list_s::~resolv_list_s() { free(label_); } void resolv_submit(resolv_list_s*cur) { if (cur->resolve()) { delete cur; return; } cur->next = resolv_list; resolv_list = cur; } /* * Look up vvp_nets in the symbol table. The "source" is the label for * the net that I want to feed, and net->port[port] is the vvp_net * input that I want that node to feed into. When the name is found, * put net->port[port] into the fan-out list for that node. */ struct vvp_net_resolv_list_s: public resolv_list_s { explicit vvp_net_resolv_list_s(char*l) : resolv_list_s(l) { } // port to be driven by the located node. vvp_net_ptr_t port; virtual bool resolve(bool mes); }; bool vvp_net_resolv_list_s::resolve(bool mes) { vvp_net_t*tmp = vvp_net_lookup(label()); if (tmp) { // Link the input port to the located output. tmp->link(port); return true; } if (mes) fprintf(stderr, "unresolved vvp_net reference: %s\n", label()); return false; } inline static void postpone_functor_input(vvp_net_ptr_t port, char*lab) { struct vvp_net_resolv_list_s*res = new struct vvp_net_resolv_list_s(lab); res->port = port; resolv_submit(res); } /* * Generic functor reference lookup. */ struct functor_gen_resolv_list_s: public resolv_list_s { explicit functor_gen_resolv_list_s(char*txt) : resolv_list_s(txt) { ref = 0; } vvp_net_t**ref; virtual bool resolve(bool mes); }; bool functor_gen_resolv_list_s::resolve(bool mes) { vvp_net_t*tmp = vvp_net_lookup(label()); if (tmp) { *ref = tmp; return true; } if (mes) fprintf(stderr, "unresolved functor reference: %s\n", label()); return false; } void functor_ref_lookup(vvp_net_t**ref, char*lab) { struct functor_gen_resolv_list_s*res = new struct functor_gen_resolv_list_s(lab); res->ref = ref; resolv_submit(res); } /* * vpiHandle lookup */ struct vpi_handle_resolv_list_s: public resolv_list_s { explicit vpi_handle_resolv_list_s(char*lab) : resolv_list_s(lab) { handle = NULL; } virtual bool resolve(bool mes); vpiHandle *handle; }; bool vpi_handle_resolv_list_s::resolve(bool mes) { symbol_value_t val = sym_get_value(sym_vpi, label()); if (!val.ptr) { // check for thread access symbols unsigned base, wid; size_t n = 0; char ss[32]; if (2 == sscanf(label(), "W<%u,%[r]>%zn", &base, ss, &n) && n == strlen(label())) { val.ptr = vpip_make_vthr_word(base, ss); sym_set_value(sym_vpi, label(), val); } else if (1 == sscanf(label(), "S<%u,str>%zn", &base, &n) && n == strlen(label())) { val.ptr = vpip_make_vthr_str_stack(base); sym_set_value(sym_vpi, label(), val); } else if (3 == sscanf(label(), "S<%u,vec4,%[su]%u>%zn", &base, ss, &wid, &n) && n == strlen(label())) { bool signed_flag = false; for (char*fp = ss ; *fp ; fp += 1) switch (*fp) { case 's': signed_flag = true; break; case 'u': signed_flag = false; break; default: break; } val.ptr = vpip_make_vthr_vec4_stack(base, signed_flag, wid); sym_set_value(sym_vpi, label(), val); } } if (!val.ptr) { // check for memory word M<mem,base,wid> } if (val.ptr) { *handle = (vpiHandle) val.ptr; return true; } if (mes) fprintf(stderr, "unresolved vpi name lookup: %s\n", label()); return false; } void compile_vpi_lookup(vpiHandle *handle, char*label) { if (strcmp(label, "$time") == 0) { *handle = vpip_sim_time(vpip_peek_current_scope(), false); free(label); return; } if (strcmp(label, "$stime") == 0) { *handle = vpip_sim_time(vpip_peek_current_scope(), true); free(label); return; } if (strcmp(label, "$realtime") == 0) { *handle = vpip_sim_realtime(vpip_peek_current_scope()); free(label); return; } if (strcmp(label, "$simtime") == 0) { *handle = vpip_sim_time(0, false); free(label); return; } struct vpi_handle_resolv_list_s*res = new struct vpi_handle_resolv_list_s(label); res->handle = handle; resolv_submit(res); } /* * Code Label lookup */ struct code_label_resolv_list_s: public resolv_list_s { explicit code_label_resolv_list_s(char*lab, bool cptr2) : resolv_list_s(lab) { code = NULL; cptr2_flag = cptr2; } struct vvp_code_s *code; bool cptr2_flag; virtual bool resolve(bool mes); }; bool code_label_resolv_list_s::resolve(bool mes) { symbol_value_t val = sym_get_value(sym_codespace, label()); if (val.num) { if (cptr2_flag) code->cptr2 = reinterpret_cast<vvp_code_t>(val.ptr); else code->cptr = reinterpret_cast<vvp_code_t>(val.ptr); return true; } if (mes) fprintf(stderr, "unresolved code label: %s\n", label()); return false; } void code_label_lookup(struct vvp_code_s *code, char *label, bool cptr2) { struct code_label_resolv_list_s *res = new struct code_label_resolv_list_s(label, cptr2); res->code = code; resolv_submit(res); } struct code_array_resolv_list_s: public resolv_list_s { explicit code_array_resolv_list_s(char*lab) : resolv_list_s(lab) { code = NULL; } struct vvp_code_s *code; virtual bool resolve(bool mes); }; bool code_array_resolv_list_s::resolve(bool mes) { code->array = array_find(label()); if (code->array != 0) { return true; } if (mes) fprintf(stderr, "Array unresolved: %s\n", label()); return false; } static void compile_array_lookup(struct vvp_code_s*code, char*label) { struct code_array_resolv_list_s *res = new struct code_array_resolv_list_s(label); res->code = code; resolv_submit(res); } static std::list<struct __vpiSysTaskCall*> scheduled_compiletf; void compile_compiletf(struct __vpiSysTaskCall*obj) { if (obj->defn->info.compiletf == 0) return; scheduled_compiletf.push_back(obj); } /* * When parsing is otherwise complete, this function is called to do * the final stuff. Clean up deferred linking here. */ void compile_cleanup(void) { int lnerrs = -1; int nerrs = 0; int last; if (verbose_flag) { fprintf(stderr, " ... Linking\n"); fflush(stderr); } do { resolv_list_s *res = resolv_list; resolv_list = 0x0; last = nerrs == lnerrs; lnerrs = nerrs; nerrs = 0; while (res) { resolv_list_s *cur = res; res = res->next; if (cur->resolve(last)) delete cur; else { nerrs++; cur->next = resolv_list; resolv_list = cur; } } if (nerrs && last) fprintf(stderr, "compile_cleanup: %d unresolved items\n", nerrs); } while (nerrs && !last); compile_errors += nerrs; if (verbose_flag) { fprintf(stderr, " ... Removing symbol tables\n"); fflush(stderr); } /* After compile is complete, the vpi symbol table is no longer needed. VPI objects are located by following scopes. */ delete_symbol_table(sym_vpi); sym_vpi = 0; /* Don't need the code labels. The instructions have numeric pointers in them, the symbol table is no longer needed. */ delete_symbol_table(sym_codespace); sym_codespace = 0; delete_symbol_table(sym_functors); sym_functors = 0; delete_udp_symbols(); compile_island_cleanup(); compile_array_cleanup(); if (verbose_flag) { fprintf(stderr, " ... Compiletf functions\n"); fflush(stderr); } assert(vpi_mode_flag == VPI_MODE_NONE); vpi_mode_flag = VPI_MODE_COMPILETF; while (! scheduled_compiletf.empty()) { struct __vpiSysTaskCall*obj = scheduled_compiletf.front(); scheduled_compiletf.pop_front(); vpip_cur_task = obj; obj->defn->info.compiletf (obj->defn->info.user_data); vpip_cur_task = 0; } vpi_mode_flag = VPI_MODE_NONE; } void compile_vpi_symbol(const char*label, vpiHandle obj) { symbol_value_t val; val.ptr = obj; sym_set_value(sym_vpi, label, val); } /* * Initialize the compiler by allocation empty symbol tables and * initializing the various address spaces. */ void compile_init(void) { sym_vpi = new_symbol_table(); sym_functors = new_symbol_table(); sym_codespace = new_symbol_table(); codespace_init(); } void compile_load_vpi_module(char*name) { vpip_load_module(name); delete[] name; } void compile_vpi_time_precision(long pre) { vpip_set_time_precision(pre); } /* * Convert a Cr string value to double. * * The format is broken into mantissa and exponent. * The exponent in turn includes a sign bit. * * The mantissa is a 64bit integer value (encoded in hex). * * The exponent included the sign bit (0x4000) and the binary * exponent offset by 0x1000. The actual exponent is the * encoded exponent - 0x1000. * * The real value is sign * (mant ** exp). */ bool crstring_test(const char*str) { if (strncmp(str, "Cr<", 3) != 0) return false; const char*tp = strchr(str, '>'); if (tp == 0) return false; if (tp[1] != 0) return false; if ((strspn(str+3, "0123456789abcdefmg")+3) != (size_t)(tp - str)) return false; return true; } double crstring_to_double(const char*label) { const char*cp = label+3; assert(*cp == 'm'); cp += 1; char*ep; uint64_t mant = strtoull(cp, &ep, 16); cp = ep; assert(*cp == 'g'); cp += 1; int exp = strtoul(cp, 0, 16); double tmp; if (mant == 0 && exp == 0x3fff) { tmp = INFINITY; } else if (mant == 0 && exp == 0x7fff) { tmp = -INFINITY; } else if (exp == 0x3fff) { tmp = nan(""); } else { double sign = (exp & 0x4000)? -1.0 : 1.0; exp &= 0x1fff; tmp = sign * ldexp((double)mant, exp - 0x1000); } return tmp; } /* * Run through the arguments looking for the nodes that are * connected to my input ports. For each source functor that I * find, connect the output of that functor to the indexed * input by inserting myself (complete with the port number in * the vvp_ipoint_t) into the list that the source heads. * * If the source functor is not declared yet, then don't do * the link yet. Save the reference to be resolved later. * * If the source is a constant value, then set the ival of the functor * and skip the symbol lookup. */ void input_connect(vvp_net_t*fdx, unsigned port, char*label) { vvp_net_ptr_t ifdx = vvp_net_ptr_t(fdx, port); /* Is this a vvp_vector4_t constant value? */ if (c4string_test(label)) { vvp_vector4_t tmp = c4string_to_vector4(label); // Inputs that are constants are schedule to execute as // soon at the simulation starts. In Verilog, constants // start propagating when the simulation starts, just // like any other signal value. But letting the // scheduler distribute the constant value has the // additional advantage that the constant is not // propagated until the network is fully linked. schedule_set_vector(ifdx, tmp); free(label); return; } /* Is this a vvp_vector8_t constant value? */ if (c8string_test(label)) { vvp_vector8_t tmp = c8string_to_vector8(label); schedule_set_vector(ifdx, tmp); free(label); return; } /* Handle the Cr<> constant driver, which is a real-value driver. */ if (crstring_test(label)) { double tmp = crstring_to_double(label); schedule_set_vector(ifdx, tmp); free(label); return; } /* Handle the general case that this is a label for a node in the vvp net. This arranges for the label to be preserved in a linker list, and linked when the symbol table is complete. */ postpone_functor_input(ifdx, label); } void inputs_connect(vvp_net_t*fdx, unsigned argc, struct symb_s*argv) { if (argc > 4) { std::cerr << "XXXX argv[0] = " << argv[0].text << std::endl; } assert(argc <= 4); for (unsigned idx = 0; idx < argc; idx += 1) { input_connect(fdx, idx, argv[idx].text); } } void wide_inputs_connect(vvp_wide_fun_core*core, unsigned argc, struct symb_s*argv) { /* Create input functors to receive values from the network. These functors pass the data to the core. */ unsigned input_functors = (argc+3) / 4; for (unsigned idx = 0 ; idx < input_functors ; idx += 1) { unsigned base = idx*4; unsigned trans = 4; if (base+trans > argc) trans = argc - base; vvp_wide_fun_t*cur = new vvp_wide_fun_t(core, base); vvp_net_t*ptr = new vvp_net_t; ptr->fun = cur; inputs_connect(ptr, trans, argv+base); } } template <class T_> void make_arith(T_ *arith, char*label, unsigned argc, struct symb_s*argv) { vvp_net_t* ptr = new vvp_net_t; ptr->fun = arith; define_functor_symbol(label, ptr); free(label); assert(argc == 2); inputs_connect(ptr, argc, argv); free(argv); } void compile_arith_cast_int(char*label, long width, unsigned argc, struct symb_s*argv) { vvp_arith_cast_int*arith = new vvp_arith_cast_int((unsigned) width); vvp_net_t* ptr = new vvp_net_t; ptr->fun = arith; define_functor_symbol(label, ptr); free(label); assert(argc == 1); inputs_connect(ptr, argc, argv); free(argv); } void compile_arith_cast_vec2(char*label, long width, unsigned argc, struct symb_s*argv) { vvp_arith_cast_vec2*arith = new vvp_arith_cast_vec2((unsigned) width); vvp_net_t* ptr = new vvp_net_t; ptr->fun = arith; define_functor_symbol(label, ptr); free(label); assert(argc == 1); inputs_connect(ptr, argc, argv); free(argv); } void compile_arith_cast_real(char*label, bool signed_flag, unsigned argc, struct symb_s*argv) { vvp_arith_cast_real*arith = new vvp_arith_cast_real(signed_flag); vvp_net_t* ptr = new vvp_net_t; ptr->fun = arith; define_functor_symbol(label, ptr); free(label); assert(argc == 1); inputs_connect(ptr, argc, argv); free(argv); } void compile_arith_abs(char*label, unsigned argc, struct symb_s*argv) { vvp_arith_abs*arith = new vvp_arith_abs; vvp_net_t* ptr = new vvp_net_t; ptr->fun = arith; define_functor_symbol(label, ptr); free(label); assert(argc == 1); inputs_connect(ptr, argc, argv); free(argv); } void compile_arith_div(char*label, long wid, bool signed_flag, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { const char *suffix = ""; if (signed_flag) suffix = ".s"; fprintf(stderr, "%s; .arith/div%s has wrong number of " "symbols\n", label, suffix); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_arith_div(wid, signed_flag); make_arith(arith, label, argc, argv); } void compile_arith_div_r(char*label, unsigned argc, struct symb_s*argv) { if (argc != 2) { fprintf(stderr, "%s; .arith/divr has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_real_ *arith = new vvp_arith_div_real; make_arith(arith, label, argc, argv); } void compile_arith_mod(char*label, long wid, bool signed_flag, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .arith/mod has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_arith_mod(wid, signed_flag); make_arith(arith, label, argc, argv); } void compile_arith_mod_r(char*label, unsigned argc, struct symb_s*argv) { if (argc != 2) { fprintf(stderr, "%s .arith/mod.r has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_real_ *arith = new vvp_arith_mod_real; make_arith(arith, label, argc, argv); } void compile_arith_mult(char*label, long wid, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .arith/mult has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_arith_mult(wid); make_arith(arith, label, argc, argv); } void compile_arith_mult_r(char*label, unsigned argc, struct symb_s*argv) { if (argc != 2) { fprintf(stderr, "%s .arith/mult.r has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_real_ *arith = new vvp_arith_mult_real; make_arith(arith, label, argc, argv); } void compile_arith_pow(char*label, long wid, bool signed_flag, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { const char *suffix = ""; if (signed_flag) suffix = ".s"; fprintf(stderr, "%s .arith/pow%s has wrong number of " "symbols\n", label, suffix); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_arith_pow(wid, signed_flag); make_arith(arith, label, argc, argv); } void compile_arith_pow_r(char*label, unsigned argc, struct symb_s*argv) { if (argc != 2) { fprintf(stderr, "%s .arith/pow.r has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_real_ *arith = new vvp_arith_pow_real; make_arith(arith, label, argc, argv); } void compile_arith_sub(char*label, long wid, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .arith/sub has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_arith_sub(wid); make_arith(arith, label, argc, argv); } void compile_arith_sub_r(char*label, unsigned argc, struct symb_s*argv) { if (argc != 2) { fprintf(stderr, "%s; .arith/sub.r has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_real_ *arith = new vvp_arith_sub_real; make_arith(arith, label, argc, argv); } void compile_arith_sum(char*label, long wid, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .arith/sum has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_arith_sum(wid); make_arith(arith, label, argc, argv); } void compile_arith_sum_r(char*label, unsigned argc, struct symb_s*argv) { if (argc != 2) { fprintf(stderr, "%s .arith/sum.r has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_real_ *arith = new vvp_arith_sum_real; make_arith(arith, label, argc, argv); } void compile_cmp_eeq(char*label, long wid, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .cmp/eeq has wrong number of symbols\n",label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_cmp_eeq(wid); make_arith(arith, label, argc, argv); } void compile_cmp_nee(char*label, long wid, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .cmp/eeq has wrong number of symbols\n",label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_cmp_nee(wid); make_arith(arith, label, argc, argv); } void compile_cmp_eq(char*label, long wid, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .cmp/eq has wrong number of symbols\n",label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_cmp_eq(wid); make_arith(arith, label, argc, argv); } void compile_cmp_eqx(char*label, long wid, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .cmp/eqx has wrong number of symbols\n",label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_cmp_eqx(wid); make_arith(arith, label, argc, argv); } void compile_cmp_eqz(char*label, long wid, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .cmp/eqz has wrong number of symbols\n",label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_cmp_eqz(wid); make_arith(arith, label, argc, argv); } void compile_cmp_eq_r(char*label, unsigned argc, struct symb_s*argv) { if (argc != 2) { fprintf(stderr, "%s .cmp/eq.r has wrong number of symbols\n",label); compile_errors += 1; return; } vvp_arith_real_ *arith = new vvp_cmp_eq_real; make_arith(arith, label, argc, argv); } void compile_cmp_ne(char*label, long wid, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .cmp/ne has wrong number of symbols\n",label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_cmp_ne(wid); make_arith(arith, label, argc, argv); } void compile_cmp_ne_r(char*label, unsigned argc, struct symb_s*argv) { if (argc != 2) { fprintf(stderr, "%s .cmp/ne.r has wrong number of symbols\n",label); compile_errors += 1; return; } vvp_arith_real_ *arith = new vvp_cmp_ne_real; make_arith(arith, label, argc, argv); } void compile_cmp_ge(char*label, long wid, bool signed_flag, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .cmp/ge has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_cmp_ge(wid, signed_flag); make_arith(arith, label, argc, argv); } void compile_cmp_ge_r(char*label, unsigned argc, struct symb_s*argv) { if (argc != 2) { fprintf(stderr, "%s .cmp/ge.r has wrong number of symbols\n",label); compile_errors += 1; return; } vvp_arith_real_ *arith = new vvp_cmp_ge_real; make_arith(arith, label, argc, argv); } void compile_cmp_gt(char*label, long wid, bool signed_flag, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); if (argc != 2) { fprintf(stderr, "%s .cmp/gt has wrong number of symbols\n", label); compile_errors += 1; return; } vvp_arith_ *arith = new vvp_cmp_gt(wid, signed_flag); make_arith(arith, label, argc, argv); } void compile_cmp_gt_r(char*label, unsigned argc, struct symb_s*argv) { if (argc != 2) { fprintf(stderr, "%s .cmp/gt.r has wrong number of symbols\n",label); compile_errors += 1; return; } vvp_arith_real_ *arith = new vvp_cmp_gt_real; make_arith(arith, label, argc, argv); } void compile_delay(char*label, unsigned width, vvp_delay_t*delay, struct symb_s arg) { vvp_net_t*net = new vvp_net_t; vvp_fun_delay*obj = new vvp_fun_delay(net, width, *delay); net->fun = obj; delete delay; input_connect(net, 0, arg.text); define_functor_symbol(label, net); free(label); } void compile_delay(char*label, unsigned width, unsigned argc, struct symb_s*argv, bool ignore_decay) { vvp_delay_t stub (0, 0, 0); if (ignore_decay) stub.set_ignore_decay(); vvp_net_t*net = new vvp_net_t; vvp_fun_delay*obj = new vvp_fun_delay(net, width, stub); net->fun = obj; inputs_connect(net, argc, argv); free(argv); define_functor_symbol(label, net); free(label); } /* * Extend nodes. */ void compile_extend_signed(char*label, long wid, struct symb_s arg) { assert(wid >= 0); vvp_fun_extend_signed*fun = new vvp_fun_extend_signed(wid); vvp_net_t*ptr = new vvp_net_t; ptr->fun = fun; define_functor_symbol(label, ptr); free(label); input_connect(ptr, 0, arg.text); } struct __vpiModPath* compile_modpath(char*label, unsigned width, struct symb_s drv, struct symb_s dest) { vvp_net_t*net = new vvp_net_t; vvp_fun_modpath*obj = new vvp_fun_modpath(net, width); net->fun = obj; input_connect(net, 0, drv.text); define_functor_symbol(label, net); __vpiModPath*modpath = vpip_make_modpath(net); compile_vpi_lookup(&modpath->path_term_out.expr, dest.text); free(label); modpath->modpath = obj; return modpath; } static struct __vpiModPathSrc*make_modpath_src(struct __vpiModPath*path, char edge, struct symb_s src, struct numbv_s vals, bool ifnone) { vvp_fun_modpath*dst = path->modpath; vvp_time64_t use_delay[12]; assert(vals.cnt == 12); for (unsigned idx = 0 ; idx < vals.cnt ; idx += 1) { use_delay[idx] = vals.nvec[idx]; } numbv_clear(&vals); vvp_fun_modpath_src*obj = 0; int vpi_edge = vpiNoEdge; if (edge == 0) { obj = new vvp_fun_modpath_src(use_delay); } else { bool posedge, negedge; switch (edge) { case '+': vpi_edge = vpiPosedge; posedge = true; negedge = false; break; case '-': vpi_edge = vpiNegedge; posedge = false; negedge = true; break; #if 0 case '*': posedge = true; negedge = true; break; #endif default: posedge = false; negedge = false; fprintf(stderr, "Unknown edge identifier %c(%d).\n", edge, edge); assert(0); } obj = new vvp_fun_modpath_edge(use_delay, posedge, negedge); } vvp_net_t*net = new vvp_net_t; struct __vpiModPathSrc* srcobj = vpip_make_modpath_src(path, net) ; vpip_attach_to_current_scope(srcobj); net->fun = obj; /* Save the vpiEdge directory into the input path term. */ srcobj->path_term_in.edge = vpi_edge; input_connect(net, 0, src.text); dst->add_modpath_src(obj, ifnone); return srcobj; } void compile_modpath_src(struct __vpiModPath*dst, char edge, struct symb_s src, struct numbv_s vals, struct symb_s condit_src, struct symb_s path_term_in) { struct __vpiModPathSrc*obj = make_modpath_src(dst, edge, src, vals, false); input_connect(obj->net, 1, condit_src.text); compile_vpi_lookup(&obj->path_term_in.expr, path_term_in.text); } void compile_modpath_src(struct __vpiModPath*dst, char edge, struct symb_s src, struct numbv_s vals, int condit_src, struct symb_s path_term_in, bool ifnone) { assert(condit_src == 0); struct __vpiModPathSrc*obj = make_modpath_src(dst, edge, src, vals, ifnone); compile_vpi_lookup(&obj->path_term_in.expr, path_term_in.text); } /* * A .shift/l statement creates an array of functors for the * width. The 0 input is the data vector to be shifted and the 1 input * is the amount of the shift. An unconnected shift amount is set to 0. */ void compile_shiftl(char*label, long wid, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); vvp_arith_ *arith = new vvp_shiftl(wid); make_arith(arith, label, argc, argv); } void compile_shiftr(char*label, long wid, bool signed_flag, unsigned argc, struct symb_s*argv) { assert( wid > 0 ); vvp_arith_ *arith = new vvp_shiftr(wid, signed_flag); make_arith(arith, label, argc, argv); } void compile_resolver(char*label, char*type, unsigned argc, struct symb_s*argv) { vvp_net_t*net = new vvp_net_t; resolv_core*core = 0; if (strcmp(type,"tri") == 0) { core = new resolv_tri(argc, net, vvp_scalar_t(BIT4_Z, 0,0)); } else if (strcmp(type,"tri0") == 0) { core = new resolv_tri(argc, net, vvp_scalar_t(BIT4_0, 5,5)); } else if (strcmp(type,"tri1") == 0) { core = new resolv_tri(argc, net, vvp_scalar_t(BIT4_1, 5,5)); } else if (strcmp(type,"triand") == 0) { core = new resolv_triand(argc, net); } else if (strcmp(type,"trior") == 0) { core = new resolv_trior(argc, net); } else { fprintf(stderr, "invalid resolver type: %s\n", type); compile_errors += 1; delete net; } if (core) { net->fun = core; define_functor_symbol(label, net); for (unsigned base = 0 ; base < argc ; base += 4) { unsigned nports = argc - base; if (nports > 4) nports = 4; if (base > 0) { net = new vvp_net_t; net->fun = new resolv_extend(core, base); } inputs_connect(net, nports, argv+base); } } free(type); free(label); free(argv); } void compile_udp_def(int sequ, char *label, char *name, unsigned nin, unsigned init, char **table) { if (sequ) { vvp_bit4_t init4; if (init == 0) init4 = BIT4_0; else if (init == 1) init4 = BIT4_1; else init4 = BIT4_X; vvp_udp_seq_s *u = new vvp_udp_seq_s(label, name, nin, init4); u->compile_table(table); } else { vvp_udp_comb_s *u = new vvp_udp_comb_s(label, name, nin); u->compile_table(table); } free(label); } char **compile_udp_table(char **table, char *row) { if (table) assert(strlen(*table)==strlen(row)); char **tt; for (tt = table; tt && *tt; tt++) { } int n = (tt-table) + 2; table = (char**)realloc(table, n*sizeof(char*)); table[n-2] = row; table[n-1] = 0x0; return table; } /* * The parser uses this function to compile and link an executable * opcode. I do this by looking up the opcode in the opcode_table. The * table gives the operand structure that is acceptable, so I can * process the operands here as well. */ void compile_code(char*label, char*mnem, comp_operands_t opa) { /* First, I can give the label a value that is the current codespace pointer. Don't need the text of the label after this is done. */ if (label) compile_codelabel(label); /* Lookup the opcode in the opcode table. */ struct opcode_table_s*op = (struct opcode_table_s*) bsearch(mnem, opcode_table, opcode_count, sizeof(struct opcode_table_s), &opcode_compare); if (op == 0) { vvperror("Invalid opcode"); compile_errors += 1; return; } assert(op); /* Build up the code from the information about the opcode and the information from the compiler. */ vvp_code_t code = codespace_allocate(); code->opcode = op->opcode; if (op->argc != (opa? opa->argc : 0)) { vvperror("operand count"); compile_errors += 1; return; } /* Pull the operands that the instruction expects from the list that the parser supplied. */ for (unsigned idx = 0 ; idx < op->argc ; idx += 1) { switch (op->argt[idx]) { case OA_NONE: break; case OA_ARR_PTR: if (opa->argv[idx].ltype != L_SYMB) { vvperror("operand format"); break; } compile_array_lookup(code, opa->argv[idx].symb.text); break; case OA_BIT1: if (opa->argv[idx].ltype != L_NUMB) { vvperror("operand format"); break; } code->bit_idx[0] = opa->argv[idx].numb; break; case OA_BIT2: if (opa->argv[idx].ltype != L_NUMB) { vvperror("operand format"); break; } code->bit_idx[1] = opa->argv[idx].numb; break; case OA_CODE_PTR: case OA_CODE_PTR2: if (opa->argv[idx].ltype != L_SYMB) { vvperror("operand format"); break; } assert(opa->argv[idx].symb.idx == 0); code_label_lookup(code, opa->argv[idx].symb.text, op->argt[idx]==OA_CODE_PTR2); break; case OA_FUNC_PTR: /* The operand is a functor. Resolve the label to a functor pointer, or postpone the resolution if it is not defined yet. */ if (opa->argv[idx].ltype != L_SYMB) { vvperror("operand format"); break; } functor_ref_lookup(&code->net, opa->argv[idx].symb.text); break; case OA_FUNC_PTR2: /* The operand is a functor. Resolve the label to a functor pointer, or postpone the resolution if it is not defined yet. */ if (opa->argv[idx].ltype != L_SYMB) { vvperror("operand format"); break; } functor_ref_lookup(&code->net2, opa->argv[idx].symb.text); break; case OA_NUMBER: if (opa->argv[idx].ltype != L_NUMB) { vvperror("operand format"); break; } code->number = opa->argv[idx].numb; break; case OA_VPI_PTR: /* The operand is a functor. Resolve the label to a functor pointer, or postpone the resolution if it is not defined yet. */ if (opa->argv[idx].ltype != L_SYMB) { vvperror("operand format"); break; } compile_vpi_lookup(&code->handle, opa->argv[idx].symb.text); break; case OA_STRING: if (opa->argv[idx].ltype != L_STRING) { vvperror("operand format"); break; } code->text = opa->argv[idx].text; break; } } free(opa); free(mnem); } void compile_codelabel(char*label) { symbol_value_t val; vvp_code_t ptr = codespace_next(); val.ptr = ptr; sym_set_value(sym_codespace, label, val); free(label); } void compile_file_line(char*label, long file_idx, long lineno, char*description) { if (label) compile_codelabel(label); /* Create an instruction in the code space. */ vvp_code_t code = codespace_allocate(); code->opcode = &of_FILE_LINE; /* Create a vpiHandle that contains the information. */ code->handle = vpip_build_file_line(description, file_idx, lineno); assert(code->handle); /* Done with the lexor-allocated name string. */ delete[] description; } void compile_vpi_call(char*label, char*name, bool func_as_task_err, bool func_as_task_warn, long file_idx, long lineno, unsigned argc, vpiHandle*argv, unsigned vec4_stack, unsigned real_stack, unsigned string_stack) { if (label) compile_codelabel(label); /* Create an instruction in the code space. */ vvp_code_t code = codespace_allocate(); code->opcode = &of_VPI_CALL; /* Create a vpiHandle that bundles the call information, and store that handle in the instruction. */ code->handle = vpip_build_vpi_call(name, 0, 0, 0, func_as_task_err, func_as_task_warn, argc, argv, vec4_stack, real_stack, string_stack, file_idx, lineno); if (code->handle == 0) compile_errors += 1; /* Done with the lexor-allocated name string. */ delete[] name; } void compile_vpi_func_call(char*label, char*name, int val_type, unsigned val_wid, long file_idx, long lineno, unsigned argc, vpiHandle*argv, unsigned vec4_stack, unsigned real_stack, unsigned string_stack) { if (label) compile_codelabel(label); /* Create an instruction in the code space. */ vvp_code_t code = codespace_allocate(); code->opcode = &of_VPI_CALL; /* Create a vpiHandle that bundles the call information, and store that handle in the instruction. */ code->handle = vpip_build_vpi_call(name, val_type, val_wid, 0, true, false, argc, argv, vec4_stack, real_stack, string_stack, file_idx, lineno); if (code->handle == 0) compile_errors += 1; /* Done with the lexor-allocated name string. */ delete[] name; } /* * When the parser finds a thread statement, I create a new thread * with the start address referenced by the program symbol passed to * me. */ void compile_thread(char*start_sym, char*flag) { bool push_flag = false; symbol_value_t tmp = sym_get_value(sym_codespace, start_sym); vvp_code_t pc = reinterpret_cast<vvp_code_t>(tmp.ptr); if (pc == 0) { vvperror("unresolved address"); return; } if (flag && (strcmp(flag,"$push") == 0)) push_flag = true; vthread_t thr = vthread_new(pc, vpip_peek_current_scope()); if (flag && (strcmp(flag,"$final") == 0)) schedule_final_vthread(thr); else schedule_vthread(thr, 0, push_flag); free(start_sym); free(flag); } void compile_param_logic(char*label, char*name, char*value, bool signed_flag, bool local_flag, long file_idx, long lineno) { vvp_vector4_t value4 = c4string_to_vector4(value); vpiHandle obj = vpip_make_binary_param(name, value4, signed_flag, local_flag, file_idx, lineno); compile_vpi_symbol(label, obj); vpip_attach_to_current_scope(obj); free(label); free(value); } void compile_param_string(char*label, char*name, char*value, bool local_flag, long file_idx, long lineno) { // name and value become owned by vpip_make_string_param vpiHandle obj = vpip_make_string_param(name, value, local_flag, file_idx, lineno); compile_vpi_symbol(label, obj); vpip_attach_to_current_scope(obj); free(label); } void compile_param_real(char*label, char*name, char*value, bool local_flag, long file_idx, long lineno) { double dvalue = crstring_to_double(value); vpiHandle obj = vpip_make_real_param(name, dvalue, local_flag, file_idx, lineno); compile_vpi_symbol(label, obj); vpip_attach_to_current_scope(obj); free(label); free(value); } void compile_island(char*label, char*type) { if (strcmp(type,"tran") == 0) compile_island_tran(label); else assert(0); free(type); }
lgpl-3.0
Fylhan/bnbox
src/Entity/EmailData.php
7178
<?php /** * Un contact représente un email envoyé par un contact * @author Fylhan * @copyright Fylhan * @license Fylhan */ class EmailData { /** * * @var string * @access protected */ protected $nom=NULL; /** * * @var string * @access protected */ protected $email; /** * * @var string * @access protected */ protected $objet=NULL; /** * * @var string * @access protected */ protected $message; /** * * @var boolean * @access protected */ protected $antibot = false; /** * True si l'email a été envoyé * @var boolean * @access protected */ protected $sent = false; /** * Date d'envoie de l'email * @var DateTime * @access protected */ protected $sentDate = NULL; protected $expediteur; protected $destinataires; protected $destinatairesCc; protected $destinatairesCci; // --- Constructor /** * @access public * @param array $params */ public function __construct($params = array()) { $this->nom = isset($params['nom']) ? $params['nom'] : $this->nom; $this->email = @$params['email']; $this->objet = isset($params['objet']) ? $params['objet'] : $this->objet; $this->message = @$params['message']; $this->antibot = isset($params['antibot']) ? $params['antibot'] : $this->antibot; $this->sent = isset($params['sent']) ? $params['sent'] : $this->sent; // $this->sentDate = isset($params['sentDate']) ? $params['sentDate'] : $this->sentDate; $this->addDestinataire(EmailContact, SiteNom); if (isset($params['destinataire']) && NULL != $params['destinataire']) { if ('flambeaux' == $params['destinataire']) { $this->addDestinataire(EmailFlambeaux, 'Flambeaux de Saint-Maur'); } elseif ('gdj' == $params['destinataire']) { $this->addDestinataire(EmailGDJ, 'GDJ de Saint-Maur'); } } $this->prepareToSave(); } /** * Vérifie la validité de cet élément * return true si les données sont valides * thrown Exception */ public function isValid() { $erreur = ''; $erreurs = array(); $champsManquants = array(); // Vérification des data if (!isset($this->email) || $this->email == NULL) { $champsManquants[] = '<label for="email" class="error">Nous aurons besoin de votre email pour vous répondre.</label>'; } if (isset($this->email) && $this->email != NULL && !preg_match('!^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$!i', $this->email)) { $erreurs[] = '<label for="email" class="error">Cette adresse email n\'est pas valide.</label>'; } if (!isset($this->message) || $this->message == NULL) { $champsManquants[] = '<label for="message" class="error">Vous n\'auriez pas oublié d\'écrire votre message par hasard ?</label>'; } if (!isset($this->antibot) || $this->antibot == NULL || (isset($this->antibot) && $this->antibot != NULL && $this->antibot != Antibot)) { $erreurs[] = '<label for="antibot" class="error">En répondant à la question antispam (dont la réponse est '.Antibot.'), vous nous permettez de vérifier que vous êtes bien humain et non un robot souhaitant nous envoyer du spam !</label>'; } // Retour du message correspondant $nbManquant = count($champsManquants); $nbErreur = count($erreurs); if ($nbManquant > 0) { if ($nbManquant > 1) $erreur = '<li>Il semble que vous ayez oublié quelques champs indispensables : <ul><li>'.implode('</li><li>', $champsManquants).'</li></ul></li>'; else $erreur = '<li>'.$champsManquants[0].'</li>'; } if ($nbErreur > 0) { $erreur .= '<li>'.implode('</li><li>', $erreurs).'</li>'; } if (NULL != $erreur && '' != $erreur) { if ($nbErreur+$nbManquant > 1) { $erreur = 'Merci de corriger les erreurs suivantes : <ul>'.$erreur.'</ul>'; } else { $erreur = '<ul>'.$erreur.'</ul>'; } throw new Exception($erreur, ERREUR_BLOQUANT); } return true; } public function prepareToPrint() { $this->prepareToPrintForm(); } public function prepareToPrintForm() { $this->nom = deparserS($this->nom); $this->email = deparserS($this->email); $this->objet = deparserS($this->objet); $this->sentDate = deparserS($this->sentDate); $this->message = br2nl(deparserS($this->message)); $this->antibot = parserI($this->antibot); $this->sent = parserI($this->sent); } public function prepareToSave() { $this->nom = strip_tags(parserS($this->nom)); $this->email = strip_tags(parserS($this->email)); $this->objet = strip_tags(parserS($this->objet)); $this->message = strip_tags(parserS($this->message)); $this->antibot = parserI($this->antibot); $this->sent = parserI($this->sent); $this->sentDate = parserS($this->sentDate); } // --- Get/Set public function getNom() { return $this->nom; } public function setNom($nom) { $this->nom = $nom; } public function getEmail() { return $this->email; } public function setEmail($email) { $this->email = $email; } public function getObjet() { return $this->objet; } public function setObjet($objet) { $this->objet = $objet; } public function getMessage() { return $this->message; } public function setMessage($message) { $this->message = $message; } public function getAntibot() { return $this->antibot; } public function setAntibot($antibot) { $this->antibot = $antibot; } public function getSent() { return $this->sent; } public function setSent($sent) { $this->sent = $sent; } public function getSentDate() { return $this->sentDate; } public function setSentDate($sentDate) { $this->sentDate = $sentDate; } public function getExpediteur() { if (NULL == $this->expediteur || '' == $this->expediteur || (is_array($this->expediteur) && count($this->expediteur) == 0)) { $this->setExpediteur($this->email, $this->nom); } return $this->expediteur; } public function setExpediteur($email, $nom=NULL) { if (NULL != $nom && '' != $nom) { $this->expediteur[$nom] = $email; } else { $this->expediteur = $email; } } public function getDestinataires() { return $this->destinataires; } public function setDestinataires($destinataires) { $this->destinataires = $destinataires; } public function addDestinataire($email, $nom=NULL) { if (NULL != $nom && '' != $nom) { $this->destinataires[$nom] = $email; } else { $this->destinataires[] = $email; } } public function getDestinatairesCc() { return $this->destinatairesCc; } public function setDestinatairesCc($destinatairesCc) { $this->destinatairesCc = $destinatairesCc; } public function addDestinataireCc($email, $nom=NULL) { if (NULL != $nom && '' != $nom) { $this->destinatairesCc[$nom] = $email; } else { $this->destinatairesCc[] = $email; } } public function getDestinatairesCci() { return $this->destinatairesCci; } public function setDestinatairesCci($destinatairesCci) { $this->destinatairesCci = $destinatairesCci; } public function addDestinataireCci($email, $nom=NULL) { if (NULL != $nom && '' != $nom) { $this->destinatairesCci[$nom] = $email; } else { $this->destinatairesCci[] = $email; } } } ?>
lgpl-3.0
pcolby/libqtaws
src/redshift/deletescheduledactionresponse.cpp
4669
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "deletescheduledactionresponse.h" #include "deletescheduledactionresponse_p.h" #include <QDebug> #include <QNetworkReply> #include <QXmlStreamReader> namespace QtAws { namespace Redshift { /*! * \class QtAws::Redshift::DeleteScheduledActionResponse * \brief The DeleteScheduledActionResponse class provides an interace for Redshift DeleteScheduledAction responses. * * \inmodule QtAwsRedshift * * <fullname>Amazon Redshift</fullname> * * <b>Overview</b> * * </p * * This is an interface reference for Amazon Redshift. It contains documentation for one of the programming or command line * interfaces you can use to manage Amazon Redshift clusters. Note that Amazon Redshift is asynchronous, which means that * some interfaces may require techniques, such as polling or asynchronous callback handlers, to determine when a command * has been applied. In this reference, the parameter descriptions indicate whether a change is applied immediately, on the * next instance reboot, or during the next maintenance window. For a summary of the Amazon Redshift cluster management * interfaces, go to <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/using-aws-sdk.html">Using the Amazon * Redshift Management * * Interfaces</a>> * * Amazon Redshift manages all the work of setting up, operating, and scaling a data warehouse: provisioning capacity, * monitoring and backing up the cluster, and applying patches and upgrades to the Amazon Redshift engine. You can focus on * using your data to acquire new insights for your business and * * customers> * * If you are a first-time user of Amazon Redshift, we recommend that you begin by reading the <a * href="https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html">Amazon Redshift Getting Started * * Guide</a>> * * If you are a database developer, the <a href="https://docs.aws.amazon.com/redshift/latest/dg/welcome.html">Amazon * Redshift Database Developer Guide</a> explains how to design, build, query, and maintain the databases that make up your * data warehouse. * * \sa RedshiftClient::deleteScheduledAction */ /*! * Constructs a DeleteScheduledActionResponse object for \a reply to \a request, with parent \a parent. */ DeleteScheduledActionResponse::DeleteScheduledActionResponse( const DeleteScheduledActionRequest &request, QNetworkReply * const reply, QObject * const parent) : RedshiftResponse(new DeleteScheduledActionResponsePrivate(this), parent) { setRequest(new DeleteScheduledActionRequest(request)); setReply(reply); } /*! * \reimp */ const DeleteScheduledActionRequest * DeleteScheduledActionResponse::request() const { Q_D(const DeleteScheduledActionResponse); return static_cast<const DeleteScheduledActionRequest *>(d->request); } /*! * \reimp * Parses a successful Redshift DeleteScheduledAction \a response. */ void DeleteScheduledActionResponse::parseSuccess(QIODevice &response) { //Q_D(DeleteScheduledActionResponse); QXmlStreamReader xml(&response); /// @todo } /*! * \class QtAws::Redshift::DeleteScheduledActionResponsePrivate * \brief The DeleteScheduledActionResponsePrivate class provides private implementation for DeleteScheduledActionResponse. * \internal * * \inmodule QtAwsRedshift */ /*! * Constructs a DeleteScheduledActionResponsePrivate object with public implementation \a q. */ DeleteScheduledActionResponsePrivate::DeleteScheduledActionResponsePrivate( DeleteScheduledActionResponse * const q) : RedshiftResponsePrivate(q) { } /*! * Parses a Redshift DeleteScheduledAction response element from \a xml. */ void DeleteScheduledActionResponsePrivate::parseDeleteScheduledActionResponse(QXmlStreamReader &xml) { Q_ASSERT(xml.name() == QLatin1String("DeleteScheduledActionResponse")); Q_UNUSED(xml) ///< @todo } } // namespace Redshift } // namespace QtAws
lgpl-3.0
Godin/sonar
server/sonar-web/src/main/js/apps/webhooks/components/DeliveryItem.tsx
2259
/* * SonarQube * Copyright (C) 2009-2019 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. */ import * as React from 'react'; import CodeSnippet from '../../../components/common/CodeSnippet'; import DeferredSpinner from '../../../components/common/DeferredSpinner'; import { formatMeasure } from '../../../helpers/measures'; import { translateWithParameters, translate } from '../../../helpers/l10n'; interface Props { className?: string; delivery: T.WebhookDelivery; loading: boolean; payload: string | undefined; } export default function DeliveryItem({ className, delivery, loading, payload }: Props) { return ( <div className={className}> <p className="spacer-bottom"> {translateWithParameters( 'webhooks.delivery.response_x', delivery.httpStatus || translate('webhooks.delivery.server_unreachable') )} </p> <p className="spacer-bottom"> {translateWithParameters( 'webhooks.delivery.duration_x', formatMeasure(delivery.durationMs, 'MILLISEC') )} </p> <p className="spacer-bottom">{translate('webhooks.delivery.payload')}</p> <DeferredSpinner className="spacer-left spacer-top" loading={loading}> {payload && <CodeSnippet noCopy={true} snippet={formatPayload(payload)} />} </DeferredSpinner> </div> ); } function formatPayload(payload: string) { try { return JSON.stringify(JSON.parse(payload), undefined, 2); } catch (error) { return payload; } }
lgpl-3.0
tyotann/tyo-java-frame
src/com/ihidea/component/mobile/push/BlankPush.java
812
package com.ihidea.component.mobile.push; import java.util.List; public class BlankPush implements IPush { @Override public void pushToUser(String appid, String userId, MobilePushEntity pushEntity) { // TODO Auto-generated method stub } @Override public void pushToUserList(String appid, List<String> userIdList, MobilePushEntity pushEntity) { // TODO Auto-generated method stub } @Override public void pushToDevice(String appid, List<String> deviceTokenList, MobilePushEntity pushEntity) { // TODO Auto-generated method stub } @Override public void pushToApp(String appid, MobilePushEntity pushEntity) { // TODO Auto-generated method stub } @Override public void pushToTag(String appid, String tagName, MobilePushEntity pushEntity) { // TODO Auto-generated method stub } }
lgpl-3.0
ideaconsult/i5
iuclid_6_2-io/src/main/java/eu/europa/echa/iuclid6/namespaces/endpoint_study_record_crystallitegrainsize/_2/package-info.java
297
@javax.xml.bind.annotation.XmlSchema(namespace = "http://iuclid6.echa.europa.eu/namespaces/ENDPOINT_STUDY_RECORD-CrystalliteGrainSize/2.0", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package eu.europa.echa.iuclid6.namespaces.endpoint_study_record_crystallitegrainsize._2;
lgpl-3.0
mobmewireless/origami-pdf
bin/gui/walker.rb
7240
#!/usr/bin/env ruby =begin = File walker.rb = Info This file is part of PDF Walker, a graphical PDF file browser Copyright (C) 2010 Guillaume Delugré <guillaume@security-labs.org> All right reserved. PDF Walker 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. PDF Walker 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 PDF Walker. If not, see <http://www.gnu.org/licenses/>. =end begin require 'gtk2' rescue LoadError abort('Error: you need to install ruby-gtk2 to run this application') end include Gtk begin require 'origami' rescue LoadError ORIGAMIDIR = "#{File.dirname(__FILE__)}/../../lib" $: << ORIGAMIDIR require 'origami' end require 'gui/menu' require 'gui/about' require 'gui/file' require 'gui/hexview' require 'gui/treeview' require 'gui/textview' require 'gui/imgview' require 'gui/config' require 'gui/properties' require 'gui/xrefs' require 'gui/signing' module PDFWalker #:nodoc:all class Walker < Window attr_reader :treeview, :hexview, :objectview attr_reader :explorer_history attr_reader :config attr_reader :filename def self.start(file = nil) Gtk.init Walker.new(file) Gtk.main end def initialize(target_file = nil) super("PDF Walker") @config = Walker::Config.new @last_search_result = [] @last_search = { :expr => "", :regexp => false, :type => :body } @explorer_history = Array.new signal_connect('destroy') { @config.save Gtk.main_quit } add_events(Gdk::Event::KEY_RELEASE_MASK) signal_connect('key_release_event') { |w, event| if event.keyval == Gdk::Keyval::GDK_F1 then about elsif event.keyval == Gdk::Keyval::GDK_Escape && @opened && ! @explorer_history.empty? @treeview.goto(@explorer_history.pop) end } create_menus create_treeview create_hexview create_objectview create_panels create_statusbar @vbox = VBox.new @vbox.pack_start(@menu, false, false) @vbox.pack_start(@hpaned) @vbox.pack_end(@statusbar, false, false) add @vbox set_default_size(self.screen.width * 0.5, self.screen.height * 0.5) #maximize show_all open(target_file) end def error(msg) dialog = Gtk::MessageDialog.new(self, Gtk::Dialog::DESTROY_WITH_PARENT, Gtk::MessageDialog::ERROR, Gtk::MessageDialog::BUTTONS_CLOSE, msg) dialog.run dialog.destroy end def reload @treeview.load(@opened) if @opened end def search dialog = Gtk::Dialog.new("Search...", self, Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT, [Gtk::Stock::FIND, Gtk::Dialog::RESPONSE_OK], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL] ) entry = Gtk::Entry.new entry.signal_connect('activate') { dialog.response(Gtk::Dialog::RESPONSE_OK) } entry.text = @last_search[:expr] button_bydata = Gtk::RadioButton.new("In object body") button_byname = Gtk::RadioButton.new(button_bydata, "In object name") button_regexp = Gtk::CheckButton.new("Regular expression") button_bydata.set_active(true) if @last_search[:type] == :body button_byname.set_active(true) if @last_search[:type] == :name button_regexp.set_active(@last_search[:regexp]) hbox = HBox.new hbox.pack_start Gtk::Label.new("Search for expression ") hbox.pack_start entry dialog.vbox.pack_start(hbox) dialog.vbox.pack_start(button_bydata) dialog.vbox.pack_start(button_byname) dialog.vbox.pack_end(button_regexp) dialog.signal_connect('response') do |dlg, response| if response == Gtk::Dialog::RESPONSE_OK search = { :expr => entry.text, :regexp => button_regexp.active?, :type => button_byname.active? ? :name : :body } if search == @last_search @last_search_result.push @last_search_result.shift results = @last_search_result else expr = search[:regexp] ? Regexp.new(search[:expr]) : search[:expr] results = if search[:type] == :body @opened.grep(expr) else @opened.ls(expr) end @last_search = search end if results.empty? error("No result found.") else if results != @last_search_result @last_search_result.each do |obj| @treeview.highlight(obj, nil) end results.each do |obj| @treeview.highlight(obj, "lightpink") end @last_search_result = results end @treeview.goto(results.first) end else dialog.destroy end end dialog.show_all end def goto_catalog @treeview.goto(@opened.Catalog.reference) end def goto_object dialog = Gtk::Dialog.new("Jump to object...", self, Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT, [Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL] ) entry = Gtk::Entry.new entry.signal_connect('activate') { dialog.response(Gtk::Dialog::RESPONSE_OK) } dialog.vbox.pack_start Gtk::Label.new("Object number: ") dialog.vbox.pack_start entry dialog.show_all no = 0 dialog.run do |response| if response == Gtk::Dialog::RESPONSE_OK no = entry.text.to_i end dialog.destroy end if no > 0 obj = @opened[no] if obj.nil? error("Object #{no} not found.") else @treeview.goto(obj) end end end private def create_panels @hpaned = HPaned.new @treepanel = ScrolledWindow.new.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC) @treepanel.add @treeview @vpaned = VPaned.new @vpaned.pack1(@objectview, true, false) @vpaned.pack2(@hexview, true, false) @hpaned.pack1(@treepanel, true, false) @hpaned.pack2(@vpaned, true, false) end def create_statusbar @statusbar = Statusbar.new @main_context = @statusbar.get_context_id 'Main' @statusbar.push(@main_context, 'No file selected') end end end if __FILE__ == $0 PDFWalker::Walker.start end
lgpl-3.0
awltech/eclipse-optimus
net.atos.optimus.m2m.engine.sdk.parent/net.atos.optimus.m2m.engine.sdk.tom.properties/src/main/java/net/atos/optimus/m2m/engine/sdk/tom/properties/zones/InputWithLabel.java
3447
/** * Optimus, framework for Model Transformation * * Copyright (C) 2013 Worldline or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.atos.optimus.m2m.engine.sdk.tom.properties.zones; import net.atos.optimus.m2m.engine.sdk.tom.properties.listeners.TextChangeListener; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.gmf.runtime.diagram.ui.properties.views.TextChangeHelper; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import com.worldline.gmf.propertysections.core.tools.FormDataBuilder; /** * Models a zone with a label and an input field * * @author tnachtergaele <nachtergaele.thomas@gmail.com> * * * @param <T> * the type of the input field */ public abstract class InputWithLabel<T extends Control> extends InputZone { /** The input field */ protected T input; /** The label describing the input field containment */ protected CLabel associatedLabel; /** The text of the label */ protected String labelText; /** The width of the label */ protected int labelWidth; /** * Constructor * * @param parent * parent composite. * @param isGroup * true creates a Group, false creates a standard Composite. * @param associatedModelFeature * the model feature of the model associated to the value in the * input text field. * @param labelText * the text of the label associated to the input field. * @param labelWidth * the width of the label associated to the input field. */ public InputWithLabel(Composite parent, boolean isGroup, EStructuralFeature associatedModelFeature, String labelText, int labelWidth) { super(parent, isGroup, associatedModelFeature); this.labelText = labelText; this.labelWidth = labelWidth; } /** * Add an input field in the zone * */ protected abstract void addInputField(); @Override public void addItemsToZone() { this.associatedLabel = this.getWidgetFactory().createCLabel(getZone(), this.labelText); this.addInputField(); } @Override public void addLayoutsToItems() { FormDataBuilder.on(this.associatedLabel).left().top().bottom().width(this.labelWidth); FormDataBuilder.on(this.input).left(this.associatedLabel).top().right().bottom(); } @Override public void addListenersToItems() { TextChangeHelper nameTextListener = new TextChangeListener(this); /* Listener setting */ nameTextListener.startListeningTo(this.input); nameTextListener.startListeningForEnter(this.input); } @Override public abstract void updateItemsValues(); }
lgpl-3.0
Mindtoeye/Hoop
src/edu/cmu/cs/in/base/io/HoopBerkeleyAltDocumentDB.java
5111
/** * Author: Martin van Velsen <vvelsen@cs.cmu.edu> * * 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 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 edu.cmu.cs.in.base.io; import java.util.Iterator; import java.util.Map; import com.sleepycat.bind.serial.SerialBinding; import com.sleepycat.bind.tuple.LongBinding; //import com.sleepycat.bind.tuple.StringBinding; import com.sleepycat.collections.StoredMap; import edu.cmu.cs.in.base.kv.HoopKVDocument; /** * */ public class HoopBerkeleyAltDocumentDB extends HoopBerkeleyDBBase { // Maps a custom unique ID (or long) to a document private StoredMap<Long,HoopKVDocument> mapByID=null; /** * */ public HoopBerkeleyAltDocumentDB () { setClassName ("HoopBerkeleyAltDocumentDB"); debug ("HoopBerkeleyAltDocumentDB ()"); } /** * */ public StoredMap<Long,HoopKVDocument> getData () { return mapByID; } /** * */ public void assignMap (StoredMap<Long,HoopKVDocument> aMap) { debug ("assignMap ()"); mapByID=aMap; } /** * */ public Boolean bind () { debug ("bind ()"); // First one LongBinding keyBinding = new LongBinding(); SerialBinding <HoopKVDocument> dataBinding=new SerialBinding<HoopKVDocument> (this.getJavaCatalog(),HoopKVDocument.class); this.mapByID=new StoredMap<Long, HoopKVDocument> (this.getDB(),keyBinding,dataBinding,true); if (this.mapByID==null) { debug ("Error creating StoredMap from database"); setDbDisabled (true); return (false); } return (true); } /** * Closes the database. */ public Boolean close() { debug ("close ()"); if (super.close()==false) return (false); debug("Resetting map ..."); this.mapByID=null; debug("Database successfully shutdown"); return (true); } /** * @param aKey String * @param aValue ArrayList<Object> */ public boolean writeKV (Long aKey,HoopKVDocument aValue) { debug ("writeKV (key:"+aKey+", value:"+aValue+")"); if (this.isDbDisabled()==true) { debug ("Error: database is not open or disabled, aborting"); return (false); } if (mapByID==null) { debug ("No map available to write to, aborting .."); return (false); } mapByID.put (aKey,aValue); return (true); } /** * */ public void dumpDB () { debug ("dumpDB ()"); if (this.isDbDisabled()==true) { debug ("Error: database is not open or disabled, aborting"); return; } if (mapByID==null) { debug ("No map available to read from, aborting .."); return; } debug ("Map size: " + mapByID.size() + " entries"); Iterator<Map.Entry<Long,HoopKVDocument>> iter=null; try { iter=mapByID.entrySet().iterator(); } catch (IndexOutOfBoundsException e) { debug ("Integrity check failed, IndexOutOfBoundsException"); } debug ("Reading data ..."); while (iter.hasNext()) { Map.Entry<Long,HoopKVDocument> entry = iter.next(); debug (entry.getKey().toString() + ' ' + entry.getValue()); } } /** * */ public Boolean checkDB () { debug ("checkDB ()"); if (this.isDbDisabled()==true) { debug ("Error: database is not open or disabled, aborting"); return (false); } if (mapByID==null) { debug ("No map available to read from, aborting .."); return (false); } debug ("Checking: " + mapByID.size() + " entries"); Iterator<Map.Entry<Long,HoopKVDocument>> iter=null; try { iter=mapByID.entrySet().iterator(); } catch (IndexOutOfBoundsException e) { debug ("Integrity check failed, IndexOutOfBoundsException"); return (false); } while (iter.hasNext()) { @SuppressWarnings("unused") Map.Entry<Long,HoopKVDocument> entry = iter.next(); //debug (entry.getKey().toString() + ' ' + entry.getValue()); System.out.print("."); } debug (" done"); return (true); } }
lgpl-3.0
SOCR/HTML5_WebSite
SOCR2.8/src/edu/ucla/stat/SOCR/analyses/result/SurvivalResult.java
3765
/**************************************************** Statistics Online Computational Resource (SOCR) http://www.StatisticsResource.org All SOCR programs, materials, tools and resources are developed by and freely disseminated to the entire community. Users may revise, extend, redistribute, modify under the terms of the Lesser GNU General Public License as published by the Open Source Initiative http://opensource.org/licenses/. All efforts should be made to develop and distribute factually correct, useful, portable and extensible resource all available in all digital formats for free over the Internet. SOCR resources are distributed in the hope that they will be useful, but without any warranty; without any explicit, implicit or implied warranty for merchantability or fitness for a particular purpose. See the GNU Lesser General Public License for more details see http://opensource.org/licenses/lgpl-license.php. http://www.SOCR.ucla.edu http://wiki.stat.ucla.edu/socr It s Online, Therefore, It Exists! ****************************************************/ package edu.ucla.stat.SOCR.analyses.result; import java.util.HashMap; public class SurvivalResult extends AnalysisResult { public static final String SURVIVAL_TIME = "SURVIVAL_TIME"; public static final String SURVIVAL_RATE = "SURVIVAL_RATE"; public static final String SURVIVAL_RATE_UPPER_CI = "SURVIVAL_RATE_UPPER_CI"; public static final String SURVIVAL_RATE_LOWER_CI = "SURVIVAL_RATE_LOWER_CI"; public static final String SURVIVAL_AT_RISK = "SURVIVAL_AT_RISK"; public static final String SURVIVAL_SE = "SURVIVAL_SE"; public static final String SURVIVAL_GROUP_NAMES = "SURVIVAL_GROUP_NAMES"; public static final String SURVIVAL_TIME_LIST = "SURVIVAL_TIME_LIST"; public static final String SURVIVAL_CENSORED_TIME = "SURVIVAL_CENSORED_TIME"; public static final String SURVIVAL_CENSORED_RATE = "SURVIVAL_CENSORED_RATE"; public static final String MAX_TIME = "MAX_TIME"; public static final String NUMBER_CENCORED = "NUMBER_CENCORED"; /*********************** Constructors ************************/ public SurvivalResult(HashMap texture) { super(texture); } public SurvivalResult(HashMap texture, HashMap graph) { super(texture, graph); } /*********************** Accessors ************************/ // for these arrays: first index is for treatment groups, second for patient data. public double[][] getSurvivalTime() { return ((double[][])texture.get(SURVIVAL_TIME)); } public double[][] getSurvivalRate() { return ((double[][])texture.get(SURVIVAL_RATE)); } public double[][] getSurvivalUpperCI() { return ((double[][])texture.get(SURVIVAL_RATE_UPPER_CI)); } public double[][] getSurvivalLowerCI() { return ((double[][])texture.get(SURVIVAL_RATE_LOWER_CI)); } public int[][] getSurvivalAtRisk() { ////System.out.println("result getSurvivalAtRisk is called"); return ((int[][])texture.get(SURVIVAL_AT_RISK)); } public double[][] getSurvivalSE() { return ((double[][])texture.get(SURVIVAL_SE)); } public String[] getSurvivalGroupNames() { return ((String[])texture.get(SURVIVAL_GROUP_NAMES)); } public String getSurvivalTimeList() { return ((String)texture.get(SURVIVAL_TIME_LIST)); } public double[][] getCensoredTimeArray() { return ((double[][])texture.get(SURVIVAL_CENSORED_TIME)); } public double[][] getCensoredRateArray() { return ((double[][])texture.get(SURVIVAL_CENSORED_RATE)); } public double[] getMaxTime() { return ((double[])texture.get(MAX_TIME)); } public String getNumberCensored() { return ((String)texture.get(NUMBER_CENCORED)); //return ((Integer)texture.get(NUMBER_CENCORED)).intValue(); } }
lgpl-3.0
eenbp/OpenNaaS-0.14-Marketplace
extensions/bundles/network.model/src/main/java/org/opennaas/extensions/network/model/domain/AdministrativeDomain.java
1881
package org.opennaas.extensions.network.model.domain; import java.util.List; import org.opennaas.extensions.network.model.topology.NetworkElement; /** * An entity that acts as a the administrator of a collection of resources. * The administrator is the entity who actually controls and provisions the resources. * An administrative domain can include computing, visualization, storage and network resources. * An Administrative Domain does not say anything about the data plane or the Location. * For that, see Network Domain and Location. * The administrator enforces policies, and should not be confused with the (economic) owner, who decides on the policy. * The administrator and owner of a network element are often, but not always, the same entity! * For example, a link between domain 1 and domain 2 is owned by domain 1. * So domain 1 effectively decides on the policy of the terminating interfaces of the link. * Thus also the interface of this link in domain 2. * That interface is than owned by domain 1, but administrated by domain 2. * A clear example of this is in so-called “open” optical exchanges. * The advantage of administrative domains is that a device including all its interfaces belongs to a single administrative domain. * In this RDF description, an Administrative domain only hasNetworkElements of type Device. * The Interfaces of the device are implied to reside in the domain due to the hasInterface property. * Beside the properties given here, you may want to use the vCard:ORG property to describe the name of the Adminstrator. * * @author isart * */ public class AdministrativeDomain { List<NetworkElement> domainElements; public List<NetworkElement> getDomainElements() { return domainElements; } public void setDomainElements(List<NetworkElement> domainElements) { this.domainElements = domainElements; } }
lgpl-3.0
Spacecraft-Code/SPELL
include/SPELL_EXC/SPELLinterpreter.H
10862
// ################################################################################ // FILE : SPELLinterpreter.H // DATE : Mar 17, 2011 // PROJECT : SPELL // DESCRIPTION: Main entry point of the executor. // -------------------------------------------------------------------------------- // // Copyright (C) 2008, 2015 SES ENGINEERING, Luxembourg S.A.R.L. // // This file is part of SPELL. // // SPELL 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. // // SPELL 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 SPELL. If not, see <http://www.gnu.org/licenses/>. // // ################################################################################ #ifndef __SPELL_INTERPRETER_H__ #define __SPELL_INTERPRETER_H__ // FILES TO INCLUDE //////////////////////////////////////////////////////// // Local includes ---------------------------------------------------------- #include "SPELL_EXC/SPELLexecutorIF.H" // Project includes -------------------------------------------------------- // System includes --------------------------------------------------------- /** \addtogroup SPELL_EXC */ /*@{*/ // FORWARD REFERENCES ////////////////////////////////////////////////////// // ENUMS /////////////////////////////////////////////////////////////////// // TYPES /////////////////////////////////////////////////////////////////// /** Configuration parameters for the interpreter */ typedef struct SPELLinterpreterConfig_ { /** If true, WS is enabled and the given persistent file is used */ bool warmstart; /** If true, the given persistent file is used to recover status */ bool recover; /** If true, the given procId corresponds to a script, not a proc id */ bool script; /** Path to main configuration file */ std::string configFile; /** Procedure identifier or script path */ std::string procId; /** SPELL context to be used */ std::string ctxName; /** Context listening port */ int ctxPort; /** Time string to be used in generated files */ std::string timeId; /** If given, holds the path to the file where WS data is stored */ std::string persis; } SPELLinterpreterConfig; // DEFINES ///////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /** ** \brief Encapsulates the Python interpreter framework in a single object. ** ** \par Description and usage: ** ** The interpreter is the main class of the executor ** process. It creates all the pieces needed to execute a given script ** or procedure. It provides also the ability of recovering a proc ** execution by using a given WS information file. ** ** Singleton used in the main program function. ** **//////////////////////////////////////////////////////////////////////////// class SPELLinterpreter { public: //-------------------------------------------------------------------- // EXCEPTIONS //////////////////////////////////////////////////////////// // ENUMS ///////////////////////////////////////////////////////////////// // TYPES ///////////////////////////////////////////////////////////////// // LIFECYCLE ///////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /** Destructor. **//////////////////////////////////////////////////////////////////// ~SPELLinterpreter(); // STATIC //////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /** Access to the singleton instance **//////////////////////////////////////////////////////////////////// static SPELLinterpreter& instance(); // METHODS /////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /** Main interpreter program loop. Will first prepare the control * objects (controller, scheduler, callstack, etc), \see prepareObjects * method. Then, execution environment will be set up (\see prepareExecution * method). If both operations are success, the methods recover() or * execute() are invoked depending on the command line arguments of * the executor application. Once these finish, it waits for the signal * to cleanup all things in order to exit the executor process. **//////////////////////////////////////////////////////////////////// void mainLoop(); ////////////////////////////////////////////////////////////////////// /** Initialize the interpreter with the given configuration ** ** \param config IN: Configuration data ** \param cif IN: SPELL client interface instance to use. **//////////////////////////////////////////////////////////////////// void initialize( const SPELLinterpreterConfig& config, SPELLcif* cif ); // DATA MEMBERS ////////////////////////////////////////////////////////// protected: //----------------------------------------------------------------- // EXCEPTIONS //////////////////////////////////////////////////////////// // ENUMS ///////////////////////////////////////////////////////////////// // TYPES ///////////////////////////////////////////////////////////////// // LIFECYCLE ///////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /** Constructor. **//////////////////////////////////////////////////////////////////// SPELLinterpreter(); // METHODS /////////////////////////////////////////////////////////////// // DATA MEMBERS ////////////////////////////////////////////////////////// private: //------------------------------------------------------------------- // EXCEPTIONS //////////////////////////////////////////////////////////// // ENUMS ///////////////////////////////////////////////////////////////// // TYPES ///////////////////////////////////////////////////////////////// // LIFECYCLE ///////////////////////////////////////////////////////////// // METHODS /////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /** Prepare the CIF component **//////////////////////////////////////////////////////////////////// void prepareCIF( const SPELLcontextConfig& ctxConfig ); ////////////////////////////////////////////////////////////////////// /** Recover the CIF component information **//////////////////////////////////////////////////////////////////// void recoverCIF( const SPELLcontextConfig& ctxConfig ); ////////////////////////////////////////////////////////////////////// /** Prepare the warm start / error recovery support mechanism. It will * build the warmstart persistence file name, create the SPELLwarmStart * object and initialize the execution frame with their references. MAy * fail if SPELL_DATA environment variable is not set, or the persistent * file cannot be created. **//////////////////////////////////////////////////////////////////// void prepareWarmStart( const SPELLcontextConfig& ctxConfig ); ////////////////////////////////////////////////////////////////////// /** If initial preparation succeeds, additional mechanisms are intialized * configured and/or installed: * * 1. Install special exceptions on Python side * 2. Install the executor instance on the SPELL registry * 3. Install the go-to mechanism on Python side * 4. Install the CIF instance on the SPELL registry * 5. Get procedure and User Library search paths * 6. Compile the procedure code and prepare the execution frame. * * \returns False in case of failure. **//////////////////////////////////////////////////////////////////// const bool prepareExecution(); ////////////////////////////////////////////////////////////////////// /** Prepare objects neede for the execution of the procedure/script. * The following steps are performed: * * 1. Initialize Python API * 2. Install Log mechanism on Python side * 3. Import SPELL framework on Python side. * 4. Load configuration from XML files * 5. Setup the client interface to connect to the client * 6. Create control objects (controller, scheduler, frame, etc) * 7. Prepare the warm start support * 8. Initialize and configure the executor object * 9. Start the command controller. * * \returns False in case of failure. **//////////////////////////////////////////////////////////////////// const bool prepareObjects(); ////////////////////////////////////////////////////////////////////// /** Execute the script/procedure. Basically invoke the execute() method * of the executor object and catch any error taking place. **//////////////////////////////////////////////////////////////////// void execute(); ////////////////////////////////////////////////////////////////////// /** Recover script/procedure execution from persistent file. Invoke * the recover() method of the executor object. **//////////////////////////////////////////////////////////////////// void recover(); ////////////////////////////////////////////////////////////////////// /** Handle errors raised during the initialization performed by the * prepareExecution method. **//////////////////////////////////////////////////////////////////// void handleStartupError(); // DATA MEMBERS ////////////////////////////////////////////////////////// /** Interpreter configuration */ SPELLinterpreterConfig m_config; /** Executor instance */ SPELLexecutorIF* m_executor; /** Warm start mechanism */ SPELLwarmStart* m_warmStart; /** Client interface */ SPELLcif* m_cif; /** Execution controller */ SPELLcontrollerIF* m_controller; /** Execution scheduler */ SPELLschedulerIF* m_scheduler; /** Callstack manager */ SPELLcallstackIF* m_callstack; /** Execution frame */ SPELLframeManager* m_frameManager; /** Current procedure or file name */ std::string m_procedure; /** Current procedures path */ std::string m_procPath; /** Current library path */ std::string m_libPath; }; /*@}*/ #endif
lgpl-3.0
GumTreeDiff/gumtree
gen.srcml/src/main/java/com/github/gumtreediff/gen/srcml/AbstractSrcmlTreeGenerator.java
6353
/* * This file is part of GumTree. * * GumTree 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. * * GumTree 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 GumTree. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2016 Jean-Rémy Falleri <jr.falleri@gmail.com> */ package com.github.gumtreediff.gen.srcml; import com.github.gumtreediff.gen.ExternalProcessTreeGenerator; import com.github.gumtreediff.io.LineReader; import com.github.gumtreediff.tree.Tree; import com.github.gumtreediff.tree.Type; import com.github.gumtreediff.tree.TreeContext; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.events.*; import java.io.*; import java.util.*; import static com.github.gumtreediff.tree.TypeSet.type; public abstract class AbstractSrcmlTreeGenerator extends ExternalProcessTreeGenerator { private static final String SRCML_CMD = System.getProperty("gt.srcml.path", "srcml"); private static final QName POS_START = new QName("http://www.srcML.org/srcML/position", "start", "pos"); private static final QName POS_END = new QName("http://www.srcML.org/srcML/position", "end", "pos"); private LineReader lr; private Set<Type> labeled = new HashSet<>( Arrays.asList( type("specifier"), type("name"), type("comment"), type("literal"), type("operator"), type("file"), type("directive"), type("modifier") )); Type position = type("position"); private StringBuilder currentLabel; private TreeContext context; @Override public TreeContext generate(Reader r) throws IOException { lr = new LineReader(r); String output = readStandardOutput(lr); return getTreeContext(output); } public TreeContext getTreeContext(String xml) { XMLInputFactory fact = XMLInputFactory.newInstance(); context = new TreeContext(); currentLabel = new StringBuilder(); try { ArrayDeque<Tree> trees = new ArrayDeque<>(); XMLEventReader r = fact.createXMLEventReader(new StringReader(xml)); while (r.hasNext()) { XMLEvent ev = r.nextEvent(); if (ev.isStartElement()) { StartElement s = ev.asStartElement(); Type type = type(s.getName().getLocalPart()); if (type.equals(position)) setLength(trees.peekFirst(), s); else { Tree t = context.createTree(type, ""); if (trees.isEmpty()) { context.setRoot(t); t.setPos(0); } else { t.setParentAndUpdateChildren(trees.peekFirst()); setPos(t, s); } trees.addFirst(t); } } else if (ev.isEndElement()) { EndElement end = ev.asEndElement(); if (type(end.getName().getLocalPart()) != position) { if (isLabeled(trees)) trees.peekFirst().setLabel(currentLabel.toString()); trees.removeFirst(); currentLabel = new StringBuilder(); } } else if (ev.isCharacters()) { Characters chars = ev.asCharacters(); if (!chars.isWhiteSpace() && isLabeled(trees)) currentLabel.append(chars.getData().trim()); } } fixPos(context); return context; } catch (Exception e) { e.printStackTrace(); } return null; } private boolean isLabeled(ArrayDeque<Tree> trees) { return labeled.contains(trees.peekFirst().getType()); } private void fixPos(TreeContext ctx) { for (Tree t : ctx.getRoot().postOrder()) { if (!t.isLeaf()) { if (t.getPos() == Tree.NO_POS || t.getLength() == Tree.NO_POS) { Tree firstChild = t.getChild(0); t.setPos(firstChild.getPos()); if (t.getChildren().size() == 1) t.setLength(firstChild.getLength()); else { Tree lastChild = t.getChild(t.getChildren().size() - 1); t.setLength(lastChild.getEndPos() - firstChild.getPos()); } } } } } private void setPos(Tree t, StartElement e) { if (e.getAttributeByName(POS_START) != null) { String posStr = e.getAttributeByName(POS_START).getValue(); String[] chunks = posStr.split(":"); int line = Integer.parseInt(chunks[0]); int column = Integer.parseInt(chunks[1]); t.setPos(lr.positionFor(line, column)); setLength(t, e); } } private void setLength(Tree t, StartElement e) { if (t.getPos() == -1) return; if ( e.getAttributeByName(POS_END) != null) { String posStr = e.getAttributeByName(POS_END).getValue(); String[] chunks = posStr.split(":"); int line = Integer.parseInt(chunks[0]); int column = Integer.parseInt(chunks[1]); t.setLength(lr.positionFor(line, column) - t.getPos() + 1); } } public abstract String getLanguage(); public String[] getCommandLine(String file) { return new String[]{SRCML_CMD, "-l", getLanguage(), "--position", file, "--tabs=1"}; } }
lgpl-3.0
abelsromero/walkmod-core
src/main/java/org/walkmod/exceptions/InvalidConfigurationException.java
288
package org.walkmod.exceptions; @SuppressWarnings("serial") public class InvalidConfigurationException extends Exception { public InvalidConfigurationException(Throwable cause) { super(cause); if (cause != null) { this.setStackTrace(cause.getStackTrace()); } } }
lgpl-3.0
pcolby/libqtaws
src/globalaccelerator/listcustomroutingportmappingsrequest.cpp
13612
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "listcustomroutingportmappingsrequest.h" #include "listcustomroutingportmappingsrequest_p.h" #include "listcustomroutingportmappingsresponse.h" #include "globalacceleratorrequest_p.h" namespace QtAws { namespace GlobalAccelerator { /*! * \class QtAws::GlobalAccelerator::ListCustomRoutingPortMappingsRequest * \brief The ListCustomRoutingPortMappingsRequest class provides an interface for GlobalAccelerator ListCustomRoutingPortMappings requests. * * \inmodule QtAwsGlobalAccelerator * * <fullname>AWS Global Accelerator</fullname> * * This is the <i>AWS Global Accelerator API Reference</i>. This guide is for developers who need detailed information * about AWS Global Accelerator API actions, data types, and errors. For more information about Global Accelerator * features, see the <a href="https://docs.aws.amazon.com/global-accelerator/latest/dg/Welcome.html">AWS Global Accelerator * Developer * * Guide</a>> * * AWS Global Accelerator is a service in which you create <i>accelerators</i> to improve the performance of your * applications for local and global users. Depending on the type of accelerator you choose, you can gain additional * benefits. * * </p <ul> <li> * * By using a standard accelerator, you can improve availability of your internet applications that are used by a global * audience. With a standard accelerator, Global Accelerator directs traffic to optimal endpoints over the AWS global * network. * * </p </li> <li> * * For other scenarios, you might choose a custom routing accelerator. With a custom routing accelerator, you can use * application logic to directly map one or more users to a specific endpoint among many * * endpoints> </li> </ul> <b> * * Global Accelerator is a global service that supports endpoints in multiple AWS Regions but you must specify the US West * (Oregon) Region to create or update * * accelerators> </b> * * By default, Global Accelerator provides you with two static IP addresses that you associate with your accelerator. With * a standard accelerator, instead of using the IP addresses that Global Accelerator provides, you can configure these * entry points to be IPv4 addresses from your own IP address ranges that you bring to Global Accelerator. The static IP * addresses are anycast from the AWS edge network. For a standard accelerator, they distribute incoming application * traffic across multiple endpoint resources in multiple AWS Regions, which increases the availability of your * applications. Endpoints for standard accelerators can be Network Load Balancers, Application Load Balancers, Amazon EC2 * instances, or Elastic IP addresses that are located in one AWS Region or multiple Regions. For custom routing * accelerators, you map traffic that arrives to the static IP addresses to specific Amazon EC2 servers in endpoints that * are virtual private cloud (VPC) * * subnets> <b> * * The static IP addresses remain assigned to your accelerator for as long as it exists, even if you disable the * accelerator and it no longer accepts or routes traffic. However, when you <i>delete</i> an accelerator, you lose the * static IP addresses that are assigned to it, so you can no longer route traffic by using them. You can use IAM policies * like tag-based permissions with Global Accelerator to limit the users who have permissions to delete an accelerator. For * more information, see <a * href="https://docs.aws.amazon.com/global-accelerator/latest/dg/access-control-manage-access-tag-policies.html">Tag-based * * policies</a>> </b> * * For standard accelerators, Global Accelerator uses the AWS global network to route traffic to the optimal regional * endpoint based on health, client location, and policies that you configure. The service reacts instantly to changes in * health or configuration to ensure that internet traffic from clients is always directed to healthy * * endpoints> * * For a list of the AWS Regions where Global Accelerator and other services are currently supported, see the <a * href="https://docs.aws.amazon.com/about-aws/global-infrastructure/regional-product-services/">AWS Region * * Table</a>> * * AWS Global Accelerator includes the following * * components> <dl> <dt>Static IP addresses</dt> <dd> * * Global Accelerator provides you with a set of two static IP addresses that are anycast from the AWS edge network. If you * bring your own IP address range to AWS (BYOIP) to use with a standard accelerator, you can instead assign IP addresses * from your own pool to use with your accelerator. For more information, see <a * href="https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html"> Bring your own IP addresses (BYOIP) in * AWS Global * * Accelerator</a>> * * The IP addresses serve as single fixed entry points for your clients. If you already have Elastic Load Balancing load * balancers, Amazon EC2 instances, or Elastic IP address resources set up for your applications, you can easily add those * to a standard accelerator in Global Accelerator. This allows Global Accelerator to use static IP addresses to access the * * resources> * * The static IP addresses remain assigned to your accelerator for as long as it exists, even if you disable the * accelerator and it no longer accepts or routes traffic. However, when you <i>delete</i> an accelerator, you lose the * static IP addresses that are assigned to it, so you can no longer route traffic by using them. You can use IAM policies * like tag-based permissions with Global Accelerator to delete an accelerator. For more information, see <a * href="https://docs.aws.amazon.com/global-accelerator/latest/dg/access-control-manage-access-tag-policies.html">Tag-based * * policies</a>> </dd> <dt>Accelerator</dt> <dd> * * An accelerator directs traffic to endpoints over the AWS global network to improve the performance of your internet * applications. Each accelerator includes one or more * * listeners> * * There are two types of * * accelerators> <ul> <li> * * A <i>standard</i> accelerator directs traffic to the optimal AWS endpoint based on several factors, including the user’s * location, the health of the endpoint, and the endpoint weights that you configure. This improves the availability and * performance of your applications. Endpoints can be Network Load Balancers, Application Load Balancers, Amazon EC2 * instances, or Elastic IP * * addresses> </li> <li> * * A <i>custom routing</i> accelerator directs traffic to one of possibly thousands of Amazon EC2 instances running in a * single or multiple virtual private clouds (VPCs). With custom routing, listener ports are mapped to statically associate * port ranges with VPC subnets, which allows Global Accelerator to determine an EC2 instance IP address at the time of * connection. By default, all port mapping destinations in a VPC subnet can't receive traffic. You can choose to configure * all destinations in the subnet to receive traffic, or to specify individual port mappings that can receive * * traffic> </li> </ul> * * For more information, see <a * href="https://docs.aws.amazon.com/global-accelerator/latest/dg/introduction-accelerator-types.html">Types of * * accelerators</a>> </dd> <dt>DNS name</dt> <dd> * * Global Accelerator assigns each accelerator a default Domain Name System (DNS) name, similar to * <code>a1234567890abcdef.awsglobalaccelerator.com</code>, that points to the static IP addresses that Global Accelerator * assigns to you or that you choose from your own IP address range. Depending on the use case, you can use your * accelerator's static IP addresses or DNS name to route traffic to your accelerator, or set up DNS records to route * traffic using your own custom domain * * name> </dd> <dt>Network zone</dt> <dd> * * A network zone services the static IP addresses for your accelerator from a unique IP subnet. Similar to an AWS * Availability Zone, a network zone is an isolated unit with its own set of physical infrastructure. When you configure an * accelerator, by default, Global Accelerator allocates two IPv4 addresses for it. If one IP address from a network zone * becomes unavailable due to IP address blocking by certain client networks, or network disruptions, then client * applications can retry on the healthy static IP address from the other isolated network * * zone> </dd> <dt>Listener</dt> <dd> * * A listener processes inbound connections from clients to Global Accelerator, based on the port (or port range) and * protocol (or protocols) that you configure. A listener can be configured for TCP, UDP, or both TCP and UDP protocols. * Each listener has one or more endpoint groups associated with it, and traffic is forwarded to endpoints in one of the * groups. You associate endpoint groups with listeners by specifying the Regions that you want to distribute traffic to. * With a standard accelerator, traffic is distributed to optimal endpoints within the endpoint groups associated with a * * listener> </dd> <dt>Endpoint group</dt> <dd> * * Each endpoint group is associated with a specific AWS Region. Endpoint groups include one or more endpoints in the * Region. With a standard accelerator, you can increase or reduce the percentage of traffic that would be otherwise * directed to an endpoint group by adjusting a setting called a <i>traffic dial</i>. The traffic dial lets you easily do * performance testing or blue/green deployment testing, for example, for new releases across different AWS Regions. * * </p </dd> <dt>Endpoint</dt> <dd> * * An endpoint is a resource that Global Accelerator directs traffic * * to> * * Endpoints for standard accelerators can be Network Load Balancers, Application Load Balancers, Amazon EC2 instances, or * Elastic IP addresses. An Application Load Balancer endpoint can be internet-facing or internal. Traffic for standard * accelerators is routed to endpoints based on the health of the endpoint along with configuration options that you * choose, such as endpoint weights. For each endpoint, you can configure weights, which are numbers that you can use to * specify the proportion of traffic to route to each one. This can be useful, for example, to do performance testing * within a * * Region> * * Endpoints for custom routing accelerators are virtual private cloud (VPC) subnets with one or many EC2 * * \sa GlobalAcceleratorClient::listCustomRoutingPortMappings */ /*! * Constructs a copy of \a other. */ ListCustomRoutingPortMappingsRequest::ListCustomRoutingPortMappingsRequest(const ListCustomRoutingPortMappingsRequest &other) : GlobalAcceleratorRequest(new ListCustomRoutingPortMappingsRequestPrivate(*other.d_func(), this)) { } /*! * Constructs a ListCustomRoutingPortMappingsRequest object. */ ListCustomRoutingPortMappingsRequest::ListCustomRoutingPortMappingsRequest() : GlobalAcceleratorRequest(new ListCustomRoutingPortMappingsRequestPrivate(GlobalAcceleratorRequest::ListCustomRoutingPortMappingsAction, this)) { } /*! * \reimp */ bool ListCustomRoutingPortMappingsRequest::isValid() const { return false; } /*! * Returns a ListCustomRoutingPortMappingsResponse object to process \a reply. * * \sa QtAws::Core::AwsAbstractClient::send */ QtAws::Core::AwsAbstractResponse * ListCustomRoutingPortMappingsRequest::response(QNetworkReply * const reply) const { return new ListCustomRoutingPortMappingsResponse(*this, reply); } /*! * \class QtAws::GlobalAccelerator::ListCustomRoutingPortMappingsRequestPrivate * \brief The ListCustomRoutingPortMappingsRequestPrivate class provides private implementation for ListCustomRoutingPortMappingsRequest. * \internal * * \inmodule QtAwsGlobalAccelerator */ /*! * Constructs a ListCustomRoutingPortMappingsRequestPrivate object for GlobalAccelerator \a action, * with public implementation \a q. */ ListCustomRoutingPortMappingsRequestPrivate::ListCustomRoutingPortMappingsRequestPrivate( const GlobalAcceleratorRequest::Action action, ListCustomRoutingPortMappingsRequest * const q) : GlobalAcceleratorRequestPrivate(action, q) { } /*! * Constructs a copy of \a other, with public implementation \a q. * * This copy-like constructor exists for the benefit of the ListCustomRoutingPortMappingsRequest * class' copy constructor. */ ListCustomRoutingPortMappingsRequestPrivate::ListCustomRoutingPortMappingsRequestPrivate( const ListCustomRoutingPortMappingsRequestPrivate &other, ListCustomRoutingPortMappingsRequest * const q) : GlobalAcceleratorRequestPrivate(other, q) { } } // namespace GlobalAccelerator } // namespace QtAws
lgpl-3.0
schuttek/nectar
src/main/java/org/nectarframework/base/service/directory/DirStatic.java
148
package org.nectarframework.base.service.directory; public class DirStatic extends DirPath { public String path; public String toPath; }
lgpl-3.0
PocketSoftMine/SoftMine
src/softmine/Block/Obsidian.php
1223
<?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/ * * */ namespace softmine\block; use softmine\item\Item; use softmine\item\Tool; class Obsidian extends Solid{ protected $id = self::OBSIDIAN; public function __construct(){ } public function getName(){ return "Obsidian"; } public function getToolType(){ return Tool::TYPE_PICKAXE; } public function getHardness(){ return 50; } public function getDrops(Item $item){ if($item->isPickaxe() >= Tool::TIER_DIAMOND){ return [ [Item::OBSIDIAN, 0, 1], ]; }else{ return []; } } }
lgpl-3.0
ideaconsult/i5
iuclid_6_4-io/src/main/java/eu/europa/echa/iuclid6/namespaces/flexible_record_jointsubmission/_6/ObjectFactory.java
3096
package eu.europa.echa.iuclid6.namespaces.flexible_record_jointsubmission._6; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the eu.europa.echa.iuclid6.namespaces.flexible_record_jointsubmission._6 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: eu.europa.echa.iuclid6.namespaces.flexible_record_jointsubmission._6 * */ public ObjectFactory() { } /** * Create an instance of {@link FLEXIBLERECORDJointSubmission } * */ public FLEXIBLERECORDJointSubmission createFLEXIBLERECORDJointSubmission() { return new FLEXIBLERECORDJointSubmission(); } /** * Create an instance of {@link FLEXIBLERECORDJointSubmission.GeneralInformation } * */ public FLEXIBLERECORDJointSubmission.GeneralInformation createFLEXIBLERECORDJointSubmissionGeneralInformation() { return new FLEXIBLERECORDJointSubmission.GeneralInformation(); } /** * Create an instance of {@link FLEXIBLERECORDJointSubmission.DataProtection } * */ public FLEXIBLERECORDJointSubmission.DataProtection createFLEXIBLERECORDJointSubmissionDataProtection() { return new FLEXIBLERECORDJointSubmission.DataProtection(); } /** * Create an instance of {@link FLEXIBLERECORDJointSubmission.Lead } * */ public FLEXIBLERECORDJointSubmission.Lead createFLEXIBLERECORDJointSubmissionLead() { return new FLEXIBLERECORDJointSubmission.Lead(); } /** * Create an instance of {@link FLEXIBLERECORDJointSubmission.Members } * */ public FLEXIBLERECORDJointSubmission.Members createFLEXIBLERECORDJointSubmissionMembers() { return new FLEXIBLERECORDJointSubmission.Members(); } /** * Create an instance of {@link FLEXIBLERECORDJointSubmission.GeneralInformation.RegulatoryProgramme } * */ public FLEXIBLERECORDJointSubmission.GeneralInformation.RegulatoryProgramme createFLEXIBLERECORDJointSubmissionGeneralInformationRegulatoryProgramme() { return new FLEXIBLERECORDJointSubmission.GeneralInformation.RegulatoryProgramme(); } /** * Create an instance of {@link FLEXIBLERECORDJointSubmission.DataProtection.Legislation } * */ public FLEXIBLERECORDJointSubmission.DataProtection.Legislation createFLEXIBLERECORDJointSubmissionDataProtectionLegislation() { return new FLEXIBLERECORDJointSubmission.DataProtection.Legislation(); } }
lgpl-3.0
nichbar/Aequorea
richtext/src/main/java/com/zzhoujay/richtext/RichType.java
386
package com.zzhoujay.richtext; import androidx.annotation.IntDef; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by zhou on 16-7-27. * 富文本类型 */ @SuppressWarnings("ALL") @IntDef({RichType.HTML, RichType.MARKDOWN}) @Retention(RetentionPolicy.SOURCE) public @interface RichType { int HTML = 0; int MARKDOWN = 1; }
lgpl-3.0
diegowald/dominioSeguro
dominioSeguro-Importer/csvreader.cpp
1833
#include "csvreader.h" #include <QFile> #include <QTextStream> CSVReader::CSVReader(const QString &filePath, const QString &columnSeparator, int ignoreFirstNLines, const QString &stringDelimiter, QObject *parent) : QObject(parent) { _filePath = filePath; _headers.clear(); _records.clear(); _columnSeparator = columnSeparator; _ignoreFirstNLines = ignoreFirstNLines; _stringDelimiter = stringDelimiter; } void CSVReader::load() { QFile file(_filePath); if (file.open(QIODevice::ReadOnly)) { QTextStream stream(&file); int currentLine = 0; int pos = -1; while (!stream.atEnd()) { QString line = stream.readLine(); if (currentLine > _ignoreFirstNLines) { QStringList row = parse(line); if (pos == -1) { _headers = row; } else { _records[pos] = row; } pos++; } currentLine++; } file.close(); } } QStringList CSVReader::headers() { return _headers; } QStringList CSVReader::record(int index) { if (_records.contains(index)) return _records[index]; else return QStringList(); } QStringList CSVReader::parse(const QString &row) { QStringList res; QStringList partialRes = row.split(_columnSeparator); foreach (QString s, partialRes) { QString r = s; if (r.startsWith(_stringDelimiter)) r = r.remove(0, _stringDelimiter.length()); if (r.endsWith(_stringDelimiter)) r.chop(_stringDelimiter.length()); res.append(r); } return res; } int CSVReader::recordCount() const { return _records.count(); }
lgpl-3.0
xdxdVSxdxd/HumanEcosystems
HE_v2/visualizations/emotions-timeline/js/header.js
9014
var testing = false; var legend; var project; $( document ).ready(function() { initialize(); }); function initialize() { project = getUrlParameter("w"); legend = new Object(); $.getJSON("../../API/getEmotionsLegend.php?w=" + project) .done(function(data){ // insert markers on map var dati = new Array(); dati[0] = new Object(); dati[0].label = "Love"; dati[0].color = "#E4F603"; dati[1] = new Object(); dati[1].label = "Anger"; dati[1].color = "#EB8AF6"; dati[2] = new Object(); dati[2].label = "Disgust"; dati[2].color = "#05F642"; dati[3] = new Object(); dati[3].label = "Boredom"; dati[3].color = "#8908F6"; dati[4] = new Object(); dati[4].label = "Fear"; dati[4].color = "#060CD4"; dati[5] = new Object(); dati[5].label = "Hate"; dati[5].color = "#8C6AD4"; dati[6] = new Object(); dati[6].label = "Joy"; dati[6].color = "#D4AD0B"; dati[7] = new Object(); dati[7].label = "Surprise"; dati[7].color = "#D4460B"; dati[8] = new Object(); dati[8].label = "Trust"; dati[8].color = "#F6000A"; dati[9] = new Object(); dati[9].label = "Sadness"; dati[9].color = "#06D4B5"; dati[10] = new Object(); dati[10].label = "Anticipation"; dati[10].color = "#EB8C00"; dati[11] = new Object(); dati[11].label = "Violence"; dati[11].color = "#6ABFD4"; dati[12] = new Object(); dati[12].label = "Terror"; dati[12].color = "#058BEB"; for(var i = 0 ; i<dati.length ; i++){ legend[ dati[i].label ] = dati[i].color; $("#legend-body").append("<div class='legend-item-holder'><div class='legend-color' style='background: " + dati[i].color + "' ></div><div class='legend-lebel'>" + dati[i].label + "</div></div>"); } // e poi chiamare gli stadi successivi di init getTimelineEmotions(); }) .fail(function( jqxhr, textStatus, error ){ //fare qualcosa in caso di fallimento }); } function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } function getContrastYIQ(hexcolor){ var r = parseInt(hexcolor.substr(1,2),16); var g = parseInt(hexcolor.substr(3,2),16); var b = parseInt(hexcolor.substr(4,2),16); var yiq = ((r*299)+(g*587)+(b*114))/1000; return (yiq >= 128) ? 'black' : 'white'; } function getUrlParameter(sParam) { var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam) { return sParameterName[1]; } } } /* TIMELINE START */ var margin = {top: 20, right: 80, bottom: 30, left: 50}; var width = $("#emo-timeline-contained").width() - margin.left - margin.right, height = $("#emo-timeline-contained").height() - margin.top - margin.bottom; var parseDate = d3.time.format("%Y%m%d").parse; var x = d3.time.scale() .range([0, width]); var y = d3.scale.linear() .range([height, 0]); //var color = d3.scale.category10(); var ll = new Array(); var cc = new Array(); for(var key in legend){ if(legend.hasOwnProperty(key)){ ll.push(key); cc.push(legend[key]); } } var color = d3.scale.ordinal() .domain(ll) .range(cc); var xAxis = d3.svg.axis() .scale(x) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); var line = d3.svg.line() .interpolate("basis") .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.temperature); }); var svg; function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } var arbitraries = new Object(); function getTimelineEmotions(){ width = $("#emo-timeline-contained").width() - margin.left - margin.right; height = $("#emo-timeline-contained").height() - margin.top - margin.bottom; parseDate = d3.time.format("%Y%m%d").parse; x = d3.time.scale() .range([0, width]); y = d3.scale.linear() .range([height, 0]); var ll = new Array(); var cc = new Array(); for(var key in legend){ if(legend.hasOwnProperty(key)){ ll.push(key); cc.push(legend[key]); } } color = d3.scale.ordinal() .domain(ll) .range(cc); xAxis = d3.svg.axis() .scale(x) .orient("bottom"); yAxis = d3.svg.axis() .scale(y) .orient("left"); line = d3.svg.line() .interpolate("basis") .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.temperature); }); svg = d3.select("#emo-timeline-contained").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.tsv("../../API/getEmotionsTimelineGeneral.php?w=" + project, function(error, data) { if (error) throw error; color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; })); data.forEach(function(d) { //console.log(d.date); d.date = parseDate(d.date); }); var cities = color.domain().map(function(name) { return { name: name, values: data.map(function(d) { var rnd = 0; if(testing){ rnd = getRandomArbitrary(0,3); } arbitraries[name + d.date] = rnd; return {date: d.date, temperature: +(d[name]+rnd)}; }) }; }); if(Object.keys( arbitraries ).length>2000){ while(Object.keys( arbitraries ).length>2000){ //console.log("remove"); var props = Object.keys( arbitraries ); delete arbitraries[props[0]]; } } x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([ d3.min(cities, function(c) { return d3.min(c.values, function(v) { return v.temperature; }); }), d3.max(cities, function(c) { return d3.max(c.values, function(v) { return v.temperature; }); }) ]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text(""); var city = svg.selectAll(".city") .data(cities) .enter().append("g") .attr("class", "city"); city.append("path") .attr("class", "line") .attr("d", function(d) { return line(d.values); }) .style("stroke", function(d) { return color(d.name); }) .style("fill", "#FFFFFF"); /* city.append("text") .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; }) .attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")"; }) .attr("x", 3) .attr("dy", ".35em") .text(function(d) { return d.name; }); */ }); } /* TIMELINE END */
lgpl-3.0
Gemorroj/Logio
src/Exception/ParserException.php
655
<?php namespace Logio\Exception; class ParserException extends \Exception { private $errorLogLine; private $pattern; public function getErrorLogLine(): ?string { return $this->errorLogLine; } /** * @return $this */ public function setErrorLogLine(string $errorLogLine): self { $this->errorLogLine = $errorLogLine; return $this; } public function getPattern(): ?string { return $this->pattern; } /** * @return $this */ public function setPattern(string $pattern): self { $this->pattern = $pattern; return $this; } }
lgpl-3.0
SergeR/webasyst-framework
wa-apps/guestbook/lib/models/guestbook.model.php
118
<?php /** * @package wa-apps/guestbook */ class guestbookModel extends waModel { protected $table = 'guestbook'; }
lgpl-3.0
mabe02/lanterna
src/main/java/com/googlecode/lanterna/gui2/LinearLayout.java
22538
/* * This file is part of lanterna (https://github.com/mabe02/lanterna). * * lanterna 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, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2010-2020 Martin Berglund */ package com.googlecode.lanterna.gui2; import com.googlecode.lanterna.TerminalPosition; import com.googlecode.lanterna.TerminalSize; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Simple layout manager the puts all components on a single line, either horizontally or vertically. */ public class LinearLayout implements LayoutManager { /** * This enum type will decide the alignment of a component on the counter-axis, meaning the horizontal alignment on * vertical {@code LinearLayout}s and vertical alignment on horizontal {@code LinearLayout}s. */ public enum Alignment { /** * The component will be placed to the left (for vertical layouts) or top (for horizontal layouts) */ Beginning, /** * The component will be placed horizontally centered (for vertical layouts) or vertically centered (for * horizontal layouts) */ Center, /** * The component will be placed to the right (for vertical layouts) or bottom (for horizontal layouts) */ End, /** * The component will be forced to take up all the horizontal space (for vertical layouts) or vertical space * (for horizontal layouts) */ Fill, } /** * This enum type will what to do with a component if the container has extra space to offer. This can happen if the * window runs in full screen or the window has been programmatically set to a fixed size, above the preferred size * of the window. */ public enum GrowPolicy { /** * This is the default grow policy, the component will not become larger than the preferred size, even if the * container can offer more. */ None, /** * With this grow policy, if the container has more space available then this component will be grown to fill * the extra space. */ CanGrow, } private static class LinearLayoutData implements LayoutData { private final Alignment alignment; private final GrowPolicy growPolicy; public LinearLayoutData(Alignment alignment, GrowPolicy growPolicy) { this.alignment = alignment; this.growPolicy = growPolicy; } } /** * Creates a {@code LayoutData} for {@code LinearLayout} that assigns a component to a particular alignment on its * counter-axis, meaning the horizontal alignment on vertical {@code LinearLayout}s and vertical alignment on * horizontal {@code LinearLayout}s. * @param alignment Alignment to store in the {@code LayoutData} object * @return {@code LayoutData} object created for {@code LinearLayout}s with the specified alignment * @see Alignment */ public static LayoutData createLayoutData(Alignment alignment) { return createLayoutData(alignment, GrowPolicy.None); } /** * Creates a {@code LayoutData} for {@code LinearLayout} that assigns a component to a particular alignment on its * counter-axis, meaning the horizontal alignment on vertical {@code LinearLayout}s and vertical alignment on * horizontal {@code LinearLayout}s. * @param alignment Alignment to store in the {@code LayoutData} object * @param growPolicy When policy to apply to the component if the parent container has more space available along * the main axis. * @return {@code LayoutData} object created for {@code LinearLayout}s with the specified alignment * @see Alignment */ public static LayoutData createLayoutData(Alignment alignment, GrowPolicy growPolicy) { return new LinearLayoutData(alignment, growPolicy); } private final Direction direction; private int spacing; private boolean changed; /** * Default constructor, creates a vertical {@code LinearLayout} */ public LinearLayout() { this(Direction.VERTICAL); } /** * Standard constructor that creates a {@code LinearLayout} with a specified direction to position the components on * @param direction Direction for this {@code Direction} */ public LinearLayout(Direction direction) { this.direction = direction; this.spacing = direction == Direction.HORIZONTAL ? 1 : 0; this.changed = true; } /** * Sets the amount of empty space to put in between components. For horizontal layouts, this is number of columns * (by default 1) and for vertical layouts this is number of rows (by default 0). * @param spacing Spacing between components, either in number of columns or rows depending on the direction * @return Itself */ public LinearLayout setSpacing(int spacing) { this.spacing = spacing; this.changed = true; return this; } /** * Returns the amount of empty space to put in between components. For horizontal layouts, this is number of columns * (by default 1) and for vertical layouts this is number of rows (by default 0). * @return Spacing between components, either in number of columns or rows depending on the direction */ public int getSpacing() { return spacing; } @Override public TerminalSize getPreferredSize(List<Component> components) { // Filter out invisible components components = components.stream().filter(Component::isVisible).collect(Collectors.toList()); if(direction == Direction.VERTICAL) { return getPreferredSizeVertically(components); } else { return getPreferredSizeHorizontally(components); } } private TerminalSize getPreferredSizeVertically(List<Component> components) { int maxWidth = 0; int height = 0; for(Component component: components) { TerminalSize preferredSize = component.getPreferredSize(); if(maxWidth < preferredSize.getColumns()) { maxWidth = preferredSize.getColumns(); } height += preferredSize.getRows(); } height += spacing * (components.size() - 1); return new TerminalSize(maxWidth, Math.max(0, height)); } private TerminalSize getPreferredSizeHorizontally(List<Component> components) { int maxHeight = 0; int width = 0; for(Component component: components) { TerminalSize preferredSize = component.getPreferredSize(); if(maxHeight < preferredSize.getRows()) { maxHeight = preferredSize.getRows(); } width += preferredSize.getColumns(); } width += spacing * (components.size() - 1); return new TerminalSize(Math.max(0,width), maxHeight); } @Override public boolean hasChanged() { return changed; } @Override public void doLayout(TerminalSize area, List<Component> components) { // Filter out invisible components components = components.stream().filter(Component::isVisible).collect(Collectors.toList()); if(direction == Direction.VERTICAL) { if (Boolean.getBoolean("com.googlecode.lanterna.gui2.LinearLayout.useOldNonFlexLayout")) { doVerticalLayout(area, components); } else { doFlexibleVerticalLayout(area, components); } } else { if (Boolean.getBoolean("com.googlecode.lanterna.gui2.LinearLayout.useOldNonFlexLayout")) { doHorizontalLayout(area, components); } else { doFlexibleHorizontalLayout(area, components); } } this.changed = false; } @Deprecated private void doVerticalLayout(TerminalSize area, List<Component> components) { int remainingVerticalSpace = area.getRows(); int availableHorizontalSpace = area.getColumns(); for(Component component: components) { if(remainingVerticalSpace <= 0) { component.setPosition(TerminalPosition.TOP_LEFT_CORNER); component.setSize(TerminalSize.ZERO); } else { Alignment alignment = Alignment.Beginning; LayoutData layoutData = component.getLayoutData(); if (layoutData instanceof LinearLayoutData) { alignment = ((LinearLayoutData)layoutData).alignment; } TerminalSize preferredSize = component.getPreferredSize(); TerminalSize decidedSize = new TerminalSize( Math.min(availableHorizontalSpace, preferredSize.getColumns()), Math.min(remainingVerticalSpace, preferredSize.getRows())); if(alignment == Alignment.Fill) { decidedSize = decidedSize.withColumns(availableHorizontalSpace); alignment = Alignment.Beginning; } TerminalPosition position = component.getPosition(); position = position.withRow(area.getRows() - remainingVerticalSpace); switch(alignment) { case End: position = position.withColumn(availableHorizontalSpace - decidedSize.getColumns()); break; case Center: position = position.withColumn((availableHorizontalSpace - decidedSize.getColumns()) / 2); break; case Beginning: default: position = position.withColumn(0); break; } component.setPosition(position); component.setSize(component.getSize().with(decidedSize)); remainingVerticalSpace -= decidedSize.getRows() + spacing; } } } private void doFlexibleVerticalLayout(TerminalSize area, List<Component> components) { int availableVerticalSpace = area.getRows(); int availableHorizontalSpace = area.getColumns(); List<Component> copyOfComponenets = new ArrayList<>(components); final Map<Component, TerminalSize> fittingMap = new IdentityHashMap<>(); int totalRequiredVerticalSpace = 0; for (Component component: components) { Alignment alignment = Alignment.Beginning; LayoutData layoutData = component.getLayoutData(); if (layoutData instanceof LinearLayoutData) { alignment = ((LinearLayoutData)layoutData).alignment; } TerminalSize preferredSize = component.getPreferredSize(); TerminalSize fittingSize = new TerminalSize( Math.min(availableHorizontalSpace, preferredSize.getColumns()), preferredSize.getRows()); if(alignment == Alignment.Fill) { fittingSize = fittingSize.withColumns(availableHorizontalSpace); } fittingMap.put(component, fittingSize); totalRequiredVerticalSpace += fittingSize.getRows() + spacing; } if (!components.isEmpty()) { // Remove the last spacing totalRequiredVerticalSpace -= spacing; } // If we can't fit everything, trim the down the size of the largest components until it fits if (availableVerticalSpace < totalRequiredVerticalSpace) { copyOfComponenets.sort((o1, o2) -> { // Reverse sort return -Integer.compare(fittingMap.get(o1).getRows(), fittingMap.get(o2).getRows()); }); while (availableVerticalSpace < totalRequiredVerticalSpace) { int largestSize = fittingMap.get(copyOfComponenets.get(0)).getRows(); for (Component largeComponent: copyOfComponenets) { TerminalSize currentSize = fittingMap.get(largeComponent); if (largestSize > currentSize.getRows()) { break; } fittingMap.put(largeComponent, currentSize.withRelativeRows(-1)); totalRequiredVerticalSpace--; } } } // If we have more space available than we need, grow components to fill if (availableVerticalSpace > totalRequiredVerticalSpace) { boolean resizedOneComponent = false; while (availableVerticalSpace > totalRequiredVerticalSpace) { for(Component component: components) { final LinearLayoutData layoutData = (LinearLayoutData)component.getLayoutData(); final TerminalSize currentSize = fittingMap.get(component); if (layoutData != null && layoutData.growPolicy == GrowPolicy.CanGrow) { fittingMap.put(component, currentSize.withRelativeRows(1)); availableVerticalSpace--; resizedOneComponent = true; } if (availableVerticalSpace <= totalRequiredVerticalSpace) { break; } } if (!resizedOneComponent) { break; } } } // Assign the sizes and positions int topPosition = 0; for(Component component: components) { Alignment alignment = Alignment.Beginning; LayoutData layoutData = component.getLayoutData(); if (layoutData instanceof LinearLayoutData) { alignment = ((LinearLayoutData)layoutData).alignment; } TerminalSize decidedSize = fittingMap.get(component); TerminalPosition position = component.getPosition(); position = position.withRow(topPosition); switch(alignment) { case End: position = position.withColumn(availableHorizontalSpace - decidedSize.getColumns()); break; case Center: position = position.withColumn((availableHorizontalSpace - decidedSize.getColumns()) / 2); break; case Beginning: default: position = position.withColumn(0); break; } component.setPosition(component.getPosition().with(position)); component.setSize(component.getSize().with(decidedSize)); topPosition += decidedSize.getRows() + spacing; } } @Deprecated private void doHorizontalLayout(TerminalSize area, List<Component> components) { int remainingHorizontalSpace = area.getColumns(); int availableVerticalSpace = area.getRows(); for(Component component: components) { if(remainingHorizontalSpace <= 0) { component.setPosition(TerminalPosition.TOP_LEFT_CORNER); component.setSize(TerminalSize.ZERO); } else { Alignment alignment = Alignment.Beginning; LayoutData layoutData = component.getLayoutData(); if (layoutData instanceof LinearLayoutData) { alignment = ((LinearLayoutData)layoutData).alignment; } TerminalSize preferredSize = component.getPreferredSize(); TerminalSize decidedSize = new TerminalSize( Math.min(remainingHorizontalSpace, preferredSize.getColumns()), Math.min(availableVerticalSpace, preferredSize.getRows())); if(alignment == Alignment.Fill) { decidedSize = decidedSize.withRows(availableVerticalSpace); alignment = Alignment.Beginning; } TerminalPosition position = component.getPosition(); position = position.withColumn(area.getColumns() - remainingHorizontalSpace); switch(alignment) { case End: position = position.withRow(availableVerticalSpace - decidedSize.getRows()); break; case Center: position = position.withRow((availableVerticalSpace - decidedSize.getRows()) / 2); break; case Beginning: default: position = position.withRow(0); break; } component.setPosition(position); component.setSize(component.getSize().with(decidedSize)); remainingHorizontalSpace -= decidedSize.getColumns() + spacing; } } } private void doFlexibleHorizontalLayout(TerminalSize area, List<Component> components) { int availableVerticalSpace = area.getRows(); int availableHorizontalSpace = area.getColumns(); List<Component> copyOfComponenets = new ArrayList<>(components); final Map<Component, TerminalSize> fittingMap = new IdentityHashMap<>(); int totalRequiredHorizontalSpace = 0; for (Component component: components) { Alignment alignment = Alignment.Beginning; LayoutData layoutData = component.getLayoutData(); if (layoutData instanceof LinearLayoutData) { alignment = ((LinearLayoutData)layoutData).alignment; } TerminalSize preferredSize = component.getPreferredSize(); TerminalSize fittingSize = new TerminalSize( preferredSize.getColumns(), Math.min(availableVerticalSpace, preferredSize.getRows())); if(alignment == Alignment.Fill) { fittingSize = fittingSize.withRows(availableVerticalSpace); } fittingMap.put(component, fittingSize); totalRequiredHorizontalSpace += fittingSize.getColumns() + spacing; } if (!components.isEmpty()) { // Remove the last spacing totalRequiredHorizontalSpace -= spacing; } // If we can't fit everything, trim the down the size of the largest components until it fits if (availableHorizontalSpace < totalRequiredHorizontalSpace) { copyOfComponenets.sort((o1, o2) -> { // Reverse sort return -Integer.compare(fittingMap.get(o1).getColumns(), fittingMap.get(o2).getColumns()); }); while (availableHorizontalSpace < totalRequiredHorizontalSpace) { int largestSize = fittingMap.get(copyOfComponenets.get(0)).getColumns(); for (Component largeComponent: copyOfComponenets) { TerminalSize currentSize = fittingMap.get(largeComponent); if (largestSize > currentSize.getColumns()) { break; } fittingMap.put(largeComponent, currentSize.withRelativeColumns(-1)); totalRequiredHorizontalSpace--; } } } // If we have more space available than we need, grow components to fill if (availableHorizontalSpace > totalRequiredHorizontalSpace) { boolean resizedOneComponent = false; while (availableHorizontalSpace > totalRequiredHorizontalSpace) { for(Component component: components) { final LinearLayoutData layoutData = (LinearLayoutData)component.getLayoutData(); final TerminalSize currentSize = fittingMap.get(component); if (layoutData != null && layoutData.growPolicy == GrowPolicy.CanGrow) { fittingMap.put(component, currentSize.withRelativeColumns(1)); availableHorizontalSpace--; resizedOneComponent = true; } if (availableHorizontalSpace <= totalRequiredHorizontalSpace) { break; } } if (!resizedOneComponent) { break; } } } // Assign the sizes and positions int leftPosition = 0; for(Component component: components) { Alignment alignment = Alignment.Beginning; LayoutData layoutData = component.getLayoutData(); if (layoutData instanceof LinearLayoutData) { alignment = ((LinearLayoutData)layoutData).alignment; } TerminalSize decidedSize = fittingMap.get(component); TerminalPosition position = component.getPosition(); position = position.withColumn(leftPosition); switch(alignment) { case End: position = position.withRow(availableVerticalSpace - decidedSize.getRows()); break; case Center: position = position.withRow((availableVerticalSpace - decidedSize.getRows()) / 2); break; case Beginning: default: position = position.withRow(0); break; } component.setPosition(component.getPosition().with(position)); component.setSize(component.getSize().with(decidedSize)); leftPosition += decidedSize.getColumns() + spacing; } } }
lgpl-3.0
IMSGlobal/caliper-ruby-public
spec/lib/events/annotation_highlighted_event_spec.rb
3254
## # This file is part of IMS Caliper Analytics™ and is licensed to # IMS Global Learning Consortium, Inc. (http://www.imsglobal.org) # under one or more contributor license agreements. See the NOTICE # file distributed with this work for additional information. # # IMS Caliper is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, version 3 of the License. # # IMS Caliper 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/. require 'spec_helper' describe Caliper::Events::AnnotationEvent do subject do described_class.new( actor: actor, action: Caliper::Actions::HIGHLIGHTED, edApp: ed_app, eventTime: '2016-11-15T10:15:00.000Z', generated: highlight, group: group, id: 'urn:uuid:0067a052-9bb4-4b49-9d1a-87cd43da488a', membership: membership, object: object, session: session ) end let(:actor) do Caliper::Entities::Agent::Person.new( id: 'https://example.edu/users/554433', ) end let(:ed_app) do Caliper::Entities::Agent::SoftwareApplication.new( id: 'https://example.com/reader', name: 'ePub Reader', version: '1.2.3' ) end let(:group) do Caliper::Entities::LIS::CourseSection.new( id: 'https://example.edu/terms/201601/courses/7/sections/1', courseNumber: 'CPS 435-01', academicSession: 'Fall 2016' ) end let(:highlight) do Caliper::Entities::Annotation::HighlightAnnotation.new( id: 'https://example.com/users/554433/texts/imscaliperimplguide/highlights?start=2300&end=2370', annotator: actor, annotated: object, selection: Caliper::Entities::Annotation::TextPositionSelector.new( start: 2300, end: 2370 ), selectionText: 'ISO 8601 formatted date and time expressed with millisecond precision.', dateCreated: '2016-11-15T10:15:00.000Z' ) end let(:membership) do Caliper::Entities::LIS::Membership.new( id: 'https://example.edu/terms/201601/courses/7/sections/1/rosters/1', member: actor, organization: group, roles: [ Caliper::Entities::LIS::Role::LEARNER ], status: Caliper::Entities::LIS::Status::ACTIVE, dateCreated: '2016-08-01T06:00:00.000Z' ) end let(:object) do Caliper::Entities::Reading::Document.new( id: 'https://example.com/#/texts/imscaliperimplguide', name: 'IMS Caliper Implementation Guide', dateCreated: '2016-10-01T06:00:00.000Z', version: '1.1' ) end let(:session) do Caliper::Entities::Session::Session.new( id: 'https://example.com/sessions/1f6442a482de72ea6ad134943812bff564a76259', startedAtTime: '2016-11-15T10:00:00.000Z' ) end include_examples 'validation against common fixture', 'caliperEventAnnotationHighlighted.json' end
lgpl-3.0
pgrabowski/jsleeannotations
jsleeannotations-types/src/main/java/jsleeannotations/slee/ChildRelationMethod.java
1070
/* * JSLEE Annotations * Copyright (c) 2015 Piotr Grabowski, All rights reserved. * * 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 3.0 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. */ package jsleeannotations.slee; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ChildRelationMethod { String sbbAliasRef(); int defaultPriority(); }
lgpl-3.0
trinityfx/trinity
cmd/puppeth/wizard_nginx.go
2385
// Copyright 2017 The go-ethereum Authors // This file is part of go-ethereum. // // go-ethereum 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. // // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>. package main import ( "fmt" "github.com/akroma-project/akroma/log" ) // ensureVirtualHost checks whether a reverse-proxy is running on the specified // host machine, and if yes requests a virtual host from the user to host a // specific web service on. If no proxy exists, the method will offer to deploy // one. // // If the user elects not to use a reverse proxy, an empty hostname is returned! func (w *wizard) ensureVirtualHost(client *sshClient, port int, def string) (string, error) { proxy, _ := checkNginx(client, w.network) if proxy != nil { // Reverse proxy is running, if ports match, we need a virtual host if proxy.port == port { fmt.Println() fmt.Printf("Shared port, which domain to assign? (default = %s)\n", def) return w.readDefaultString(def), nil } } // Reverse proxy is not running, offer to deploy a new one fmt.Println() fmt.Println("Allow sharing the port with other services (y/n)? (default = yes)") if w.readDefaultYesNo(true) { nocache := false if proxy != nil { fmt.Println() fmt.Printf("Should the reverse-proxy be rebuilt from scratch (y/n)? (default = no)\n") nocache = w.readDefaultYesNo(false) } if out, err := deployNginx(client, w.network, port, nocache); err != nil { log.Error("Failed to deploy reverse-proxy", "err", err) if len(out) > 0 { fmt.Printf("%s\n", out) } return "", err } // Reverse proxy deployed, ask again for the virtual-host fmt.Println() fmt.Printf("Proxy deployed, which domain to assign? (default = %s)\n", def) return w.readDefaultString(def), nil } // Reverse proxy not requested, deploy as a standalone service return "", nil }
lgpl-3.0
jlpoolen/libreveris
src/main/omr/log/LogGuiAppender.java
2439
//----------------------------------------------------------------------------// // // // L o g G u i A p p e n d e r // // // //----------------------------------------------------------------------------// // <editor-fold defaultstate="collapsed" desc="hdr"> // // Copyright © Hervé Bitteur and others 2000-2013. All rights reserved. // // This software is released under the GNU General Public License. // // Goto http://kenai.com/projects/audiveris to report bugs or suggestions. // //----------------------------------------------------------------------------// // </editor-fold> package omr.log; import omr.Main; import omr.ui.MainGui; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.AppenderBase; import java.util.concurrent.ArrayBlockingQueue; /** * Class {@code LogGuiAppender} is a log appender that appends the * logging messages to the GUI. * It uses an intermediate queue to cope with initial conditions when the GUI * is not yet ready to accept messages. * * @author Hervé Bitteur */ public class LogGuiAppender extends AppenderBase<ILoggingEvent> { //~ Static fields/initializers --------------------------------------------- /** * Size of the mail box. * (This cannot be an application Constant, for elaboration dependencies) */ private static final int LOG_MBX_SIZE = 10000; /** Temporary mail box for logged messages. */ private static ArrayBlockingQueue<ILoggingEvent> logMbx = new ArrayBlockingQueue<ILoggingEvent>( LOG_MBX_SIZE); //~ Methods ---------------------------------------------------------------- //---------------// // getEventCount // //---------------// public static int getEventCount () { return logMbx.size(); } //-----------// // pollEvent // //-----------// public static ILoggingEvent pollEvent () { return logMbx.poll(); } //--------// // append // //--------// @Override protected void append (ILoggingEvent event) { logMbx.offer(event); MainGui gui = Main.getGui(); if (gui != null) { gui.notifyLog(); } } }
lgpl-3.0
idryanov/2schematic
src/pcd2schematic.cpp
1669
/** * @file pcd2schematic.cpp * @author Ivan Dryanovski <ivan.dryanovski@gmail.com> * * @section LICENSE * * Copyright (C) 2013, Ivan Dryanovski * * 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/>. */ #include "pcd2schematic.h" using namespace std; using namespace rgbd_2_schematic; int main(int argc, char** argv) { // get parameters if (argc != 6) { cout << "ERROR: Usage is " << argv[0]; cout << " input.pcd output.schematic resolution filter_window mode" << endl; return -1; } const string input_path = argv[1]; const string output_path = argv[2]; double resolution = atof(argv[3]); int window = atoi(argv[4]); int mode = atoi(argv[5]); // convert octree Schematic schematic; PcdConverter converter; converter.setResolution(resolution); converter.setMaterialMode(mode); converter.setColorFilterWindow(window); converter.load(input_path); converter.convert(schematic); // write out Writer writer(output_path); writer.write(schematic); cout << "Done." << endl; return 0; }
lgpl-3.0
trillek-team/trillek-server-core
src/os.cpp
8249
#if defined(_MSC_VER) #include "os.hpp" #include <iostream> #include "trillek-game.hpp" #include "systems/dispatcher.hpp" #ifdef __APPLE__ // Needed so we can disable retina support for our window. #define GLFW_EXPOSE_NATIVE_COCOA 1 #define GLFW_EXPOSE_NATIVE_NSGL 1 #include <GLFW/glfw3native.h> // We can't just include objc/runtime.h and objc/message.h because glfw is too forward thinking for its own good. typedef void* SEL; extern "C" id objc_msgSend(id self, SEL op, ...); extern "C" SEL sel_getUid(const char *str); #endif namespace trillek { // Error helper function used by GLFW for error messaging. // Currently outputs to std::cout. static void ErrorCallback(int error, const char* description) { std::cout << description << std::endl; } bool OS::InitializeWindow(const int width, const int height, const std::string title, const unsigned int glMajor /*= 3*/, const unsigned int glMinor /*= 2*/) { glfwSetErrorCallback(ErrorCallback); // Initialize the library. if (glfwInit() != GL_TRUE) { return false; } glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, glMajor); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, glMinor); #if __APPLE__ glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #else glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_ANY_PROFILE); #endif // Create a windowed mode window and its OpenGL context. this->window = glfwCreateWindow(width, height, title.c_str(), NULL, NULL); if (!this->window) { glfwTerminate(); return false; } this->client_width = width; this->client_height = height; #ifdef __APPLE__ // Force retina displays to create a 1x framebuffer so we don't choke our fillrate. id cocoaWindow = glfwGetCocoaWindow(this->window); id cocoaGLView = ((id (*)(id, SEL)) objc_msgSend)(cocoaWindow, sel_getUid("contentView")); ((void (*)(id, SEL, bool)) objc_msgSend)(cocoaGLView, sel_getUid("setWantsBestResolutionOpenGLSurface:"), false); #endif // attach the context glfwMakeContextCurrent(this->window); #ifndef __APPLE__ // setting glewExperimental fixes a glfw context problem // (tested on Ubuntu 13.04) glewExperimental = GL_TRUE; // Init GLEW. GLuint error = glewInit(); if (error != GLEW_OK) { return false; } #endif // Associate a pointer for this instance with this window. glfwSetWindowUserPointer(this->window, this); // Set up some callbacks. glfwSetWindowSizeCallback(this->window, &OS::windowResized); glfwSetKeyCallback(this->window, &OS::keyboardEvent); glfwSetCursorPosCallback(this->window, &OS::mouseMoveEvent); glfwSetCharCallback(this->window, &OS::characterEvent); glfwSetMouseButtonCallback(this->window, &OS::mouseButtonEvent); glfwSetWindowFocusCallback(this->window, &OS::windowFocusChange); glfwGetCursorPos(this->window, &this->old_mouse_x, &this->old_mouse_y); return true; } void OS::MakeCurrent() { glfwMakeContextCurrent(this->window); } void OS::DetachContext() { glfwMakeContextCurrent(NULL); } void OS::Terminate() { glfwTerminate(); } void OS::SetWindowShouldClose() { glfwSetWindowShouldClose(this->window, GL_TRUE); } bool OS::Closing() { return glfwWindowShouldClose(this->window) > 0; } void OS::SwapBuffers() { glfwSwapBuffers(this->window); } void OS::OSMessageLoop() { glfwWaitEvents(); } int OS::GetWindowWidth() { return this->client_width; } int OS::GetWindowHeight() { return this->client_height; } std::chrono::nanoseconds OS::GetTime() { return std::chrono::nanoseconds(static_cast<int64_t>(glfwGetTime() * 1.0E9)); } void OS::windowResized(GLFWwindow* window, int width, int height) { // Get the user pointer and cast it. OS* os = static_cast<OS*>(glfwGetWindowUserPointer(window)); if (os) { os->UpdateWindowSize(width, height); } } void OS::keyboardEvent(GLFWwindow* window, int key, int scancode, int action, int mods) { // Get the user pointer and cast it. OS* os = static_cast<OS*>(glfwGetWindowUserPointer(window)); if (os) { os->DispatchKeyboardEvent(key, scancode, action, mods); } } void OS::characterEvent(GLFWwindow* window, unsigned int uchar) { // Get the user pointer and cast it. OS* os = static_cast<OS*>(glfwGetWindowUserPointer(window)); if (os) { os->DispatchCharacterEvent(uchar); } } void OS::mouseMoveEvent(GLFWwindow* window, double x, double y) { // Get the user pointer and cast it. OS* os = static_cast<OS*>(glfwGetWindowUserPointer(window)); if (os) { os->DispatchMouseMoveEvent(x, y); } } void OS::mouseButtonEvent(GLFWwindow* window, int button, int action, int mods) { // Get the user pointer and cast it. OS* os = static_cast<OS*>(glfwGetWindowUserPointer(window)); if (os) { os->DispatchMouseButtonEvent(button, action, mods); } } void OS::windowFocusChange(GLFWwindow* window, int focused) { if (focused == GL_FALSE) { // Get the user pointer and cast it. OS* os = static_cast<OS*>(glfwGetWindowUserPointer(window)); if (os) { // TODO: Implement a DispatchWindowFocusEvent() method in OS // TODO: Dispatch a focus changed event. } } } void OS::UpdateWindowSize(const int width, const int height) { this->client_width = width; this->client_height = height; } void OS::DispatchKeyboardEvent(const int key, const int scancode, const int action, const int mods) { KeyboardEvent key_event; if (action == GLFW_PRESS) { key_event = { key, scancode, KeyboardEvent::KEY_DOWN, mods }; } else if (action == GLFW_REPEAT) { key_event = { key, scancode, KeyboardEvent::KEY_REPEAT, mods }; } else if (action == GLFW_RELEASE) { key_event = { key, scancode, KeyboardEvent::KEY_UP, mods }; } event::Dispatcher<KeyboardEvent>::GetInstance()->NotifySubscribers(&key_event); } void OS::DispatchCharacterEvent(const unsigned int uchar) { KeyboardEvent key_event { (const int)uchar, 0, KeyboardEvent::KEY_CHAR, 0 }; event::Dispatcher<KeyboardEvent>::GetInstance()->NotifySubscribers(&key_event); } void OS::DispatchMouseMoveEvent(const double x, const double y) { MouseMoveEvent mmov_event = { static_cast<double>(x) / this->client_width, static_cast<double>(y) / this->client_height, static_cast<int>(this->old_mouse_x), static_cast<int>(this->old_mouse_y), static_cast<int>(x), static_cast<int>(y) }; event::Dispatcher<MouseMoveEvent>::GetInstance()->NotifySubscribers(&mmov_event); // If we are in mouse lock we will snap the mouse to the middle of the screen. if (this->mouse_lock) { this->old_mouse_x = this->client_width / 2; this->old_mouse_y = this->client_height / 2; glfwSetCursorPos(this->window, this->old_mouse_x, this->old_mouse_y); } else { this->old_mouse_x = x; this->old_mouse_y = y; } } void OS::DispatchMouseButtonEvent(const int button, const int action, const int mods) { MouseBtnEvent mbtn_event; if (action == GLFW_PRESS) { mbtn_event.action = MouseBtnEvent::DOWN; } else { mbtn_event.action = MouseBtnEvent::UP; } if (button == GLFW_MOUSE_BUTTON_LEFT) { mbtn_event.button = MouseBtnEvent::LEFT; } else if (button == GLFW_MOUSE_BUTTON_RIGHT) { mbtn_event.button = MouseBtnEvent::RIGHT; } else if (button == GLFW_MOUSE_BUTTON_MIDDLE) { mbtn_event.button = MouseBtnEvent::MIDDLE; } event::Dispatcher<MouseBtnEvent>::GetInstance()->NotifySubscribers(&mbtn_event); } void OS::ToggleMouseLock() { this->mouse_lock = !this->mouse_lock; if (this->mouse_lock) { glfwSetInputMode(this->window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } else { glfwSetInputMode(this->window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } } void OS::SetMousePosition(double x, double y) { glfwSetCursorPos(this->window, x, y); } } // End of trillek #endif //MSC_VER
lgpl-3.0
Semantive/jts
src/main/java/com/vividsolutions/jts/geom/LineString.java
10257
/* * The JTS Topology Suite is a collection of Java classes that * implement the fundamental operations required to validate a given * geo-spatial data set to a known topological specification. * * Copyright (C) 2001 Vivid Solutions * * 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 * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ package com.vividsolutions.jts.geom; import com.vividsolutions.jts.algorithm.CGAlgorithms; import com.vividsolutions.jts.operation.BoundaryOp; /** * Models an OGC-style <code>LineString</code>. * A LineString consists of a sequence of two or more vertices, * along with all points along the linearly-interpolated curves * (line segments) between each * pair of consecutive vertices. * Consecutive vertices may be equal. * The line segments in the line may intersect each other (in other words, * the linestring may "curl back" in itself and self-intersect. * Linestrings with exactly two identical points are invalid. * <p/> * A linestring must have either 0 or 2 or more points. * If these conditions are not met, the constructors throw * an {@link IllegalArgumentException} * * @version 1.7 */ public class LineString extends Geometry implements Lineal { private static final long serialVersionUID = 3110669828065365560L; /** * The points of this <code>LineString</code>. */ protected CoordinateSequence points; /** * Constructs a <code>LineString</code> with the given points. * *@param points the points of the linestring, or <code>null</code> * to create the empty geometry. This array must not contain <code>null</code> * elements. Consecutive points may be equal. *@param precisionModel the specification of the grid of allowable points * for this <code>LineString</code> *@param SRID the ID of the Spatial Reference System used by this * <code>LineString</code> * @throws IllegalArgumentException if too few points are provided */ /** * @deprecated Use GeometryFactory instead */ public LineString(Coordinate points[], PrecisionModel precisionModel, int SRID) { super(new GeometryFactory(precisionModel, SRID)); init(getFactory().getCoordinateSequenceFactory().create(points)); } /** * Constructs a <code>LineString</code> with the given points. * * @param points the points of the linestring, or <code>null</code> * to create the empty geometry. * @throws IllegalArgumentException if too few points are provided */ public LineString(CoordinateSequence points, GeometryFactory factory) { super(factory); init(points); } private void init(CoordinateSequence points) { if (points == null) { points = getFactory().getCoordinateSequenceFactory().create(new Coordinate[]{}); } if (points.size() == 1) { throw new IllegalArgumentException("Invalid number of points in LineString (found " + points.size() + " - must be 0 or >= 2)"); } this.points = points; } public Coordinate[] getCoordinates() { return points.toCoordinateArray(); } public CoordinateSequence getCoordinateSequence() { return points; } public Coordinate getCoordinateN(int n) { return points.getCoordinate(n); } public Coordinate getCoordinate() { if (isEmpty()) return null; return points.getCoordinate(0); } public int getDimension() { return 1; } public int getBoundaryDimension() { if (isClosed()) { return Dimension.FALSE; } return 0; } public boolean isEmpty() { return points.size() == 0; } public int getNumPoints() { return points.size(); } public Point getPointN(int n) { return getFactory().createPoint(points.getCoordinate(n)); } public Point getStartPoint() { if (isEmpty()) { return null; } return getPointN(0); } public Point getEndPoint() { if (isEmpty()) { return null; } return getPointN(getNumPoints() - 1); } public boolean isClosed() { if (isEmpty()) { return false; } return getCoordinateN(0).equals2D(getCoordinateN(getNumPoints() - 1)); } public boolean isRing() { return isClosed() && isSimple(); } public String getGeometryType() { return "LineString"; } /** * Returns the length of this <code>LineString</code> * * @return the length of the linestring */ public double getLength() { return CGAlgorithms.length(points); } /** * Gets the boundary of this geometry. * The boundary of a lineal geometry is always a zero-dimensional geometry (which may be empty). * * @return the boundary geometry * @see Geometry#getBoundary */ public Geometry getBoundary() { return (new BoundaryOp(this)).getBoundary(); } /** * Creates a {@link LineString} whose coordinates are in the reverse * order of this objects * * @return a {@link LineString} with coordinates in the reverse order */ public Geometry reverse() { CoordinateSequence seq = (CoordinateSequence) points.clone(); CoordinateSequences.reverse(seq); LineString revLine = getFactory().createLineString(seq); return revLine; } /** * Returns true if the given point is a vertex of this <code>LineString</code>. * * @param pt the <code>Coordinate</code> to check * @return <code>true</code> if <code>pt</code> is one of this <code>LineString</code> * 's vertices */ public boolean isCoordinate(Coordinate pt) { for (int i = 0; i < points.size(); i++) { if (points.getCoordinate(i).equals(pt)) { return true; } } return false; } protected Envelope computeEnvelopeInternal() { if (isEmpty()) { return new Envelope(); } return points.expandEnvelope(new Envelope()); } public boolean equalsExact(Geometry other, double tolerance) { if (!isEquivalentClass(other)) { return false; } LineString otherLineString = (LineString) other; if (points.size() != otherLineString.points.size()) { return false; } for (int i = 0; i < points.size(); i++) { if (!equal(points.getCoordinate(i), otherLineString.points.getCoordinate(i), tolerance)) { return false; } } return true; } public void apply(CoordinateFilter filter) { for (int i = 0; i < points.size(); i++) { filter.filter(points.getCoordinate(i)); } } public void apply(CoordinateSequenceFilter filter) { if (points.size() == 0) return; for (int i = 0; i < points.size(); i++) { filter.filter(points, i); if (filter.isDone()) break; } if (filter.isGeometryChanged()) geometryChanged(); } public void apply(GeometryFilter filter) { filter.filter(this); } public void apply(GeometryComponentFilter filter) { filter.filter(this); } /** * Creates and returns a full copy of this {@link LineString} object. * (including all coordinates contained by it). * * @return a clone of this instance */ public Object clone() { LineString ls = (LineString) super.clone(); ls.points = (CoordinateSequence) points.clone(); return ls; } /** * Normalizes a LineString. A normalized linestring * has the first point which is not equal to it's reflected point * less than the reflected point. */ public void normalize() { for (int i = 0; i < points.size() / 2; i++) { int j = points.size() - 1 - i; // skip equal points on both ends if (!points.getCoordinate(i).equals(points.getCoordinate(j))) { if (points.getCoordinate(i).compareTo(points.getCoordinate(j)) > 0) { CoordinateArrays.reverse(getCoordinates()); } return; } } } protected boolean isEquivalentClass(Geometry other) { return other instanceof LineString; } protected int compareToSameClass(Object o) { LineString line = (LineString) o; // MD - optimized implementation int i = 0; int j = 0; while (i < points.size() && j < line.points.size()) { int comparison = points.getCoordinate(i).compareTo(line.points.getCoordinate(j)); if (comparison != 0) { return comparison; } i++; j++; } if (i < points.size()) { return 1; } if (j < line.points.size()) { return -1; } return 0; } protected int compareToSameClass(Object o, CoordinateSequenceComparator comp) { LineString line = (LineString) o; return comp.compare(this.points, line.points); } }
lgpl-3.0
osbitools/OsBiToolsWs
OsBiWsPrjShared/src/main/java/com/osbitools/ws/shared/prj/web/LangSetWsSrvServlet.java
3630
/* * Open Source Business Intelligence Tools - http://www.osbitools.com/ * * Copyright 2014-2016 IvaLab Inc. and by respective contributors (see below). * * Released under the LGPL v3 or higher * See http://www.gnu.org/licenses/lgpl-3.0.html * * Date: 2015-08-08 * * Contributors: * * Igor Peonte <igor.144@gmail.com> * */ package com.osbitools.ws.shared.prj.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.osbitools.ws.shared.WsSrvException; import com.osbitools.ws.shared.prj.PrjMgrConstants; import com.osbitools.ws.shared.prj.utils.LangSetUtils; /** * * LangLabels File Manager. Implements next CRUD spec * * doGet - Read Project ll_set * doPut - Save and automatically commit new file * * @author "Igor Peonte <igor.144@gmail.com>" * */ @WebServlet("/rest/ll_set") public class LangSetWsSrvServlet extends GenericPrjMgrWsSrvServlet { // Default serial version uid private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { super.doGet(req, resp); } catch (ServletException e) { if (e.getCause().getClass().equals(WsSrvException.class)) { // Authentication failed checkSendError(req, resp, (WsSrvException) e.getCause()); return; } else { throw e; } } String name = req.getParameter(PrjMgrConstants.REQ_NAME_PARAM); LangSetUtils lu = (LangSetUtils) req.getSession(). getServletContext().getAttribute("ll_set_utils"); // Read project based lang file try { printJson(resp, lu.read( getPrjRootDir(req), name, isMinfied(req))); } catch (WsSrvException e) { checkSendError(req, resp, e); } } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { super.doPut(req, resp); } catch (ServletException e) { if (e.getCause().getClass().equals(WsSrvException.class)) { // Authentication failed checkSendError(req, resp, (WsSrvException) e.getCause()); return; } else { throw e; } } String comment = req.getParameter("comment") != null ? req.getParameter("comment") : ""; String name = req.getParameter(PrjMgrConstants.REQ_NAME_PARAM); LangSetUtils lu = (LangSetUtils) req.getSession(). getServletContext().getAttribute("ll_set_utils"); try { printJson(resp, lu.save(getPrjRootDir(req), name, req.getInputStream(), comment, getLoginUser(req), getGit(req), isMinfied(req))); } catch (WsSrvException e) { checkSendError(req, resp, e); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { sendNotImplemented(req, resp); } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { sendNotImplemented(req, resp); } @Override protected String[] getMandatoryParameters() { return new String[] {PrjMgrConstants.REQ_NAME_PARAM}; } }
lgpl-3.0
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/db/entities/ChineseCityEntity.java
2074
package wangdaye.com.geometricweather.db.entities; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Generated; import wangdaye.com.geometricweather.common.basic.models.ChineseCity; /** * Chinese city entity. * * {@link ChineseCity}. * */ @Entity public class ChineseCityEntity { @Id public Long id; public String cityId; public String province; public String city; public String district; public String latitude; public String longitude; @Generated(hash = 787683596) public ChineseCityEntity(Long id, String cityId, String province, String city, String district, String latitude, String longitude) { this.id = id; this.cityId = cityId; this.province = province; this.city = city; this.district = district; this.latitude = latitude; this.longitude = longitude; } @Generated(hash = 1803922116) public ChineseCityEntity() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getCityId() { return this.cityId; } public void setCityId(String cityId) { this.cityId = cityId; } public String getProvince() { return this.province; } public void setProvince(String province) { this.province = province; } public String getCity() { return this.city; } public void setCity(String city) { this.city = city; } public String getDistrict() { return this.district; } public void setDistrict(String district) { this.district = district; } public String getLatitude() { return this.latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return this.longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } }
lgpl-3.0
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/settings/dialogs/RunningInBackgroundODialog.java
2231
package wangdaye.com.geometricweather.settings.dialogs; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import wangdaye.com.geometricweather.R; import wangdaye.com.geometricweather.common.basic.GeoDialog; import wangdaye.com.geometricweather.common.utils.helpers.IntentHelper; /** * Running in background O dialog. * */ @RequiresApi(api = Build.VERSION_CODES.O) public class RunningInBackgroundODialog extends GeoDialog implements View.OnClickListener { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = LayoutInflater.from(getActivity()).inflate( R.layout.dialog_running_in_background_o, container, false); initWidget(view); return view; } private void initWidget(View view) { view.findViewById(R.id.dialog_running_in_background_o_setNotificationGroupBtn).setOnClickListener(this); view.findViewById(R.id.dialog_running_in_background_o_ignoreBatteryOptBtn).setOnClickListener(this); } @SuppressLint("NonConstantResourceId") @Override public void onClick(View v) { switch (v.getId()) { case R.id.dialog_running_in_background_o_setNotificationGroupBtn: Intent intent = new Intent(); intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS); intent.putExtra(Settings.EXTRA_APP_PACKAGE, requireActivity().getPackageName()); requireActivity().startActivity(intent); break; case R.id.dialog_running_in_background_o_ignoreBatteryOptBtn: IntentHelper.startBatteryOptimizationActivity(requireContext()); break; } } }
lgpl-3.0
modelinglab/ocl
ext/complex-types/src/main/java/org/modelinglab/ocl/ext/complextypes/operations/string/StringEndsWith.java
1610
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.modelinglab.ocl.ext.complextypes.operations.string; import org.modelinglab.ocl.core.ast.Operation; import org.modelinglab.ocl.core.ast.Parameter; import org.modelinglab.ocl.core.ast.types.Classifier; import org.modelinglab.ocl.core.ast.types.PrimitiveType; import org.modelinglab.ocl.core.ast.types.TemplateRestrictions; /** * * @author Gonzalo Ortiz Jaureguizar */ public class StringEndsWith extends Operation { private static final long serialVersionUID = 1L; private static final StringEndsWith INSTANCE = new StringEndsWith(); StringEndsWith() { super(null); Parameter subString = new Parameter(); subString.setName("substring"); subString.setType(PrimitiveType.getInstance(PrimitiveType.PrimitiveKind.STRING)); addOwnedParameter(subString); setName("endsWith"); setType(PrimitiveType.getInstance(PrimitiveType.PrimitiveKind.BOOLEAN)); setSource(PrimitiveType.getInstance(PrimitiveType.PrimitiveKind.STRING)); } @Override public Operation specificOperation(Classifier sourceType, java.util.List<Classifier> argTypes, TemplateRestrictions restrictions) { return this; } public static StringEndsWith getInstance() { return INSTANCE; } // This method is called immediately after an object of this class is deserialized. // This method returns the singleton instance. protected Object readResolve() { return getInstance(); } }
lgpl-3.0
Defernus/incantations-mod
src/main/java/ru/def/incantations/tileentity/TileEntityRegister.java
1233
package ru.def.incantations.tileentity; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import ru.def.incantations.tileentity.render.RenderBookMonument; import ru.def.incantations.tileentity.render.RenderSkyChargingTable; import ru.def.incantations.tileentity.render.RenderWritingTable; /** * Created by Defernus on 12.05.2017. */ public class TileEntityRegister { public static void register(){ GameRegistry.registerTileEntity(TileEntityBookMonument.class,"tile_book_monument"); GameRegistry.registerTileEntity(TileEntityWritingTable.class,"tile_writing_table"); GameRegistry.registerTileEntity(TileEntitySkyChargingTable.class, "tile_sky_charging_table"); } @SideOnly(Side.CLIENT) public static void registerClient(){ ClientRegistry.bindTileEntitySpecialRenderer(TileEntityBookMonument.class, new RenderBookMonument()); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityWritingTable.class, new RenderWritingTable()); ClientRegistry.bindTileEntitySpecialRenderer(TileEntitySkyChargingTable.class, new RenderSkyChargingTable()); } }
lgpl-3.0
jimevins/glbarcode
test/test-svg-renderer.cpp
1224
/* test-svg-renderer.cpp * * Copyright (C) 2013 Jim Evins <evins@snaught.com> * * This file is part of glbarcode++. * * glbarcode++ 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. * * glbarcode++ 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 glbarcode++. If not, see <http://www.gnu.org/licenses/>. */ #include "glbarcode/Factory.h" #include "glbarcode/RendererSvg.h" #include <iostream> #include <string> int main( int argc, char **argv ) { glbarcode::RendererSvg renderer; if ( argc != 2 ) { std::cerr << "Usage: " << argv[0] << "data"; } glbarcode::Factory::init(); glbarcode::Barcode* bc = glbarcode::Factory::createBarcode( "code39" ); bc->build( argv[1] ); bc->render( renderer ); delete bc; }
lgpl-3.0
vfulco/Flask-Analytics
flask_analytics/providers/chartbeat.py
1302
from flask_analytics.providers.base import BaseProvider class Chartbeat(BaseProvider): uid = None domain = None def __init__(self, uid=None, domain=None): self.uid = uid self.domain = domain @property def template(self): return """<script type="text/javascript"> var _sf_async_config={{}}; /** CONFIGURATION START **/ _sf_async_config.uid = {uid}; /** CHANGE THIS **/ _sf_async_config.domain = "{domain}"; /** CHANGE THIS **/ /** CONFIGURATION END **/ (function(){{ function loadChartbeat() {{ window._sf_endpt=(new Date()).getTime(); var e = document.createElement("script"); e.setAttribute("language", "javascript"); e.setAttribute("type", "text/javascript"); e.setAttribute('src', '//static.chartbeat.com/js/chartbeat.js'); document.body.appendChild(e); }} var oldonload = window.onload; window.onload = (typeof window.onload != "function") ? loadChartbeat : function() {{ oldonload(); loadChartbeat(); }}; }})(); </script>""" @property def source(self): if self.uid is None or self.domain is None: return None return self.template.format(uid=self.uid, domain=self.domain)
unlicense
jvazquez/organization
organization/job_offers/validation.py
3572
''' Created on Jun 14, 2014 @author: jvazquez ''' import json import functools from flask import current_app, request, Response from organization.common.constants import ERROR, NOT_FOUND, JSON_HEADER, MSG def expectations(expected_keys=None, constraint_check=None, entity=None): """ Performs the validation of the decorated endpoint. expected_keys None or list of strings that will define the values that will need to be present when a request is received constraint_check None or list of dictionaries that contain the following syntax {Instance: 'key_on_request_to_find_by_id'} entity None or dictionary that has the following format {Instance: 'id'} Instance is the entity you will verify before performing an update id of the element is the string that will be extracted from the request If any of these rules is defined and not complemented, we will return the following status codes 400 Invalid request 404 Entity not found Obviously you will return an invalid request if you do not follow the format that you define and you will return 404 when you send an inexistent key """ def data_validation(f): @functools.wraps(f) def wrapper(*args, **kwargs): has_all_keys = True constraints_exists = [] if expected_keys is not None: decoded_keys = [item.encode('utf-8') for item in request.json.keys()] msg = "Received: {yours}, Expected:{mine}"\ .format(yours=decoded_keys, mine=expected_keys) current_app.logger.debug(msg) for entity_field_name in expected_keys: is_on_expected = entity_field_name in decoded_keys if not is_on_expected: msg = "{} is not on expected".format(entity_field_name) current_app.logger.debug(msg) has_all_keys = False break else: has_all_keys = True if not has_all_keys: msg = "Not all keys are present. We want {these} and you sent\ {yours}".format(these=expected_keys, yours=decoded_keys) return Response(json.dumps({MSG: msg}), ERROR, content_type=JSON_HEADER) if constraint_check is not None: for index, structure in enumerate(constraint_check): provided_id = request.json[structure.values()[index]] constraints_exists.append(structure.keys()[index]\ .query.filter_by(id=provided_id)\ .count()) if 0 in constraints_exists: msg = "You sent me something I can't find" return Response(json.dumps({MSG: msg}), NOT_FOUND, content_type=JSON_HEADER) if entity is not None: structure = entity.keys()[0] object_id = request.json[entity.values()[0]] was_found = structure.query.filter_by(id=object_id).count() if not was_found: msg = "You sent me something I can't find" return Response(json.dumps({MSG: msg}), NOT_FOUND, content_type=JSON_HEADER) return f(*args, **kwargs) return wrapper return data_validation
unlicense
ibnoe/SIMRS-1
WebUI/Backoffice/Referensi/SatuanKerja/List.aspx.cs
15313
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Referensi_SatuanKerja_List : System.Web.UI.Page { public int NoKe = 0; protected string dsReportSessionName = "dsListRefSatuanKerja"; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["SatuanKerjaManagement"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } else { btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddSatuanKerja"); } btnSearch.Text = Resources.GetString("", "Search"); ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif"; ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif"; ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif"; ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif"; UpdateDataView(true); } } #region .Update View Data ////////////////////////////////////////////////////////////////////// // PhysicalDataRead // ------------------------------------------------------------------ /// <summary> /// This function is responsible for loading data from database. /// </summary> /// <returns>DataSet</returns> public DataSet PhysicalDataRead() { // Local variables DataSet oDS = new DataSet(); // Get Data SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable myData = myObj.SelectAll(); oDS.Tables.Add(myData); return oDS; } /// <summary> /// This function is responsible for binding data to Datagrid. /// </summary> /// <param name="dv"></param> private void BindData(DataView dv) { // Sets the sorting order dv.Sort = DataGridList.Attributes["SortField"]; if (DataGridList.Attributes["SortAscending"] == "no") dv.Sort += " DESC"; if (dv.Count > 0) { DataGridList.ShowFooter = false; int intRowCount = dv.Count; int intPageSaze = DataGridList.PageSize; int intPageCount = intRowCount / intPageSaze; if (intRowCount - (intPageCount * intPageSaze) > 0) intPageCount = intPageCount + 1; if (DataGridList.CurrentPageIndex >= intPageCount) DataGridList.CurrentPageIndex = intPageCount - 1; } else { DataGridList.ShowFooter = true; DataGridList.CurrentPageIndex = 0; } // Re-binds the grid NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex; DataGridList.DataSource = dv; DataGridList.DataBind(); int CurrentPage = DataGridList.CurrentPageIndex + 1; lblCurrentPage.Text = CurrentPage.ToString(); lblTotalPage.Text = DataGridList.PageCount.ToString(); lblTotalRecord.Text = dv.Count.ToString(); } /// <summary> /// This function is responsible for loading data from database and store to Session. /// </summary> /// <param name="strDataSessionName"></param> public void DataFromSourceToMemory(String strDataSessionName) { // Gets rows from the data source DataSet oDS = PhysicalDataRead(); // Stores it in the session cache Session[strDataSessionName] = oDS; } /// <summary> /// This function is responsible for update data view from datagrid. /// </summary> /// <param name="requery">true = get data from database, false= get data from session</param> public void UpdateDataView(bool requery) { // Retrieves the data if ((Session[dsReportSessionName] == null) || (requery)) { if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString()); DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } public void UpdateDataView() { // Retrieves the data if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } #endregion #region .Event DataGridList ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // HANDLERs // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageChanged(Object sender, DataGridPageChangedEventArgs e) { DataGridList.CurrentPageIndex = e.NewPageIndex; DataGridList.SelectedIndex = -1; UpdateDataView(); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="nPageIndex"></param> public void GoToPage(Object sender, int nPageIndex) { DataGridPageChangedEventArgs evPage; evPage = new DataGridPageChangedEventArgs(sender, nPageIndex); PageChanged(sender, evPage); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a first page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToFirst(Object sender, ImageClickEventArgs e) { GoToPage(sender, 0); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a previous page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToPrev(Object sender, ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex > 0) { GoToPage(sender, DataGridList.CurrentPageIndex - 1); } else { GoToPage(sender, 0); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a next page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1)) { GoToPage(sender, DataGridList.CurrentPageIndex + 1); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a last page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToLast(Object sender, ImageClickEventArgs e) { GoToPage(sender, DataGridList.PageCount - 1); } /// <summary> /// This function is invoked when you click on a column's header to /// sort by that. It just saves the current sort field name and /// refreshes the grid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void SortByColumn(Object sender, DataGridSortCommandEventArgs e) { String strSortBy = DataGridList.Attributes["SortField"]; String strSortAscending = DataGridList.Attributes["SortAscending"]; // Sets the new sorting field DataGridList.Attributes["SortField"] = e.SortExpression; // Sets the order (defaults to ascending). If you click on the // sorted column, the order reverts. DataGridList.Attributes["SortAscending"] = "yes"; if (e.SortExpression == strSortBy) DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes"); // Refreshes the view OnClearSelection(null, null); UpdateDataView(); } /// <summary> /// The function gets invoked when a new item is being created in /// the datagrid. This applies to pager, header, footer, regular /// and alternating items. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageItemCreated(Object sender, DataGridItemEventArgs e) { // Get the newly created item ListItemType itemType = e.Item.ItemType; ////////////////////////////////////////////////////////// // Is it the HEADER? if (itemType == ListItemType.Header) { for (int i = 0; i < DataGridList.Columns.Count; i++) { // draw to reflect sorting if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression) { ////////////////////////////////////////////// // Should be much easier this way: // ------------------------------------------ // TableCell cell = e.Item.Cells[i]; // Label lblSorted = new Label(); // lblSorted.Font = "webdings"; // lblSorted.Text = strOrder; // cell.Controls.Add(lblSorted); // // but it seems it doesn't work <g> ////////////////////////////////////////////// // Add a non-clickable triangle to mean desc or asc. // The </a> ensures that what follows is non-clickable TableCell cell = e.Item.Cells[i]; LinkButton lb = (LinkButton)cell.Controls[0]; //lb.Text += "</a>&nbsp;<span style=font-family:webdings;>" + GetOrderSymbol() + "</span>"; lb.Text += "</a>&nbsp;<img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >"; } } } ////////////////////////////////////////////////////////// // Is it the PAGER? if (itemType == ListItemType.Pager) { // There's just one control in the list... TableCell pager = (TableCell)e.Item.Controls[0]; // Enumerates all the items in the pager... for (int i = 0; i < pager.Controls.Count; i += 2) { // It can be either a Label or a Link button try { Label l = (Label)pager.Controls[i]; l.Text = "Hal " + l.Text; l.CssClass = "CurrentPage"; } catch { LinkButton h = (LinkButton)pager.Controls[i]; h.Text = "[ " + h.Text + " ]"; h.CssClass = "HotLink"; } } } } /// <summary> /// Verifies whether the current sort is ascending or descending and /// returns an appropriate display text (i.e., a webding) /// </summary> /// <returns></returns> private String GetOrderSymbol() { bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no"); //return (bDescending ? " 6" : " 5"); return (bDescending ? "downbr.gif" : "upbr.gif"); } /// <summary> /// When clicked clears the current selection if any /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnClearSelection(Object sender, EventArgs e) { DataGridList.SelectedIndex = -1; } #endregion #region .Event Button /// <summary> /// When clicked, redirect to form add for inserts a new record to the database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnNewRecord(Object sender, EventArgs e) { string CurrentPage = DataGridList.CurrentPageIndex.ToString(); Response.Redirect("Add.aspx?CurrentPage=" + CurrentPage); } /// <summary> /// When clicked, filter data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnSearch(Object sender, System.EventArgs e) { if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; DataView dv = ds.Tables[0].DefaultView; if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Kode") dv.RowFilter = " Kode LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NamaSatker") dv.RowFilter = " NamaSatker LIKE '%" + txtSearch.Text + "%'"; else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Keterangan") dv.RowFilter = " Keterangan LIKE '%" + txtSearch.Text + "%'"; else dv.RowFilter = ""; BindData(dv); } #endregion #region .Update Link Item Butom /// <summary> /// The function is responsible for get link button form. /// </summary> /// <param name="szId"></param> /// <param name="CurrentPage"></param> /// <returns></returns> public string GetLinkButton(string Id, string Nama, string CurrentPage) { string szResult = ""; if (Session["SatuanKerjaManagement"] != null) { szResult += "<a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" "; szResult += ">" + Resources.GetString("", "Edit") + "</a>"; szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" "; szResult += ">" + Resources.GetString("", "Delete") + "</a>"; } return szResult; } #endregion }
unlicense
drmwndr/cloud1
db/schema.rb
4683
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20170726003353) do create_table "conditions", :force => true do |t| t.string "description", :limit => 45 t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "line_items", :force => true do |t| t.integer "product_id", :null => false t.integer "condition_id", :null => false t.decimal "quantity", :precision => 8, :scale => 2, :null => false t.date "exp_date" t.string "serial_number", :limit => 45 t.string "batch_number", :limit => 45 t.string "stock_address", :limit => 45, :null => false t.text "remarks" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end add_index "line_items", ["condition_id"], :name => "index_line_items_on_condition_id" add_index "line_items", ["product_id"], :name => "index_line_items_on_product_id" create_table "order_items", :force => true do |t| t.integer "line_item_id", :null => false t.integer "order_id", :null => false t.integer "quantity" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end add_index "order_items", ["line_item_id"], :name => "index_order_items_on_line_item_id" add_index "order_items", ["order_id"], :name => "index_order_items_on_order_id" create_table "order_statuses", :force => true do |t| t.string "description", :limit => 45 t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "orders", :force => true do |t| t.integer "order_status_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end add_index "orders", ["order_status_id"], :name => "index_orders_on_order_status_id" create_table "product_alternatives", :force => true do |t| t.integer "master_product_id", :null => false t.integer "similar_product_id", :null => false t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end add_index "product_alternatives", ["master_product_id"], :name => "index_product_alternatives_on_master_product_id" add_index "product_alternatives", ["similar_product_id"], :name => "index_product_alternatives_on_similar_product_id" create_table "product_types", :force => true do |t| t.string "description", :limit => 45, :null => false t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "product_uoms", :force => true do |t| t.string "description", :limit => 45, :null => false t.string "uom", :limit => 6, :null => false t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "products", :force => true do |t| t.integer "product_type_id", :null => false t.integer "product_uom_id", :default => 1, :null => false t.string "part_number", :limit => 45 t.string "sanitized_part_number", :limit => 45 t.string "description", :limit => 45, :null => false t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end add_index "products", ["product_type_id"], :name => "index_products_on_product_type_id" add_index "products", ["product_uom_id"], :name => "index_products_on_product_uom_id" end
unlicense
cc14514/hq6
hq-server/src/main/java/org/hyperic/hq/events/AbstractEvent.java
2749
/* * NOTE: This copyright doesnot cover user programs that use HQ program services * by normal system calls through the application program interfaces provided as * part of the Hyperic Plug-in Development Kit or the Hyperic Client Development * Kit - this is merely considered normal use of the program, and doesnot fall * under the heading of "derived work". Copyright (C) [2004, 2005, 2006], * Hyperic, Inc. This file is part of HQ. HQ is free software; you can * redistribute it and/or modify it under the terms version 2 of the GNU General * Public License as published by the Free Software Foundation. This program is * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. You * should have received a copy of the GNU General Public License along with this * program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA. */ /* * AbstractEvent.java Created on September 11, 2002, 2:45 PM */ package org.hyperic.hq.events; import java.io.Serializable; /** * Subsystems will extend the abstract Event class to be able to return a * specific payload value. */ public abstract class AbstractEvent implements Serializable, Cloneable { private static final long serialVersionUID = 1300452915258577781L; private Long _id; private Integer _instanceId; private long _timestamp = System.currentTimeMillis(); public Long getId() { return _id; } public void setId(Long id) { _id = id; } public Integer getInstanceId() { return _instanceId; } public void setInstanceId(Integer instanceId) { _instanceId = instanceId; } public long getTimestamp() { return _timestamp; } public void setTimestamp(long timestamp) { _timestamp = timestamp; } public boolean isLoggingSupported() { return this instanceof LoggableInterface; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_id == null) ? 0 : _id.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } AbstractEvent other = (AbstractEvent) obj; if (_id == null) { if (other._id != null) { return false; } } else if (!_id.equals(other._id)) { return false; } return true; } }
unlicense
nghiatd/aati
public/avatars/upload-file.php
245
<?php $uploaddir = ROOT_URL."/public/avatars/"; echo $uploaddir; $file = $uploaddir . basename($_FILES['uploadfile']['name']); if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) { echo "success"; } else { echo "error"; } ?>
unlicense
flavius/kakoune
src/buffer.hh
8434
#ifndef buffer_hh_INCLUDED #define buffer_hh_INCLUDED #include "clock.hh" #include "coord.hh" #include "flags.hh" #include "safe_ptr.hh" #include "scope.hh" #include "shared_string.hh" #include "value.hh" #include "vector.hh" #include <time.h> namespace Kakoune { enum class EolFormat { Lf, Crlf }; constexpr Array<EnumDesc<EolFormat>, 2> enum_desc(EolFormat) { return { { { EolFormat::Lf, "lf" }, { EolFormat::Crlf, "crlf" }, } }; } enum class ByteOrderMark { None, Utf8 }; constexpr Array<EnumDesc<ByteOrderMark>, 2> enum_desc(ByteOrderMark) { return { { { ByteOrderMark::None, "none" }, { ByteOrderMark::Utf8, "utf8" }, } }; } class Buffer; constexpr timespec InvalidTime = { -1, -1 }; // A BufferIterator permits to iterate over the characters of a buffer class BufferIterator { public: using value_type = char; using difference_type = ssize_t; using pointer = const value_type*; using reference = const value_type&; using iterator_category = std::random_access_iterator_tag; BufferIterator() : m_buffer(nullptr) {} BufferIterator(const Buffer& buffer, BufferCoord coord); bool operator== (const BufferIterator& iterator) const; bool operator!= (const BufferIterator& iterator) const; bool operator< (const BufferIterator& iterator) const; bool operator<= (const BufferIterator& iterator) const; bool operator> (const BufferIterator& iterator) const; bool operator>= (const BufferIterator& iterator) const; const char& operator* () const; const char& operator[](size_t n) const; size_t operator- (const BufferIterator& iterator) const; BufferIterator operator+ (ByteCount size) const; BufferIterator operator- (ByteCount size) const; BufferIterator& operator+= (ByteCount size); BufferIterator& operator-= (ByteCount size); BufferIterator& operator++ (); BufferIterator& operator-- (); BufferIterator operator++ (int); BufferIterator operator-- (int); const BufferCoord& coord() const { return m_coord; } private: SafePtr<const Buffer> m_buffer; StringView m_line; BufferCoord m_coord; LineCount m_last_line; }; using BufferLines = Vector<StringDataPtr, MemoryDomain::BufferContent>; // A Buffer is a in-memory representation of a file // // The Buffer class permits to read and mutate this file // representation. It also manage modifications undo/redo and // provides tools to deal with the line/column nature of text. class Buffer : public SafeCountable, public OptionManagerWatcher, public Scope { public: enum class Flags { None = 0, File = 1 << 0, New = 1 << 1, Fifo = 1 << 2, NoUndo = 1 << 3, NoHooks = 1 << 4, Debug = 1 << 5, ReadOnly = 1 << 6, }; Buffer(String name, Flags flags, StringView data = {}, timespec fs_timestamp = InvalidTime); Buffer(const Buffer&) = delete; Buffer& operator= (const Buffer&) = delete; ~Buffer(); Flags flags() const { return m_flags; } Flags& flags() { return m_flags; } bool set_name(String name); void update_display_name(); BufferCoord insert(BufferCoord pos, StringView content); BufferCoord erase(BufferCoord begin, BufferCoord end); BufferCoord replace(BufferCoord begin, BufferCoord end, StringView content); size_t timestamp() const; timespec fs_timestamp() const; void set_fs_timestamp(timespec ts); void commit_undo_group(); bool undo(size_t count = 1) noexcept; bool redo(size_t count = 1) noexcept; bool move_to(size_t history_id) noexcept; size_t current_history_id() const noexcept; String string(BufferCoord begin, BufferCoord end) const; const char& byte_at(BufferCoord c) const; ByteCount distance(BufferCoord begin, BufferCoord end) const; BufferCoord advance(BufferCoord coord, ByteCount count) const; BufferCoord next(BufferCoord coord) const; BufferCoord prev(BufferCoord coord) const; BufferCoord char_next(BufferCoord coord) const; BufferCoord char_prev(BufferCoord coord) const; BufferCoord back_coord() const; BufferCoord end_coord() const; bool is_valid(BufferCoord c) const; bool is_end(BufferCoord c) const; BufferCoord last_modification_coord() const; BufferIterator begin() const; BufferIterator end() const; LineCount line_count() const; StringView operator[](LineCount line) const { return m_lines[line]; } const StringDataPtr& line_storage(LineCount line) const { return m_lines.get_storage(line); } // returns an iterator at given coordinates. clamp line_and_column BufferIterator iterator_at(BufferCoord coord) const; // returns nearest valid coordinates from given ones BufferCoord clamp(BufferCoord coord) const; BufferCoord offset_coord(BufferCoord coord, CharCount offset); BufferCoordAndTarget offset_coord(BufferCoordAndTarget coord, LineCount offset); const String& name() const { return m_name; } const String& display_name() const { return m_display_name; } // returns true if the buffer is in a different state than // the last time it was saved bool is_modified() const; // notify the buffer that it was saved in the current state void notify_saved(); ValueMap& values() const { return m_values; } void run_hook_in_own_context(StringView hook_name, StringView param, String client_name = ""); void reload(StringView data, timespec fs_timestamp = InvalidTime); void check_invariant() const; struct Change { enum Type : char { Insert, Erase }; Type type; bool at_end; BufferCoord begin; BufferCoord end; }; ConstArrayView<Change> changes_since(size_t timestamp) const; String debug_description() const; // Methods called by the buffer manager void on_registered(); void on_unregistered(); private: void on_option_changed(const Option& option) override; BufferCoord do_insert(BufferCoord pos, StringView content); BufferCoord do_erase(BufferCoord begin, BufferCoord end); struct Modification; void apply_modification(const Modification& modification); void revert_modification(const Modification& modification); struct LineList : BufferLines { [[gnu::always_inline]] StringDataPtr& get_storage(LineCount line) { return BufferLines::operator[]((int)line); } [[gnu::always_inline]] const StringDataPtr& get_storage(LineCount line) const { return BufferLines::operator[]((int)line); } [[gnu::always_inline]] StringView operator[](LineCount line) const { return get_storage(line)->strview(); } StringView front() const { return BufferLines::front()->strview(); } StringView back() const { return BufferLines::back()->strview(); } }; LineList m_lines; String m_name; String m_display_name; Flags m_flags; using UndoGroup = Vector<Modification, MemoryDomain::BufferMeta>; struct HistoryNode : SafeCountable, UseMemoryDomain<MemoryDomain::BufferMeta> { HistoryNode(size_t id, HistoryNode* parent); size_t id; SafePtr<HistoryNode> parent; UndoGroup undo_group; Vector<std::unique_ptr<HistoryNode>, MemoryDomain::BufferMeta> childs; SafePtr<HistoryNode> redo_child; TimePoint timepoint; }; size_t m_next_history_id = 0; HistoryNode m_history; SafePtr<HistoryNode> m_history_cursor; SafePtr<HistoryNode> m_last_save_history_cursor; UndoGroup m_current_undo_group; void move_to(HistoryNode* history_node) noexcept; template<typename Func> HistoryNode* find_history_node(HistoryNode* node, const Func& func); Vector<Change, MemoryDomain::BufferMeta> m_changes; timespec m_fs_timestamp; // Values are just data holding by the buffer, they are not part of its // observable state mutable ValueMap m_values; }; template<> struct WithBitOps<Buffer::Flags> : std::true_type {}; } #include "buffer.inl.hh" #endif // buffer_hh_INCLUDED
unlicense
lamassu/lamassu-machine
tools/cam-bench.js
2166
const pWhilst = require('p-whilst') const v4l2camera = require('v4l2camera') const jpg = require('jpeg-turbo') const microtime = require('microtime') const _ = require('lodash/fp') const ons = {} const intervals = {} const counts = {} function on (name) { ons[name] = microtime.now() } function off (name) { const interval = microtime.now() - ons[name] intervals[name] = (intervals[name] || 0) + interval counts[name] = (counts[name] || 0) + 1 } function setConfig (width, height, formatName, cam) { const format = cam.formats.filter(f => f.formatName === formatName && f.width === width && f.height === height )[0] if (!format) throw new Error('Unsupported cam resolution: %dx%d', width, height) cam.configSet(format) } function capture (cam) { return new Promise((resolve, reject) => { on('full-capture') on('capture') cam.capture(success => { off('capture') if (!success) return reject(new Error('cam error')) on('frame-raw') const frame = Buffer.from(cam.frameRaw()) off('frame-raw') // on('greyscale') // const greyscale = jpg.decompressSync(frame, {format: jpg.FORMAT_GRAY}) // off('greyscale') off('full-capture') return resolve() }) }) } function printStats () { const names = _.keys(ons) _.forEach(name => { console.log(`${name}: [${counts[name]}] ${(intervals[name] / counts[name]) / 1000} ms`) }, names) } function fullCapture () { return new Promise((resolve, reject) => { cam.start() return pWhilst(() => count++ < 500, () => capture(cam)) .then(() => cam.stop(resolve)) }) } const cam = new v4l2camera.Camera('/dev/video0') setConfig(1280, 720, 'YUYV', cam) function simpleCapture () { return new Promise((resolve, reject) => { on('full-cam') on('start') cam.start() off('start') let capCount = 0 return pWhilst(() => capCount++ < 20, () => capture(cam)) .then(() => on('stop')) .then(() => cam.stop(resolve)) .then(() => off('stop')) .then(() => off('full-cam')) }) } let count = 0 // fullCapture() pWhilst(() => count++ < 10, simpleCapture) .then(printStats)
unlicense
debop/spring-batch-experiments
chapter06/src/main/java/kr/spring/batch/chapter06/file/ProductFooterStaxCallback.java
1610
package kr.spring.batch.chapter06.file; import lombok.extern.slf4j.Slf4j; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.listener.StepExecutionListenerSupport; import org.springframework.batch.item.xml.StaxWriterCallback; import javax.xml.stream.XMLEventFactory; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import java.io.IOException; /** * kr.spring.batch.chapter06.file.ProductFooterStaxCallback * * @author 배성혁 sunghyouk.bae@gmail.com * @since 13. 8. 7. 오전 10:23 */ @Slf4j public class ProductFooterStaxCallback extends StepExecutionListenerSupport implements StaxWriterCallback { private StepExecution stepExecution; @Override public void write(XMLEventWriter writer) throws IOException { try { XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent event = eventFactory.createStartElement("", "", "footer"); writer.add(event); event = eventFactory.createStartElement("", "", "writeCount"); writer.add(event); event = eventFactory.createCharacters(String.valueOf(stepExecution.getWriteCount())); writer.add(event); event = eventFactory.createEndElement("", "", "writeCount"); writer.add(event); event = eventFactory.createEndElement("", "", "footer"); writer.add(event); } catch (XMLStreamException ignored) { log.warn("Footer 작업 중 예외가 발생했습니다.", ignored); } } @Override public void beforeStep(StepExecution stepExecution) { this.stepExecution = stepExecution; } }
unlicense
briangreenery/bran
lib/worker/register.js
758
var request = require('request'); function register(options) { var url, body; url = 'http://' + options.master + '/workers'; body = { name: options.name, port: options.port }; if (options.verbose) { console.error('Registering with %s', options.master); } request.post(url, {json: body}, function(err, res) { if (err) { console.error('Failed to register with master: %s'.bold.red, err.message); } else if (res.statusCode !== 200) { console.error( 'Failed to register with master: status %d'.bold.red, res.statusCode); } else if (options.verbose) { console.error('Registration successful'); } setTimeout(register.bind(undefined, options), 10000); }); } module.exports = register;
unlicense
tronje/GWV
04/playing_field/node.py
1092
# -*- coding: utf-8 -*- import math class Node(object): """A node in a PlayingField, which has a value, coordinates, a distance (from some start node) and a parent. """ def __init__(self, value, coords, distance=math.inf, parent=None): """Initialize a Node. Params: ------- value : object The value saved by this node. coords : (int, int) the coordinates of this Node in the PlayingField as a tuple distance : int A variable to hold a distance to be assigned by a search algorithm. Default is infinity. parent : Node A variable to hold a parent to be assigned by a search algorithm. """ self.value = value self.coords = coords self.distance = distance self.parent = parent def __str__(self): return str(self.value) @property def x(self): """The x-coordinate""" return self.coords[0] @property def y(self): """The y-coordinate""" return self.coords[1]
unlicense
aurelijusjaneliunas/darius-ir-jurga.net
backend/apps/stag/views.py
504
from django.shortcuts import render from .models import Lock from .serializers import LockSerializer from rest_framework import generics class LockList(generics.ListCreateAPIView): queryset = Lock.objects.all() serializer_class = LockSerializer class LockDetail(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'slug' queryset = Lock.objects.all() serializer_class = LockSerializer # Create your views here. def index(request): return render(request, "stag/index.html")
unlicense
acardenasnet/santafe_jh
src/main/webapp/app/entities/address/address.state.js
5096
(function() { 'use strict'; angular .module('santafeJhApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider .state('address', { parent: 'entity', url: '/address', data: { authorities: ['ROLE_USER'], pageTitle: 'santafeJhApp.address.home.title' }, views: { 'content@': { templateUrl: 'app/entities/address/addresses.html', controller: 'AddressController', controllerAs: 'vm' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('address'); $translatePartialLoader.addPart('global'); return $translate.refresh(); }] } }) .state('address-detail', { parent: 'entity', url: '/address/{id}', data: { authorities: ['ROLE_USER'], pageTitle: 'santafeJhApp.address.detail.title' }, views: { 'content@': { templateUrl: 'app/entities/address/address-detail.html', controller: 'AddressDetailController', controllerAs: 'vm' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('address'); return $translate.refresh(); }], entity: ['$stateParams', 'Address', function($stateParams, Address) { return Address.get({id : $stateParams.id}); }] } }) .state('address.new', { parent: 'address', url: '/new', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/address/address-dialog.html', controller: 'AddressDialogController', controllerAs: 'vm', backdrop: 'static', size: 'lg', resolve: { entity: function () { return { number: null, id: null }; } } }).result.then(function() { $state.go('address', null, { reload: true }); }, function() { $state.go('address'); }); }] }) .state('address.edit', { parent: 'address', url: '/{id}/edit', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/address/address-dialog.html', controller: 'AddressDialogController', controllerAs: 'vm', backdrop: 'static', size: 'lg', resolve: { entity: ['Address', function(Address) { return Address.get({id : $stateParams.id}); }] } }).result.then(function() { $state.go('address', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('address.delete', { parent: 'address', url: '/{id}/delete', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/address/address-delete-dialog.html', controller: 'AddressDeleteController', controllerAs: 'vm', size: 'md', resolve: { entity: ['Address', function(Address) { return Address.get({id : $stateParams.id}); }] } }).result.then(function() { $state.go('address', null, { reload: true }); }, function() { $state.go('^'); }); }] }); } })();
unlicense
debop/spring-batch-experiments
chapter02/src/test/java/kr/spring/batch/chapter02/test/structure/DummyTasklet.java
793
package kr.spring.batch.chapter02.test.structure; import lombok.extern.slf4j.Slf4j; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; /** * kr.spring.batch.chapter02.test.structure.DummyTasklet * * @author 배성혁 sunghyouk.bae@gmail.com * @since 13. 7. 31. 오전 12:09 */ @Slf4j public class DummyTasklet implements Tasklet { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { log.info("Execute Tasklet... StepName=[{}]", chunkContext.getStepContext().getStepName()); return RepeatStatus.FINISHED; } }
unlicense
dbasilioesp/RobotCombat
Item.cpp
491
#include "Item.h" Item::Item(void) { } Item::~Item(void) { } int Item::getId() { return id; } string Item::getName() { return name; } string Item::getType() { return type; } int Item::getValue() { return value; } void Item::setId(int _id) { id = _id; } void Item::setName(string _name) { name = _name; } void Item::setValue(int _value) { value = _value; } void Item::setType(int _type) { type = _type; }
unlicense
codeApeFromChina/resource
frame_packages/java_libs/hibernate-distribution-3.6.10.Final/project/hibernate-core/src/main/java/org/hibernate/annotations/Check.java
1507
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * 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 distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.annotations; import static java.lang.annotation.ElementType.*; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; /** * Arbitrary SQL check constraints which can be defined at the class, * property or collection level * * @author Emmanuel Bernard */ @Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface Check { String constraints(); }
unlicense
JustenG/ComputerGraphics
deps/fbx/FBXFile.cpp
54294
#include "FBXFile.h" #include <fbxsdk.h> #include <algorithm> #include <set> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/norm.hpp> #include "gl_core_4_4.h" #include "GLFW/glfw3.h" struct ImportAssistor { ImportAssistor() : scene(nullptr), evaluator(nullptr), importer(nullptr), loadTextures(false), loadAnimations(false), loadMeshes(false), loadCameras(false), loadLights(false) {} ~ImportAssistor() = default; FbxScene* scene; FbxAnimEvaluator* evaluator; FbxImporter* importer; std::vector<FBXNode*> bones; bool loadTextures; bool loadAnimations; bool loadMeshes; bool loadCameras; bool loadLights; float unitScale; bool flipTextureY; std::map<std::string, int> boneIndexList; }; //------------ Helpers -------------------- template<typename T> int GetDirectIndex(FbxLayerElementTemplate<T>* pElementArray, int defaultIndex) { assert(pElementArray != nullptr); int directIndex = defaultIndex; switch (pElementArray->GetReferenceMode()) { case FbxGeometryElement::eDirect: break; // Just use the control point index in the direct array. case FbxGeometryElement::eIndexToDirect: directIndex = pElementArray->GetIndexArray().GetAt(defaultIndex); break; default: //POW2_ASSERT_FAIL( "Reference mode not supported." ); directIndex = -1; break; } return directIndex; } template<typename T> int GetPolygonVertexDirectIndex(FbxLayerElementTemplate<T>* pElementArray, FbxMesh* pFbxMesh, int polygonIndex, int vertIndex) { int directIndex = -1; switch (pElementArray->GetReferenceMode()) { case FbxGeometryElement::eDirect: case FbxGeometryElement::eIndexToDirect: directIndex = pFbxMesh->GetTextureUVIndex(polygonIndex, vertIndex); break; default: break; // other reference modes not shown here! } return directIndex; } int GetVertexCoordDirectIndex(FbxMesh* pFbxMesh, FbxLayerElementUV* pFbxTexCoord, int controlPointIndex, int polygonIndex, int vertIndex) { int directIndex = -1; switch (pFbxTexCoord->GetMappingMode()) { case FbxGeometryElement::eByControlPoint: directIndex = GetDirectIndex(pFbxTexCoord, controlPointIndex); break; case FbxGeometryElement::eByPolygonVertex: directIndex = GetPolygonVertexDirectIndex(pFbxTexCoord, pFbxMesh, polygonIndex, vertIndex); break; case FbxGeometryElement::eByPolygon: // doesn't make much sense for UVs case FbxGeometryElement::eAllSame: // doesn't make much sense for UVs case FbxGeometryElement::eNone: // doesn't make much sense for UVs default: break; } return directIndex; } int GetVertexColorDirectIndex(FbxGeometryElementVertexColor* pVertexColor, int controlPointIndex) { int directIndex = -1; switch (pVertexColor->GetMappingMode()) { case FbxGeometryElement::eByControlPoint: directIndex = GetDirectIndex(pVertexColor, controlPointIndex); break; case FbxGeometryElement::eByPolygonVertex: { switch (pVertexColor->GetReferenceMode()) { case FbxGeometryElement::eDirect: case FbxGeometryElement::eIndexToDirect: directIndex = GetDirectIndex(pVertexColor, controlPointIndex); break; default: break; // other reference modes not shown here! } } break; case FbxGeometryElement::eByPolygon: case FbxGeometryElement::eAllSame: case FbxGeometryElement::eNone: default: break; } return directIndex; } void LoadVertexPositions(FbxVector4* pVertexPositions, int vertexCount, std::vector<FBXVertex>& vertices) { vertices.resize(vertexCount); for (int i = 0; i < vertexCount; ++i) { auto& vertex = vertices[i]; FbxVector4 vPos = pVertexPositions[i]; vertex.position.x = (float)vPos[0]; vertex.position.y = (float)vPos[1]; vertex.position.z = (float)vPos[2]; vertex.position.w = 1; } } void LoadVertexIndices(FbxMesh* pFbxMesh, std::vector<unsigned int>& indices) { int polygonCount = pFbxMesh->GetPolygonCount(); indices.resize(polygonCount * 3); unsigned int indexID = 0; for (int polygonIndex = 0; polygonIndex < polygonCount; polygonIndex++) { int polygonSize = pFbxMesh->GetPolygonSize(polygonIndex); for (int i = 0; i < polygonSize; i++) { assert(polygonSize == 3); assert(indexID<indices.size()); indices[indexID++] = pFbxMesh->GetPolygonVertex(polygonIndex, i); } } } void LoadVertexColors(FbxGeometryElementVertexColor* pVertexColors, int vertexCount, std::vector<FBXVertex>& vertices) { for (int i = 0; i < vertexCount; ++i) { auto& vertex = vertices[i]; int directIndex = GetVertexColorDirectIndex(pVertexColors, i); if (directIndex >= 0) { FbxColor fbxColour = pVertexColors->GetDirectArray().GetAt(directIndex); vertex.colour.x = (float)fbxColour.mRed; vertex.colour.y = (float)fbxColour.mGreen; vertex.colour.z = (float)fbxColour.mBlue; vertex.colour.w = (float)fbxColour.mAlpha; } } } void LoadTexCoords(FbxLayerElementUV* pTexCoord, FbxMesh* pFbxMesh, bool shouldFlipTextureY, std::vector<FBXVertex>& vertices, int uvNumber) { int polygonCount = pFbxMesh->GetPolygonCount(); for (int polygonIndex = 0; polygonIndex < polygonCount; ++polygonIndex) { int polygonSize = pFbxMesh->GetPolygonSize(polygonIndex); for (int polyVertexIndex = 0; polyVertexIndex < polygonSize; ++polyVertexIndex) { assert(polyVertexIndex < 3); int vertexIndex = pFbxMesh->GetPolygonVertex(polygonIndex, polyVertexIndex); int directIndex = GetVertexCoordDirectIndex(pFbxMesh, pTexCoord, vertexIndex, polygonIndex, polyVertexIndex); if (vertexIndex != -1 && directIndex >= 0) { FbxVector2 fbxUV = pTexCoord->GetDirectArray().GetAt(directIndex); assert((unsigned int)vertexIndex < vertices.size()); auto& vertex = vertices[vertexIndex]; if (uvNumber == 0) { vertex.texCoord1.x = (float)fbxUV[0]; vertex.texCoord1.y = (float)fbxUV[1]; if (shouldFlipTextureY) vertex.texCoord1.y = 1.0f - vertex.texCoord1.y; } else if (uvNumber == 1) { vertex.texCoord2.x = (float)fbxUV[0]; vertex.texCoord2.y = (float)fbxUV[1]; if (shouldFlipTextureY) vertex.texCoord2.y = 1.0f - vertex.texCoord2.y; } } } } } void LoadNormals(FbxGeometryElementNormal* pNormal, int vertexCount, std::vector<FBXVertex>& vertices) { for (int i = 0; i < vertexCount; ++i) { int directIndex = -1; if (pNormal->GetMappingMode() == FbxGeometryElement::eByControlPoint || pNormal->GetMappingMode() == FbxGeometryElement::eByPolygonVertex) { directIndex = GetDirectIndex(pNormal, i); } if (directIndex >= 0) { FbxVector4 normal = pNormal->GetDirectArray().GetAt(directIndex); auto& vertex = vertices[i]; vertex.normal.x = (float)normal[0]; vertex.normal.y = (float)normal[1]; vertex.normal.z = (float)normal[2]; vertex.normal.w = 0; } } } void LoadSkinningData(FbxMesh* pFbxMesh, std::vector<FBXVertex>& vertices, std::map<std::string, int> boneIndexList) { FbxSkin* fbxSkin = (FbxSkin*)pFbxMesh->GetDeformer(0, FbxDeformer::eSkin); int skinClusterCount = fbxSkin != nullptr ? fbxSkin->GetClusterCount() : 0; FbxCluster** skinClusters = nullptr; int* skinClusterBoneIndices = nullptr; if (skinClusterCount > 0) { skinClusters = new FbxCluster *[skinClusterCount]; skinClusterBoneIndices = new int[skinClusterCount]; for (int i = 0; i < skinClusterCount; ++i) { skinClusters[i] = fbxSkin->GetCluster(i); if (skinClusters[i]->GetLink() == nullptr) { skinClusterBoneIndices[i] = -1; } else { skinClusterBoneIndices[i] = boneIndexList[skinClusters[i]->GetLink()->GetName()]; } } } int polygonCount = pFbxMesh->GetPolygonCount(); // process each polygon for (int polygonIndex = 0; polygonIndex < polygonCount; ++polygonIndex) { int polygonSize = pFbxMesh->GetPolygonSize(polygonIndex); for (int polyVertexIndex = 0; polyVertexIndex < polygonSize && polyVertexIndex < 4; ++polyVertexIndex) { int vertexIndex = pFbxMesh->GetPolygonVertex(polygonIndex, polyVertexIndex); FBXVertex& vertex = vertices[vertexIndex]; for (int skinClusterIndex = 0; skinClusterIndex != skinClusterCount; ++skinClusterIndex) { if (skinClusterBoneIndices[skinClusterIndex] == -1) continue; int lIndexCount = skinClusters[skinClusterIndex]->GetControlPointIndicesCount(); int* lIndices = skinClusters[skinClusterIndex]->GetControlPointIndices(); double* lWeights = skinClusters[skinClusterIndex]->GetControlPointWeights(); for (int l = 0; l < lIndexCount; l++) { if (vertexIndex == lIndices[l]) { // add weight and index if (vertex.weights.x == 0) { vertex.weights.x = (float)lWeights[l]; vertex.indices.x = (float)skinClusterBoneIndices[skinClusterIndex]; } else if (vertex.weights.y == 0) { vertex.weights.y = (float)lWeights[l]; vertex.indices.y = (float)skinClusterBoneIndices[skinClusterIndex]; } else if (vertex.weights.z == 0) { vertex.weights.z = (float)lWeights[l]; vertex.indices.z = (float)skinClusterBoneIndices[skinClusterIndex]; } else { vertex.weights.w = (float)lWeights[l]; vertex.indices.w = (float)skinClusterBoneIndices[skinClusterIndex]; } } } } } } delete[] skinClusters; delete[] skinClusterBoneIndices; } // ---------------- Class impl ---------------------- FBXTexture::~FBXTexture() { delete[] data; if (handle != (unsigned int)-1) glDeleteTextures(1, &handle); } void FBXFile::unload() { delete m_root; m_root = nullptr; for (auto m : m_meshes) delete m; for (auto m : m_materials) delete m.second; for (auto s : m_skeletons) delete s; for (auto a : m_animations) delete a.second; for (auto t : m_textures) delete t.second; m_meshes.clear(); m_lights.clear(); m_cameras.clear(); m_materials.clear(); m_skeletons.clear(); m_animations.clear(); m_textures.clear(); } bool FBXFile::load( const char* a_filename, UNIT_SCALE a_scale /* = FBXFile::UNITS_METER */, bool a_loadTextures /* = true */, bool a_loadAnimations /* = true */, bool a_loadMeshes /* = true */, bool a_loadCameras /* = false */, bool a_loadLights /* = false */, bool a_flipTextureY /*= true*/ ) { if (m_root != nullptr) { printf("Scene already loaded!\n"); return false; } FbxManager* lSdkManager = nullptr; FbxScene* lScene = nullptr; // The first thing to do is to create the FBX SDK manager which is the // object allocator for almost all the classes in the SDK. lSdkManager = FbxManager::Create(); if (lSdkManager == nullptr) { printf("Unable to create the FBX SDK manager\n"); return false; } // create an IOSettings object FbxIOSettings * ios = FbxIOSettings::Create(lSdkManager, IOSROOT); lSdkManager->SetIOSettings(ios); // Create an importer. FbxImporter* lImporter = FbxImporter::Create(lSdkManager, ""); // Initialize the importer by providing a filename. bool lImportStatus = lImporter->Initialize(a_filename, -1, lSdkManager->GetIOSettings()); if (!lImportStatus) { printf("Call to FbxImporter::Initialize() failed:\n\t%s\n", lImporter->GetStatus().GetErrorString()); lImporter->Destroy(); return false; } // Create the entity that will hold the scene. int lFileMajor, lFileMinor, lFileRevision; int lSDKMajor, lSDKMinor, lSDKRevision; unsigned int i; bool lStatus; // Get the file version number generate by the FBX SDK. FbxManager::GetFileFormatVersion(lSDKMajor, lSDKMinor, lSDKRevision); lImporter->GetFileVersion(lFileMajor, lFileMinor, lFileRevision); lScene = FbxScene::Create(lSdkManager, "root"); // Import the scene. lStatus = lImporter->Import(lScene); lImporter->Destroy(); if (lStatus == false) { printf("Unable to open FBX file!\n"); return false; } float unitScale = 1; // convert scale if (lScene->GetGlobalSettings().GetSystemUnit() != FbxSystemUnit::sPredefinedUnits[a_scale]) { const FbxSystemUnit::ConversionOptions lConversionOptions = { false, // mConvertRrsNodes true, // mConvertAllLimits true, // mConvertClusters true, // mConvertLightIntensity true, // mConvertPhotometricLProperties true // mConvertCameraClipPlanes }; unitScale = (float)(lScene->GetGlobalSettings().GetSystemUnit().GetScaleFactor() / FbxSystemUnit::sPredefinedUnits[a_scale].GetScaleFactor()); // Convert the scene to meters using the defined options. FbxSystemUnit::sPredefinedUnits[a_scale].ConvertScene(lScene, lConversionOptions); } // convert the scene to OpenGL axis (right-handed Y up) FbxAxisSystem::OpenGL.ConvertScene(lScene); // Convert mesh, NURBS and patch into triangle mesh FbxGeometryConverter geomConverter(lSdkManager); geomConverter.Triangulate(lScene, true); FbxNode* lNode = lScene->GetRootNode(); if (lNode != nullptr) { // store the folder path of the scene m_path = a_filename; long iLastForward = m_path.find_last_of('/'); long iLastBackward = m_path.find_last_of('\\'); if (iLastForward > iLastBackward) { m_path.resize(iLastForward + 1); } else if (iLastBackward != 0) { m_path.resize(iLastBackward + 1); } else { m_path = ""; } m_importAssistor = new ImportAssistor(); m_importAssistor->scene = lScene; m_importAssistor->evaluator = lScene->GetAnimationEvaluator(); m_importAssistor->importer = lImporter; m_importAssistor->loadTextures = a_loadTextures; m_importAssistor->loadAnimations = a_loadAnimations; m_importAssistor->loadMeshes = a_loadMeshes; m_importAssistor->loadCameras = a_loadCameras; m_importAssistor->loadLights = a_loadLights; m_importAssistor->unitScale = unitScale; m_importAssistor->flipTextureY = a_flipTextureY; m_root = new FBXNode(); m_root->m_name = "root"; m_root->m_globalTransform = m_root->m_localTransform = glm::mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); // grab the ambient light data from the scene m_ambientLight.x = (float)lScene->GetGlobalSettings().GetAmbientColor().mRed; m_ambientLight.y = (float)lScene->GetGlobalSettings().GetAmbientColor().mGreen; m_ambientLight.z = (float)lScene->GetGlobalSettings().GetAmbientColor().mBlue; m_ambientLight.w = (float)lScene->GetGlobalSettings().GetAmbientColor().mAlpha; // gather bones to create indices for them in a skeleton if (a_loadAnimations == true) { for (i = 0; i < (unsigned int)lNode->GetChildCount(); ++i) { gatherBones((void*)lNode->GetChild(i)); } } // extract scene (meshes, lights, cameras) for (i = 0; i < (unsigned int)lNode->GetChildCount(); ++i) { extractObject(m_root, (void*)lNode->GetChild(i)); } // ensure all threads are finished for (auto t : m_threads) { t->join(); delete t; } m_threads.clear(); // build skeleton and extract animation keyframes if (a_loadAnimations == true && m_importAssistor->bones.size() > 0) { FBXSkeleton* skeleton = new FBXSkeleton(); skeleton->m_boneCount = (unsigned int)m_importAssistor->bones.size(); skeleton->m_nodes = new FBXNode *[skeleton->m_boneCount]; // TODO cleanup properly void* pBonesBuffer = _aligned_malloc(sizeof(glm::mat4)*(skeleton->m_boneCount + 1), 16); skeleton->m_bones = new(pBonesBuffer) glm::mat4[skeleton->m_boneCount]; void* pBindPosesBuffer = _aligned_malloc(sizeof(glm::mat4)*(skeleton->m_boneCount + 1), 16); skeleton->m_bindPoses = new(pBindPosesBuffer)glm::mat4[skeleton->m_boneCount]; skeleton->m_parentIndex = new int[skeleton->m_boneCount]; for (i = 0; i < skeleton->m_boneCount; ++i) { skeleton->m_nodes[i] = m_importAssistor->bones[i]; skeleton->m_bones[i] = skeleton->m_nodes[i]->m_localTransform; } for (i = 0; i < skeleton->m_boneCount; ++i) { skeleton->m_parentIndex[i] = -1; for (int j = 0; j < (int)skeleton->m_boneCount; ++j) { if (skeleton->m_nodes[i]->m_parent == skeleton->m_nodes[j]) { skeleton->m_parentIndex[i] = j; break; } } } extractSkeleton(skeleton, lScene); m_skeletons.push_back(skeleton); extractAnimation(lScene); } m_root->updateGlobalTransform(); delete m_importAssistor; m_importAssistor = nullptr; } lSdkManager->Destroy(); // load textures! for (auto texture : m_textures) m_threads.push_back(new std::thread([](FBXTexture* t) { t->data = stbi_load(t->path.c_str(), &t->width, &t->height, &t->format, STBI_default); // t->data = SOIL_load_image(t->path.c_str(), &t->width, &t->height, &t->channels, SOIL_LOAD_AUTO); if (t->data == nullptr) { printf("Failed to load texture: %s\n", t->path.c_str()); } }, texture.second)); for (auto t : m_threads) { t->join(); delete t; } m_threads.clear(); return true; } void FBXFile::extractObject(FBXNode* a_parent, void* a_object) { FbxNode* fbxNode = (FbxNode*)a_object; FBXNode* node = nullptr; FbxNodeAttribute::EType lAttributeType; int i; bool isBone = false; //JPS: Assuming only one attribute assert( fbxNode->GetNodeAttributeCount()<=1 ); FbxNodeAttribute* pNodeAttribute = fbxNode->GetNodeAttribute(); if (pNodeAttribute != nullptr) { lAttributeType = pNodeAttribute->GetAttributeType(); switch (lAttributeType) { case FbxNodeAttribute::eSkeleton: { isBone = true; } break; case FbxNodeAttribute::eMesh: { if (m_importAssistor->loadMeshes) { extractMeshes(fbxNode->GetMesh()); } } break; case FbxNodeAttribute::eCamera: { if (m_importAssistor->loadCameras == false) { node = new FBXCameraNode(); extractCamera((FBXCameraNode*)node,fbxNode); node->m_name = fbxNode->GetName(); m_cameras[node->m_name] = (FBXCameraNode*)node; } } break; case FbxNodeAttribute::eLight: { if (m_importAssistor->loadLights == false) { node = new FBXLightNode(); extractLight((FBXLightNode*)node,fbxNode); node->m_name = fbxNode->GetName(); m_lights[node->m_name] = (FBXLightNode*)node; } } break; default: break; } } // if null then use it as a plain 3D node if (node == nullptr) { node = new FBXNode(); node->m_name = fbxNode->GetName(); } // add to parent's children and update parent a_parent->m_children.push_back(node); node->m_parent = a_parent; // build local transform // use anim evaluator as bones store transforms in a different spot FbxAMatrix lLocal = m_importAssistor->evaluator->GetNodeLocalTransform(fbxNode); node->m_localTransform = glm::mat4( lLocal[0][0], lLocal[0][1], lLocal[0][2], lLocal[0][3], lLocal[1][0], lLocal[1][1], lLocal[1][2], lLocal[1][3], lLocal[2][0], lLocal[2][1], lLocal[2][2], lLocal[2][3], lLocal[3][0], lLocal[3][1], lLocal[3][2], lLocal[3][3] ); if (m_importAssistor->loadAnimations == true && isBone == true) { m_importAssistor->bones.push_back(node); } // children for (i = 0; i < fbxNode->GetChildCount(); i++) { extractObject(node, (void*)fbxNode->GetChild(i)); } } void FBXFile::extractMeshes(void* a_object) { assert(a_object!=nullptr); FbxMesh* pFbxMesh = static_cast<FbxMesh*>(a_object); m_meshes.push_back( new FBXMeshNode() ); FBXMeshNode& meshNode = *m_meshes.back(); FbxVector4* pVertexPositions = pFbxMesh->GetControlPoints(); int vertexCount = pFbxMesh->GetControlPointsCount(); LoadVertexPositions(pVertexPositions, vertexCount, meshNode.m_vertices); LoadVertexIndices(pFbxMesh, meshNode.m_indices); FbxGeometryElementVertexColor* fbxColours = pFbxMesh->GetElementVertexColor(0); if( fbxColours!=nullptr ) { meshNode.m_vertexAttributes |= FBXVertex::eCOLOUR; LoadVertexColors( fbxColours, vertexCount, meshNode.m_vertices ); } FbxGeometryElementUV* fbxTexCoord0 = pFbxMesh->GetElementUV(0); if( fbxTexCoord0 ) { LoadTexCoords( fbxTexCoord0, pFbxMesh, m_importAssistor->flipTextureY, meshNode.m_vertices, 0); meshNode.m_vertexAttributes |= FBXVertex::eTEXCOORD1; } FbxGeometryElementUV* fbxTexCoord1 = pFbxMesh->GetElementUV(1); if( fbxTexCoord1 ) { LoadTexCoords( fbxTexCoord1, pFbxMesh, m_importAssistor->flipTextureY, meshNode.m_vertices, 1); meshNode.m_vertexAttributes |= FBXVertex::eTEXCOORD2; } FbxGeometryElementNormal* fbxNormal = pFbxMesh->GetElementNormal(0); if( fbxNormal ) { LoadNormals(fbxNormal, vertexCount, meshNode.m_vertices); meshNode.m_vertexAttributes |= FBXVertex::eNORMAL; } // gather skinning info LoadSkinningData(pFbxMesh, meshNode.m_vertices, m_importAssistor->boneIndexList); optimiseMesh(&meshNode); // set mesh names, vertex attributes, extract material and add to mesh map for ( int i = 0 ; i < pFbxMesh->GetElementMaterialCount(); ++i ) { meshNode.m_name = pFbxMesh->GetName(); meshNode.m_materials.push_back( extractMaterial(pFbxMesh,i) ); } } void FBXFile::optimiseMesh(FBXMeshNode* a_mesh) { /* //sort the vertex array so all common verts are adjacent in the array std::sort(a_mesh->m_vertices.begin(), a_mesh->m_vertices.end()); unsigned int forward_iter = 1; int j = 0; while ( forward_iter < a_mesh->m_vertices.size() ) { if ( a_mesh->m_vertices[j] == a_mesh->m_vertices[forward_iter] ) { // if the adjacent verts are equal make all the duplicate vert's indicies point at the first one in the vector a_mesh->m_indices[a_mesh->m_vertices[forward_iter].index[0]] = j; ++forward_iter; } else { // if they aren't duplicates, update the index to point at the vert's post sort position in the vector a_mesh->m_indices[a_mesh->m_vertices[j].index[0]] = j; ++j; // then push the current forward iterator back // not sure if checking if j != forward pointer would be faster here. a_mesh->m_vertices[j] = a_mesh->m_vertices[forward_iter]; a_mesh->m_indices[a_mesh->m_vertices[forward_iter].index[0]] = j; ++forward_iter; } } a_mesh->m_vertices.resize(j+1); */ if ((a_mesh->m_vertexAttributes & FBXVertex::eTEXCOORD1) != 0) { a_mesh->m_vertexAttributes |= FBXVertex::eTANGENT|FBXVertex::eBINORMAL; calculateTangentsBinormals(a_mesh->m_vertices,a_mesh->m_indices); } } void FBXFile::extractLight(FBXLightNode* a_light, void* a_object) { FbxNode* fbxNode = (FbxNode*)a_object; FbxLight* fbxLight = (FbxLight*)fbxNode->GetNodeAttribute(); // get type, if on, and colour a_light->m_type = (FBXLightNode::LightType)fbxLight->LightType.Get(); a_light->m_on = fbxLight->CastLight.Get(); a_light->m_colour.x = (float)fbxLight->Color.Get()[0]; a_light->m_colour.y = (float)fbxLight->Color.Get()[1]; a_light->m_colour.z = (float)fbxLight->Color.Get()[2]; a_light->m_colour.w = (float)fbxLight->Intensity.Get(); // get spot light angles (will return data even for non-spotlights) a_light->m_innerAngle = (float)fbxLight->InnerAngle.Get() * (glm::pi<float>() / 180); a_light->m_outerAngle = (float)fbxLight->OuterAngle.Get() * (glm::pi<float>() / 180); // get falloff data (none,linear, quadratic), cubic is ignored switch (fbxLight->DecayType.Get()) { case 0: a_light->m_attenuation = glm::vec4(1,0,0,0); break; case 1: break; a_light->m_attenuation = glm::vec4(0,1,0,0); case 2: break; a_light->m_attenuation = glm::vec4(0,0,1,0); default: break; }; } void FBXFile::extractCamera(FBXCameraNode* a_camera, void* a_object) { FbxNode* fbxNode = (FbxNode*)a_object; FbxCamera* fbxCamera = (FbxCamera*)fbxNode->GetNodeAttribute(); // get field of view if (fbxCamera->ProjectionType.Get() != FbxCamera::eOrthogonal) { a_camera->m_fieldOfView = (float)fbxCamera->FieldOfView.Get() * (glm::pi<float>() / 180); } else { a_camera->m_fieldOfView = 0; } // get aspect ratio if one was defined if (fbxCamera->GetAspectRatioMode() != FbxCamera::eWindowSize) { a_camera->m_aspectRatio = (float)fbxCamera->AspectWidth.Get() / (float)fbxCamera->AspectHeight.Get(); } else { a_camera->m_aspectRatio = 0; } // get near/far a_camera->m_near = (float)fbxCamera->NearPlane.Get(); a_camera->m_far = (float)fbxCamera->FarPlane.Get(); // build view matrix glm::vec3 vEye, vTo, vUp; vEye.x = (float)fbxCamera->Position.Get()[0]; vEye.y = (float)fbxCamera->Position.Get()[1]; vEye.z = (float)fbxCamera->Position.Get()[2]; if (fbxNode->GetTarget() != nullptr) { vTo.x = (float)fbxNode->GetTarget()->LclTranslation.Get()[0]; vTo.y = (float)fbxNode->GetTarget()->LclTranslation.Get()[1]; vTo.z = (float)fbxNode->GetTarget()->LclTranslation.Get()[2]; } else { vTo.x = (float)fbxCamera->InterestPosition.Get()[0]; vTo.y = (float)fbxCamera->InterestPosition.Get()[1]; vTo.z = (float)fbxCamera->InterestPosition.Get()[2]; } if (fbxNode->GetTargetUp()) { vUp.x = (float)fbxNode->GetTargetUp()->LclTranslation.Get()[0]; vUp.y = (float)fbxNode->GetTargetUp()->LclTranslation.Get()[1]; vUp.z = (float)fbxNode->GetTargetUp()->LclTranslation.Get()[2]; } else { vUp.x = (float)fbxCamera->UpVector.Get()[0]; vUp.y = (float)fbxCamera->UpVector.Get()[1]; vUp.z = (float)fbxCamera->UpVector.Get()[2]; } a_camera->m_viewMatrix = glm::lookAt(vEye,vTo,vUp); } FBXMaterial* FBXFile::extractMaterial(void* a_mesh, int a_materialIndex) { FbxGeometry* pGeometry = (FbxGeometry*)a_mesh; FbxNode* lNode = pGeometry->GetNode(); FbxSurfaceMaterial *lMaterial = lNode->GetMaterial(a_materialIndex); // check if material already loaded, else create new material m_materialMutex.lock(); auto oIter = m_materials.find( lMaterial->GetName() ); if (oIter != m_materials.end()) { m_materialMutex.unlock(); return oIter->second; } else { FBXMaterial* material = new FBXMaterial; material->name = lMaterial->GetName(); // get the implementation to see if it's a hardware shader. const FbxImplementation* lImplementation = GetImplementation(lMaterial, FBXSDK_IMPLEMENTATION_HLSL); if (lImplementation == nullptr) { lImplementation = GetImplementation(lMaterial, FBXSDK_IMPLEMENTATION_CGFX); } if (lImplementation != nullptr) { FbxBindingTable const* lRootTable = lImplementation->GetRootTable(); FbxString lFileName = lRootTable->DescAbsoluteURL.Get(); FbxString lTechniqueName = lRootTable->DescTAG.Get(); printf("Unsupported hardware shader material!\n"); printf("\tFile: %s\n",lFileName.Buffer()); printf("\tTechnique: %s\n\n",lTechniqueName.Buffer()); } else if (lMaterial->GetClassId().Is(FbxSurfacePhong::ClassId)) { // We found a Phong material FbxSurfacePhong* pPhong = (FbxSurfacePhong*)lMaterial; material->ambient.x = (float)pPhong->Ambient.Get()[0]; material->ambient.y = (float)pPhong->Ambient.Get()[1]; material->ambient.z = (float)pPhong->Ambient.Get()[2]; material->ambient.w = (float)pPhong->AmbientFactor.Get(); material->diffuse.x = (float)pPhong->Diffuse.Get()[0]; material->diffuse.y = (float)pPhong->Diffuse.Get()[1]; material->diffuse.z = (float)pPhong->Diffuse.Get()[2]; material->diffuse.w = (float)pPhong->TransparencyFactor.Get(); material->specular.x = (float)pPhong->Specular.Get()[0]; material->specular.y = (float)pPhong->Specular.Get()[1]; material->specular.z = (float)pPhong->Specular.Get()[2]; material->specular.w = (float)pPhong->Shininess.Get(); material->emissive.x = (float)pPhong->Emissive.Get()[0]; material->emissive.y = (float)pPhong->Emissive.Get()[1]; material->emissive.z = (float)pPhong->Emissive.Get()[2]; material->emissive.w = (float)pPhong->EmissiveFactor.Get(); } else if(lMaterial->GetClassId().Is(FbxSurfaceLambert::ClassId) ) { FbxSurfaceLambert* pLambert = (FbxSurfaceLambert*)lMaterial; material->ambient.x = (float)pLambert->Ambient.Get()[0]; material->ambient.y = (float)pLambert->Ambient.Get()[1]; material->ambient.z = (float)pLambert->Ambient.Get()[2]; material->ambient.w = (float)pLambert->AmbientFactor.Get(); material->diffuse.x = (float)pLambert->Diffuse.Get()[0]; material->diffuse.y = (float)pLambert->Diffuse.Get()[1]; material->diffuse.z = (float)pLambert->Diffuse.Get()[2]; material->diffuse.w = (float)pLambert->TransparencyFactor.Get(); // No specular in lambert materials material->specular.x = 0; material->specular.y = 0; material->specular.z = 0; material->specular.w = 0; material->emissive.x = (float)pLambert->Emissive.Get()[0]; material->emissive.y = (float)pLambert->Emissive.Get()[1]; material->emissive.z = (float)pLambert->Emissive.Get()[2]; material->emissive.w = (float)pLambert->EmissiveFactor.Get(); } else { printf("Unknown type of Material: %s\n", lMaterial->GetClassId().GetName()); } unsigned int auiTextureLookup[] = { FbxLayerElement::eTextureDiffuse - FbxLayerElement::sTypeTextureStartIndex, FbxLayerElement::eTextureAmbient - FbxLayerElement::sTypeTextureStartIndex, FbxLayerElement::eTextureEmissive - FbxLayerElement::sTypeTextureStartIndex, FbxLayerElement::eTextureSpecular - FbxLayerElement::sTypeTextureStartIndex, FbxLayerElement::eTextureShininess - FbxLayerElement::sTypeTextureStartIndex, FbxLayerElement::eTextureNormalMap - FbxLayerElement::sTypeTextureStartIndex, FbxLayerElement::eTextureTransparency - FbxLayerElement::sTypeTextureStartIndex, FbxLayerElement::eTextureDisplacement - FbxLayerElement::sTypeTextureStartIndex, }; if (m_importAssistor->loadTextures == true) { for ( unsigned int i = 0 ; i < FBXMaterial::TextureTypes_Count ; ++i ) { FbxProperty pProperty = lMaterial->FindProperty(FbxLayerElement::sTextureChannelNames[auiTextureLookup[i]]); if ( pProperty.IsValid() && pProperty.GetSrcObjectCount<FbxTexture>() > 0) { FbxFileTexture* fileTexture = FbxCast<FbxFileTexture>(pProperty.GetSrcObject<FbxTexture>(0)); if (fileTexture != nullptr) { const char* szLastForward = strrchr(fileTexture->GetFileName(),'/'); const char* szLastBackward = strrchr(fileTexture->GetFileName(),'\\'); const char* szFilename = fileTexture->GetFileName(); material->textureRotation[i] = (float)fileTexture->GetRotationW(); material->textureTiling[i].x = (float)fileTexture->GetScaleU(); material->textureTiling[i].y = (float)fileTexture->GetScaleV(); material->textureOffsets[i].x = (float)fileTexture->GetTranslationU(); material->textureOffsets[i].y = (float)fileTexture->GetTranslationV(); if (szLastForward != nullptr && szLastForward > szLastBackward) szFilename = szLastForward + 1; else if (szLastBackward != nullptr) szFilename = szLastBackward + 1; std::string fullPath = m_path + szFilename; auto iter = m_textures.find(fullPath); if (iter != m_textures.end()) { material->textures[i] = iter->second; } else { FBXTexture* texture = new FBXTexture(); texture->name = szFilename; texture->path = fullPath; material->textures[i] = texture; m_textures[ fullPath ] = texture; } } } } } m_materials[material->name] = material; m_materialMutex.unlock(); return material; } m_materialMutex.unlock(); return nullptr; } void FBXFile::initialiseOpenGLTextures() { int textureUnit = 0; for (auto texture : m_textures) { // texture.second->handle = SOIL_create_OGL_texture(texture.second->data, texture.second->width, texture.second->height, texture.second->channels, // SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_TEXTURE_REPEATS); switch (texture.second->format) { case STBI_grey: texture.second->format = GL_RED; break; case STBI_grey_alpha: texture.second->format = GL_RG; break; case STBI_rgb: texture.second->format = GL_RGB; break; case STBI_rgb_alpha: texture.second->format = GL_RGBA; break; }; glGenTextures(1, &texture.second->handle); glActiveTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, texture.second->handle); glTexImage2D(GL_TEXTURE_2D, 0, texture.second->format, texture.second->width, texture.second->height, 0, texture.second->format, GL_UNSIGNED_BYTE, texture.second->data); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); } } void FBXFile::extractAnimation(void* a_scene) { FbxScene* fbxScene = (FbxScene*)a_scene; int animStackCount = fbxScene->GetSrcObjectCount<FbxAnimStack>(); std::vector<int> tracks; std::vector<void*> nodes; tracks.reserve(128); nodes.reserve(128); FbxTime frameTime; for (int i = 0; i < animStackCount; i++) { tracks.clear(); nodes.clear(); FbxAnimStack* lAnimStack = fbxScene->GetSrcObject<FbxAnimStack>(i); FBXAnimation* anim = new FBXAnimation(); anim->m_name = lAnimStack->GetName(); // get animated track bone indices and nodes, and calculate start/end frame int nbAnimLayers = lAnimStack->GetMemberCount(FbxCriteria::ObjectType(FbxAnimLayer::ClassId)); for (int j = 0; j < nbAnimLayers; ++j) { FbxAnimLayer* lAnimLayer = lAnimStack->GetMember<FbxAnimLayer>(j); extractAnimationTrack(tracks, lAnimLayer, fbxScene->GetRootNode(), nodes, anim->m_startFrame, anim->m_endFrame); } // frame count (includes start/end frames) unsigned int frameCount = anim->m_endFrame - anim->m_startFrame + 1; // allocate tracks and keyframes anim->m_trackCount = (unsigned int)tracks.size(); anim->m_tracks = new FBXTrack[ anim->m_trackCount ]; for (unsigned int track = 0 ; track < anim->m_trackCount ; ++track ) { anim->m_tracks[track].m_boneIndex = tracks[track]; anim->m_tracks[track].m_keyframeCount = frameCount; anim->m_tracks[track].m_keyframes = new FBXKeyFrame[ frameCount ]; } // evaluate all of the animated track keyframes // loop by frame first to limit FBX time changes (dreadfully slow!) for ( unsigned int frame = 0 ; frame < frameCount ; ++frame ) { frameTime.SetFrame(frame + anim->m_startFrame); for (unsigned int track = 0 ; track < anim->m_trackCount ; ++track ) { FbxAMatrix localMatrix = m_importAssistor->evaluator->GetNodeLocalTransform( (FbxNode*)nodes[ track ], frameTime ); FbxQuaternion R = localMatrix.GetQ(); FbxVector4 T = localMatrix.GetT(); FbxVector4 S = localMatrix.GetS(); anim->m_tracks[track].m_keyframes[ frame ].m_key = frame + anim->m_startFrame; anim->m_tracks[track].m_keyframes[ frame ].m_rotation = glm::quat((float)R[3],(float)R[0],(float)R[1],(float)R[2]); anim->m_tracks[track].m_keyframes[ frame ].m_translation = glm::vec3((float)T[0],(float)T[1],(float)T[2]); anim->m_tracks[track].m_keyframes[ frame ].m_scale = glm::vec3((float)S[0],(float)S[1],(float)S[2]); } } m_animations[ anim->m_name ] = anim; } } void FBXFile::extractAnimationTrack(std::vector<int>& a_tracks, void* a_layer, void* a_node, std::vector<void*>& a_nodes, unsigned int& a_startFrame, unsigned int& a_endFrame) { FbxAnimLayer* fbxAnimLayer = (FbxAnimLayer*)a_layer; FbxNode* fbxNode = (FbxNode*)a_node; // find node index in skeleton int boneIndex = -1; FBXSkeleton* skeleton = m_skeletons[0]; for ( unsigned int i = 0 ; i < skeleton->m_boneCount ; ++i ) { if (skeleton->m_nodes[i]->m_name == fbxNode->GetName()) { boneIndex = i; break; } } // extract bones that have animated properties on them only bool hasKeys = false; FbxAnimCurve* lAnimCurve = nullptr; if (boneIndex >= 0) { // translation lAnimCurve = fbxNode->LclTranslation.GetCurve(fbxAnimLayer, FBXSDK_CURVENODE_COMPONENT_X); if (lAnimCurve) { hasKeys = true; unsigned int frame = (unsigned int)lAnimCurve->KeyGetTime(0).GetFrameCount(); if (frame < a_startFrame) a_startFrame = frame; frame = (unsigned int)lAnimCurve->KeyGetTime(lAnimCurve->KeyGetCount()-1).GetFrameCount(); if (frame > a_endFrame) a_endFrame = frame; } lAnimCurve = fbxNode->LclTranslation.GetCurve(fbxAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y); if (lAnimCurve) { hasKeys = true; unsigned int frame = (unsigned int)lAnimCurve->KeyGetTime(0).GetFrameCount(); if (frame < a_startFrame) a_startFrame = frame; frame = (unsigned int)lAnimCurve->KeyGetTime(lAnimCurve->KeyGetCount()-1).GetFrameCount(); if (frame > a_endFrame) a_endFrame = frame; } lAnimCurve = fbxNode->LclTranslation.GetCurve(fbxAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z); if (lAnimCurve) { hasKeys = true; unsigned int frame = (unsigned int)lAnimCurve->KeyGetTime(0).GetFrameCount(); if (frame < a_startFrame) a_startFrame = frame; frame = (unsigned int)lAnimCurve->KeyGetTime(lAnimCurve->KeyGetCount()-1).GetFrameCount(); if (frame > a_endFrame) a_endFrame = frame; } // rotation lAnimCurve = fbxNode->LclRotation.GetCurve(fbxAnimLayer, FBXSDK_CURVENODE_COMPONENT_X); if (lAnimCurve) { hasKeys = true; unsigned int frame = (unsigned int)lAnimCurve->KeyGetTime(0).GetFrameCount(); if (frame < a_startFrame) a_startFrame = frame; frame = (unsigned int)lAnimCurve->KeyGetTime(lAnimCurve->KeyGetCount()-1).GetFrameCount(); if (frame > a_endFrame) a_endFrame = frame; } lAnimCurve = fbxNode->LclRotation.GetCurve(fbxAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y); if (lAnimCurve) { hasKeys = true; unsigned int frame = (unsigned int)lAnimCurve->KeyGetTime(0).GetFrameCount(); if (frame < a_startFrame) a_startFrame = frame; frame = (unsigned int)lAnimCurve->KeyGetTime(lAnimCurve->KeyGetCount()-1).GetFrameCount(); if (frame > a_endFrame) a_endFrame = frame; } lAnimCurve = fbxNode->LclRotation.GetCurve(fbxAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z); if (lAnimCurve) { hasKeys = true; unsigned int frame = (unsigned int)lAnimCurve->KeyGetTime(0).GetFrameCount(); if (frame < a_startFrame) a_startFrame = frame; frame = (unsigned int)lAnimCurve->KeyGetTime(lAnimCurve->KeyGetCount()-1).GetFrameCount(); if (frame > a_endFrame) a_endFrame = frame; } // scale lAnimCurve = fbxNode->LclScaling.GetCurve(fbxAnimLayer, FBXSDK_CURVENODE_COMPONENT_X); if (lAnimCurve) { hasKeys = true; unsigned int frame = (unsigned int)lAnimCurve->KeyGetTime(0).GetFrameCount(); if (frame < a_startFrame) a_startFrame = frame; frame = (unsigned int)lAnimCurve->KeyGetTime(lAnimCurve->KeyGetCount()-1).GetFrameCount(); if (frame > a_endFrame) a_endFrame = frame; } lAnimCurve = fbxNode->LclScaling.GetCurve(fbxAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y); if (lAnimCurve) { hasKeys = true; unsigned int frame = (unsigned int)lAnimCurve->KeyGetTime(0).GetFrameCount(); if (frame < a_startFrame) a_startFrame = frame; frame = (unsigned int)lAnimCurve->KeyGetTime(lAnimCurve->KeyGetCount()-1).GetFrameCount(); if (frame > a_endFrame) a_endFrame = frame; } lAnimCurve = fbxNode->LclScaling.GetCurve(fbxAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z); if (lAnimCurve) { hasKeys = true; unsigned int frame = (unsigned int)lAnimCurve->KeyGetTime(0).GetFrameCount(); if (frame < a_startFrame) a_startFrame = frame; frame = (unsigned int)lAnimCurve->KeyGetTime(lAnimCurve->KeyGetCount()-1).GetFrameCount(); if (frame > a_endFrame) a_endFrame = frame; } if (hasKeys) { a_nodes.push_back(fbxNode); a_tracks.push_back(boneIndex); } } for (int i = 0; i < fbxNode->GetChildCount(); ++i) { extractAnimationTrack(a_tracks, fbxAnimLayer, fbxNode->GetChild(i), a_nodes, a_startFrame, a_endFrame); } } void FBXFile::extractSkeleton(FBXSkeleton* a_skeleton, void* a_scene) { FbxScene* fbxScene = (FbxScene*)a_scene; int poseCount = fbxScene->GetPoseCount(); for (int i = 0; i < poseCount; ++i) { FbxPose* lPose = fbxScene->GetPose(i); for ( int j = 0 ; j < lPose->GetCount() ; ++j ) { float scaleFactor = m_importAssistor->unitScale; FbxMatrix scale(scaleFactor,0,0,0, 0,scaleFactor,0,0, 0,0,scaleFactor,0, 0,0,0,1); FbxMatrix lMatrix = lPose->GetMatrix(j); FbxMatrix lBindMatrix = lMatrix.Inverse() * scale; for ( unsigned int k = 0 ; k < a_skeleton->m_boneCount ; ++k ) { if (a_skeleton->m_nodes[k]->m_name == lPose->GetNodeName(j).GetCurrentName()) { FbxVector4 row0 = lBindMatrix.GetRow(0); FbxVector4 row1 = lBindMatrix.GetRow(1); FbxVector4 row2 = lBindMatrix.GetRow(2); FbxVector4 row3 = lBindMatrix.GetRow(3); a_skeleton->m_bindPoses[ k ][0] = glm::vec4( (float)row0[0], (float)row0[1], (float)row0[2], (float)row0[3] ); a_skeleton->m_bindPoses[ k ][1] = glm::vec4( (float)row1[0], (float)row1[1], (float)row1[2], (float)row1[3] ); a_skeleton->m_bindPoses[ k ][2] = glm::vec4( (float)row2[0], (float)row2[1], (float)row2[2], (float)row2[3] ); a_skeleton->m_bindPoses[ k ][3] = glm::vec4( (float)row3[0], (float)row3[1], (float)row3[2], (float)row3[3] ); } } } } } void FBXSkeleton::evaluate(const FBXAnimation* a_animation, float a_time, bool a_loop, float a_FPS) { if (a_animation != nullptr) { // determine frame we're on int totalFrames = a_animation->m_endFrame - a_animation->m_startFrame; float animDuration = totalFrames / a_FPS; // get time through frame float frameTime = 0; if (a_loop) frameTime = glm::max(glm::mod(a_time,animDuration),0.0f); else frameTime = glm::min(glm::max(a_time,0.0f),animDuration); const FBXTrack* track = nullptr; const FBXKeyFrame* start = nullptr; const FBXKeyFrame* end = nullptr; for ( unsigned int i = 0 ; i < a_animation->m_trackCount ; ++i ) { track = &(a_animation->m_tracks[i]); start = nullptr; end = nullptr; float startTime, endTime; // determine the two keyframes we're between for ( unsigned int j = 0 ; j < track->m_keyframeCount - 1 ; ++j ) { startTime = (track->m_keyframes[j].m_key - a_animation->m_startFrame) / a_FPS; endTime = (track->m_keyframes[j + 1].m_key - a_animation->m_startFrame) / a_FPS; if (startTime <= frameTime && endTime >= frameTime) { // found? start = &(track->m_keyframes[j]); end = &(track->m_keyframes[j+1]); break; } } // interpolate between them if (start != nullptr && end != nullptr) { float fScale = glm::max(0.0f,glm::min(1.0f,(frameTime - startTime) / (endTime - startTime))); // translation glm::vec3 T = glm::mix(start->m_translation,end->m_translation,fScale); // scale glm::vec3 S = glm::mix(start->m_scale,end->m_scale,fScale); // rotation (quaternion slerp) glm::quat R = glm::normalize(glm::slerp(start->m_rotation,end->m_rotation,fScale)); // build matrix glm::mat4 mRot = glm::mat4_cast( R ); glm::mat4 mScale = glm::scale( S ); glm::mat4 mTranslate = glm::translate( T ); m_nodes[ track->m_boneIndex ]->m_localTransform = mTranslate * mScale * mRot; } } } } void FBXSkeleton::updateBones() { // update bones for ( int i = 0 ; i < (int)m_boneCount ; ++i ) { if ( m_parentIndex[i] == -1 ) m_bones[ i ] = m_nodes[ i ]->m_localTransform; else m_bones[i] = m_bones[ m_parentIndex[ i ] ] * m_nodes[ i ]->m_localTransform; } // combine bind pose for ( int i = 0 ; i < (int)m_boneCount ; ++i ) { m_bones[ i ] = m_bones[ i ] * m_bindPoses[ i ]; } } void FBXFile::calculateTangentsBinormals(std::vector<FBXVertex>& a_vertices, const std::vector<unsigned int>& a_indices) { unsigned int vertexCount = (unsigned int)a_vertices.size(); glm::vec3* tan1 = new glm::vec3[vertexCount * 2]; glm::vec3* tan2 = tan1 + vertexCount; memset(tan1, 0, vertexCount * sizeof(glm::vec3) * 2); unsigned int indexCount = (unsigned int)a_indices.size(); for (unsigned int a = 0; a < indexCount; a += 3) { unsigned int i1 = a_indices[a]; unsigned int i2 = a_indices[a + 1]; unsigned int i3 = a_indices[a + 2]; const glm::vec4& v1 = a_vertices[i1].position; const glm::vec4& v2 = a_vertices[i2].position; const glm::vec4& v3 = a_vertices[i3].position; const glm::vec2& w1 = a_vertices[i1].texCoord1; const glm::vec2& w2 = a_vertices[i2].texCoord1; const glm::vec2& w3 = a_vertices[i3].texCoord1; float x1 = v2.x - v1.x; float x2 = v3.x - v1.x; float y1 = v2.y - v1.y; float y2 = v3.y - v1.y; float z1 = v2.z - v1.z; float z2 = v3.z - v1.z; float s1 = w2.x - w1.x; float s2 = w3.x - w1.x; float t1 = w2.y - w1.y; float t2 = w3.y - w1.y; float t = s1 * t2 - s2 * t1; float r = t == 0 ? 0 : 1.0f / t; glm::vec3 sdir((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); glm::vec3 tdir((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); tan1[i1] += sdir; tan1[i2] += sdir; tan1[i3] += sdir; tan2[i1] += tdir; tan2[i2] += tdir; tan2[i3] += tdir; } for (unsigned int a = 0; a < vertexCount; a++) { const glm::vec3& n = a_vertices[a].normal.xyz(); const glm::vec3& t = tan1[a]; // Gram-Schmidt orthogonalise glm::vec3 p = t - n * glm::dot(n, t); if ( glm::length2(p) != 0 ) { a_vertices[a].tangent = glm::vec4( glm::normalize( p ), 0.0f ); // calculate binormal float sign = glm::dot(glm::cross(n.xyz(), t.xyz()), tan2[a].xyz()) < 0.0f ? -1.0f : 1.0f; a_vertices[a].binormal = glm::vec4(glm::cross(a_vertices[a].normal.xyz(),a_vertices[a].tangent.xyz()) * sign, 0); } } delete[] tan1; } unsigned int FBXFile::nodeCount(FBXNode* a_node) { if (a_node == nullptr) return 0; unsigned int uiCount = 1; for (auto n : a_node->m_children) uiCount += nodeCount(n); return uiCount; } FBXMeshNode* FBXFile::getMeshByName(const char* a_name) { for (auto mesh : m_meshes) if (mesh->m_name == a_name) return mesh; return nullptr; } FBXLightNode* FBXFile::getLightByName(const char* a_name) { auto oIter = m_lights.find(a_name); if (oIter != m_lights.end()) return oIter->second; return nullptr; } FBXCameraNode* FBXFile::getCameraByName(const char* a_name) { auto oIter = m_cameras.find(a_name); if (oIter != m_cameras.end()) return oIter->second; return nullptr; } FBXMaterial* FBXFile::getMaterialByName(const char* a_name) { auto oIter = m_materials.find(a_name); if (oIter != m_materials.end()) return oIter->second; return nullptr; } FBXTexture* FBXFile::getTextureByName(const char* a_name) { auto oIter = m_textures.find(a_name); if (oIter != m_textures.end()) return oIter->second; return nullptr; } FBXAnimation* FBXFile::getAnimationByName(const char* a_name) { auto oIter = m_animations.find(a_name); if (oIter != m_animations.end()) return oIter->second; return nullptr; } FBXLightNode* FBXFile::getLightByIndex(unsigned int a_index) { for (auto t : m_lights) { if (a_index-- == 0) return t.second; } return nullptr; } FBXCameraNode* FBXFile::getCameraByIndex(unsigned int a_index) { for (auto t : m_cameras) { if (a_index-- == 0) return t.second; } return nullptr; } FBXMaterial* FBXFile::getMaterialByIndex(unsigned int a_index) { for (auto t : m_materials) { if (a_index-- == 0) return t.second; } return nullptr; } FBXAnimation* FBXFile::getAnimationByIndex(unsigned int a_index) { for (auto t : m_animations) { if (a_index-- == 0) return t.second; } return nullptr; } FBXTexture* FBXFile::getTextureByIndex(unsigned int a_index) { for (auto t : m_textures) { if (a_index-- == 0) return t.second; } return nullptr; } void FBXFile::gatherBones(void* a_object) { FbxNode* fbxNode = (FbxNode*)a_object; if (fbxNode->GetNodeAttribute() != nullptr && fbxNode->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::eSkeleton) { unsigned int index = (unsigned int)m_importAssistor->boneIndexList.size(); m_importAssistor->boneIndexList[fbxNode->GetName()] = index; } for (int i = 0; i < fbxNode->GetChildCount(); i++) { gatherBones((void*)fbxNode->GetChild(i)); } } void FBXNode::updateGlobalTransform() { if (m_parent != nullptr) m_globalTransform = m_parent->m_globalTransform * m_localTransform; else m_globalTransform = m_localTransform; for (auto child : m_children) child->updateGlobalTransform(); } void FBXCameraNode::updateGlobalTransform() { if (m_parent != nullptr) m_globalTransform = m_parent->m_globalTransform * m_localTransform; else m_globalTransform = m_localTransform; m_viewMatrix = glm::inverse(m_globalTransform); for (auto child : m_children) child->updateGlobalTransform(); } FBXAnimation* FBXAnimation::clone() const { FBXAnimation* copy = new FBXAnimation(); copy->m_name = m_name; copy->m_startFrame = m_startFrame; copy->m_endFrame = m_endFrame; copy->m_trackCount = m_trackCount; copy->m_tracks = new FBXTrack[m_trackCount]; for (unsigned int i = 0; i < m_trackCount; ++i) { copy->m_tracks[i].m_boneIndex = m_tracks[i].m_boneIndex; copy->m_tracks[i].m_keyframeCount = m_tracks[i].m_keyframeCount; copy->m_tracks[i].m_keyframes = new FBXKeyFrame[m_tracks[i].m_keyframeCount]; memcpy(copy->m_tracks[i].m_keyframes, m_tracks[i].m_keyframes, sizeof(FBXKeyFrame) * m_tracks[i].m_keyframeCount); } return copy; }
unlicense
belczyk/robbo
game/scripts/Game/EnvironmentContext.js
7089
(function() { var app, _ref; window.app = (_ref = window.app) != null ? _ref : {}; app = window.app; app.EnvironmentContext = (function() { function EnvironmentContext(eventAggregator, drawingCtx, timer) { var _this = this; this.eventAggregator = eventAggregator; this.drawingCtx = drawingCtx; this.timer = timer; this.keys = 0; this.eventAggregator.subscribe('key-collected', (function() { return _this.keys++; }), this); this.eventAggregator.subscribe('key-used', (function() { return _this.keys--; }), this); this.eventAggregator.subscribe('restart-level', (function() { return _this.keys = 0; }), this); } EnvironmentContext.prototype.delay = function(time, fun) { return this.timer.delay(time, fun); }; EnvironmentContext.prototype.hide = function(x, y) { return this.drawingCtx.clear(x, y); }; EnvironmentContext.prototype.initMap = function(width, height) { var i, j, _i, _ref1, _results; this.width = width; this.height = height; this.map = []; _results = []; for (i = _i = 0, _ref1 = height - 1; 0 <= _ref1 ? _i <= _ref1 : _i >= _ref1; i = 0 <= _ref1 ? ++_i : --_i) { this.map.push([]); _results.push((function() { var _j, _ref2, _results1; _results1 = []; for (j = _j = 0, _ref2 = width - 1; 0 <= _ref2 ? _j <= _ref2 : _j >= _ref2; j = 0 <= _ref2 ? ++_j : --_j) { _results1.push(this.map[i].push(null)); } return _results1; }).call(this)); } return _results; }; EnvironmentContext.prototype.getNNeighbour = function(x, y) { return new app.NNeighbour(this.getObjAt(x, y - 1), this.getObjAt(x, y + 1), this.getObjAt(x + 1, y), this.getObjAt(x - 1, y)); }; EnvironmentContext.prototype.getMNeighbour = function(x, y) { var n; n = this.getNNeighbour(x, y); return new app.MNeighbour(n.N, this.getObjAt(x + 1, y - 1), n.E, this.getObjAt(x + 1, y + 1), n.S, this.getObjAt(x - 1, y + 1), n.W, this.getObjAt(x - 1, y - 1)); }; EnvironmentContext.prototype.getKeysNumber = function() { return this.keys; }; EnvironmentContext.prototype.getRow = function(lineNumber, startingColumn, endingColumn) { var i, ret, _i; if (startingColumn == null) { startingColumn = 0; } if (endingColumn == null) { endingColumn = this.width - 1; } ret = []; for (i = _i = startingColumn; startingColumn <= endingColumn ? _i <= endingColumn : _i >= endingColumn; i = startingColumn <= endingColumn ? ++_i : --_i) { ret.push(this.getObjAt(i, lineNumber)); } return ret; }; EnvironmentContext.prototype.getObjAt = function(x, y) { if (x > this.width - 1 || y > this.height - 1 || x < 0 || y < 0) { return { message: "Outside the map", outsideMap: true, canStepOn: (function() { return false; }), canBlowUp: function() { return false; } }; } return this.map[y][x]; }; EnvironmentContext.prototype.getObjAtD = function(obj, delta) { var x, y; x = delta.x(obj.x); y = delta.y(obj.y); if (x > this.width - 1 || y > this.height - 1 || x < 0 || y < 0) { return { message: "Outside the map", outsideMap: true, canStepOn: (function() { return false; }), canBlowUp: function() { return false; } }; } return this.map[y][x]; }; EnvironmentContext.prototype.setObjAtD = function(objr, delta, obj) { var x, y; x = delta.x(objr.x); y = delta.y(objr.y); this.map[y][x] = obj; if (obj != null) { obj.x = x; obj.y = y; return this.drawingCtx.draw(obj); } else { return this.drawingCtx.clear(x, y); } }; EnvironmentContext.prototype.setObjAt = function(x, y, obj) { this.map[y][x] = obj; if (obj != null) { obj.x = x; obj.y = y; return this.drawingCtx.draw(obj); } else { return this.drawingCtx.clear(x, y); } }; EnvironmentContext.prototype.putObj = function(obj) { if (obj != null) { return this.setObjAt(obj.x, obj.y, obj); } }; EnvironmentContext.prototype.moveObjByD = function(x, y, delta) { var obj; obj = this.getObjAt(x, y); this.setObjAt(x, y, null); return this.setObjAt(delta.x(x), delta.y(y), obj); }; EnvironmentContext.prototype.moveObjBy = function(x, y, dx, dy) { var obj; obj = this.getObjAt(x, y); this.setObjAt(x, y, null); return this.setObjAt(x + dx, y + dy, obj); }; EnvironmentContext.prototype.stepOnD = function(x, y, delta) { var obj; obj = this.getObjAt(x, y); if ((obj != null) && (obj.isMoveable != null) && obj.isMoveable) { if (typeof obj.onPush === "function") { obj.onPush(); } return this.moveObjByD(x, y, delta); } }; EnvironmentContext.prototype.stepOn = function(x, y, dx, dy) { var obj; obj = this.getObjAt(x, y); if ((obj != null) && (obj.isMoveable != null) && obj.isMoveable) { if (typeof obj.onPush === "function") { obj.onPush(); } return this.moveObjBy(x, y, dx, dy); } }; EnvironmentContext.prototype.getRobbo = function() { var cell, row, _i, _j, _len, _len1, _ref1; _ref1 = this.map; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { row = _ref1[_i]; for (_j = 0, _len1 = row.length; _j < _len1; _j++) { cell = row[_j]; if ((cell != null ? cell.isRobbo : void 0) != null) { return cell; } } } }; EnvironmentContext.prototype.objChangedState = function(obj) { return this.drawingCtx.draw(obj); }; EnvironmentContext.prototype.rmObj = function(obj) { return this.setObjAt(obj.x, obj.y, null); }; EnvironmentContext.prototype.getObjName = function(obj) { var funcNameRegex, results; funcNameRegex = /function(.{1,})\(/; results = funcNameRegex.exec(obj.constructor.toString()); if (results && results.length > 1) { return results[1].trim(); } else { return ""; } }; EnvironmentContext.prototype.registerRandomCall = function(obj, fun) { return this.timer.registerRandomCall(obj, fun); }; EnvironmentContext.prototype.unregisterRandomCalls = function(obj) { return this.timer.unregisterRandomCalls(obj); }; EnvironmentContext.prototype.sound = function(name) { var sound, _ref1; sound = $("#audio-" + name).clone()[0]; return (_ref1 = $("#audio-" + name).clone()[0]) != null ? _ref1.play() : void 0; }; return EnvironmentContext; })(); }).call(this);
unlicense
IMSEVIMSE/IMStreamer
IMStreamer.js
4433
// Get extension URL for paths to local files var fullURL = chrome.runtime.getURL("/"); // Create the button and set id and class var IMSgetStream = document.createElement("button"); IMSgetStream.id = 'IMSButton'; IMSgetStream.className = 'titleReviewBarItem'; IMSgetStream.innerHTML = "Watch full movie"; // Create divider to fit design var divider = document.createElement("div"); divider.className = 'divider'; // Append (as child of div) divider and IMSButton to correct class var buttonAppender = document.getElementsByClassName("plot_summary ")[0]; buttonAppender.appendChild(divider); buttonAppender.appendChild(IMSgetStream); // Get current url to extract IMDB tt-link var URL = window.location.href; var IMDBvar = URL.match("title/(.*)/"); // Event handler for button_click IMSgetStream.addEventListener ("click", function() { // Check if videoplayer element exists via unique ID if (document.getElementById("IMSVidContainer")) { // Videoplayer element does exist // Get the modal and change display setting from none to block var modal = document.getElementById('IMSVidContainer'); modal.style.display = "block"; // Fade in modal var OpacityTrack = 0; var OpacityInterval = setInterval(function() { fadeIn() }, 5); function fadeIn() { if (OpacityTrack >= 1) { //Make sure settings are correct when exiting interval modal.style.opacity = 1; modal.style.display = "block"; clearInterval(OpacityInterval); } else { OpacityTrack += 0.05; modal.style.opacity = OpacityTrack; } } } else { // Videoplayer element doesn't exist // Create element for videoplayer var IMSvideoPlayer = document.createElement("div"); //Set ID and class IMSvideoPlayer.id = 'IMSVidContainer'; IMSvideoPlayer.className = 'modal'; // Insert embedded video from vodlocker.to to modal with divs. IMSvideoPlayer.innerHTML='<div class="modal-content"><span class="close">&times;</span><div id="loadingBG" align="center"><iframe src="http://vodlocker.to/embed?i=' + IMDBvar[1] + ' " width="80%" height="720" allowscriptaccess="always" allowfullscreen="true" scrolling="no" frameborder="0"></iframe></div></div>'; // Append IMSvideoPlayer element to top of code var videoAppender = document.getElementsByTagName('html')[0]; videoAppender.prepend(IMSvideoPlayer); // Set background to loading gif if video is slow to load var IMSloading = document.getElementById('loadingBG'); var temp = "url(" + fullURL + "resources/loading.gif) center center no-repeat"; IMSloading.style.background = temp; // Fade in modal var OpacityTrack = 0; var OpacityInterval = setInterval(function() { fadeIn() }, 5); function fadeIn() { if (OpacityTrack >= 1) { IMSvideoPlayer.style.opacity = 1; clearInterval(OpacityInterval); } else { OpacityTrack += 0.05; IMSvideoPlayer.style.opacity = OpacityTrack; } } // Get the modal (legacy) var modal = document.getElementById('IMSVidContainer'); // Get the span element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on span then close the modal span.onclick = function() { // Fade out modal var OpacityTrack = 1; var OpacityInterval = setInterval(function() { fadeOut() }, 20); function fadeOut() { if (OpacityTrack <= 0) { // Make sure settings are correct, display (none) needed for clickthrough modal.style.opacity = 0; modal.style.display = "none"; clearInterval(OpacityInterval); } else { OpacityTrack -= 0.05; modal.style.opacity = OpacityTrack; } } } // When the user clicks anywhere outside of the modal, close it - same as span window.onclick = function(event) { if (event.target == modal) { var OpacityTrack = 1; var OpacityInterval = setInterval(function() { fadeOut() }, 20); function fadeOut() { if (OpacityTrack <= 0) { modal.style.opacity = 0; modal.style.display = "none"; clearInterval(OpacityInterval); } else { OpacityTrack -= 0.05; modal.style.opacity = OpacityTrack; } } } } } });
unlicense
h4ck3rm1k3/federal-election-commission-aggregation-json-2011
objects/cc/a8512e496bc75a239b638fa2601497cc4b962c.js
378
mycallback( {"_record_type": "fec.version.v7_0.TEXT", "FILER COMMITTEE ID NUMBER": "C00461061", "REC TYPE": "TEXT", "TEXT4000": "Total earmarked through conduit PAC limit not affected", "TRANSACTION ID NUMBER": "TINCA8167IDTA636", "_src_file": "2011/20110504/727407.fec_5.yml", "BACK REFERENCE TRAN ID NUMBER": "INCA8167IDTA636", "BACK REFERENCE SCHED / FORM NAME": "SA11AI"});
unlicense
ArtemZ/mcplugin-license
src/groovy/ru/netdedicated/GrailsUtils.java
1456
package ru.netdedicated; import org.codehaus.groovy.grails.commons.DomainClassArtefactHandler; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.GrailsDomainClass; import java.util.ArrayList; import java.util.List; class GrailsUtils { public static Class getDomainClass(String name) throws Exception{ // GrailsApplication application = GAHolder.getGrailsApplication(); // if(application == null) throw new Exception("Application reference is not set"); // GrailsDomainClass domain = (GrailsDomainClass) application.getArtefact(DomainClassArtefactHandler.TYPE, name) ; GrailsDomainClass domain = null; for(GrailsDomainClass dom : listDomainClasses() ){ if(dom.getName().equals(name)){ domain = dom; } } return domain.getClazz(); } public static List<GrailsDomainClass> listDomainClasses() throws Exception{ GrailsApplication application = GAHolder.getGrailsApplication(); if(application == null) throw new Exception("Application reference is not set"); List<GrailsDomainClass> domainClasses = new ArrayList<GrailsDomainClass>(); for (int i = 0, max = application.getArtefacts(DomainClassArtefactHandler.TYPE).length; i < max; i++) { GrailsDomainClass grailsDomainClass = (GrailsDomainClass) application.getArtefacts(DomainClassArtefactHandler.TYPE)[i]; domainClasses.add(grailsDomainClass); } return domainClasses; } }
unlicense
clilystudio/NetBook
allsrc/com/xiaomi/kenai/jbosh/E.java
1273
package com.xiaomi.kenai.jbosh; final class E { static final f a = f.a("accept"); static final f b; static final f c; static final f d; static final f e; static final f f; static final f g; static final f h; static final f i; static final f j; static final f k; static final f l; static final f m; static final f n; static final f o; static final f p; static final f q; static final f r; static final f s; static final f t; static final f u; static { f.a("authid"); b = f.a("ack"); c = f.a("charsets"); d = f.a("condition"); f.a("content"); e = f.a("from"); f = f.a("hold"); g = f.a("inactivity"); f.a("key"); h = f.a("maxpause"); f.a("newkey"); i = f.a("pause"); j = f.a("polling"); k = f.a("report"); l = f.a("requests"); m = f.a("rid"); n = f.a("route"); f.a("secure"); o = f.a("sid"); f.a("stream"); p = f.a("time"); q = f.a("to"); r = f.a("type"); s = f.a("ver"); t = f.a("wait"); u = f.a("http://www.w3.org/XML/1998/namespace", "lang", "xml"); } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.xiaomi.kenai.jbosh.E * JD-Core Version: 0.6.0 */
unlicense
crisisking/skybot
plugins/dotnetpad.py
2209
"dotnetpad.py: by sklnd, because gobiner wouldn't shut up" import urllib.request, urllib.parse, urllib.error from util import hook, http def dotnetpad(lang, code): "Posts a provided snippet of code in a provided langugage to dotnetpad.net" code = code.encode('utf8') params = {'language': lang, 'code': code} try: result = http.get_json( 'https://dotnetpad.net/Skybot', post_data=params, get_method='POST' ) except http.HTTPError: return 'error: unable to connect to dotnetpad' if result['Errors']: return 'First error: %s' % (result['Errors'][0]['ErrorText']) elif result['Output']: return result['Output'].lstrip() else: return 'No output' @hook.command def fs(inp): ".fs -- post a F# code snippet to dotnetpad.net and print the results" return dotnetpad('fsharp', inp) @hook.command def cs(snippet): ".cs -- post a C# code snippet to dotnetpad.net and print the results" file_template = ('using System; ' 'using System.Linq; ' 'using System.Collections.Generic; ' 'using System.Text; ' '%s') class_template = ('public class Default ' '{' ' %s \n' '}') main_template = ('public static void Main(String[] args) ' '{' ' %s \n' '}') # There are probably better ways to do the following, but I'm feeling lazy # if no main is found in the snippet, use the template with Main in it if 'public static void Main' not in snippet: code = main_template % snippet code = class_template % code code = file_template % code # if Main is found, check for class and see if we need to use the # classed template elif 'class' not in snippet: code = class_template % snippet code = file_template % code return 'Error using dotnetpad' # if we found class, then use the barebones template else: code = file_template % snippet return dotnetpad('csharp', code)
unlicense
jcolebrand/hnb
hnb/Controllers/AboutController.cs
299
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace hnb.Controllers { public class AboutController : Controller { public ActionResult Index() { return View (); } } }
unlicense
yoonghan/selfservicedb
src/main/java/com/jaring/jom/store/jdbi/entity/MenuListBean.java
1157
package com.jaring.jom.store.jdbi.entity; import com.jaring.jom.store.jdbi.caches.impl.ImmutableMapper; import com.jaring.jom.store.jdbi.entity.immutable.ImmutableMenuListBean; public class MenuListBean implements ImmutableMapper<ImmutableMenuListBean>{ private Short menuId; private MenuBean menu; private Short level; private Short levelOrder; public Short getMenuId() { return menuId; } public void setMenuId(Short menuId) { this.menuId = menuId; } public Short getLevel() { return level; } public void setLevel(Short level) { this.level = level; } public MenuBean getMenu() { return menu; } public void setMenu(MenuBean menu) { this.menu = menu; } public Short getLevelOrder() { return levelOrder; } public void setLevelOrder(Short levelOrder) { this.levelOrder = levelOrder; } public MenuListBean clone(){ MenuListBean mlb = new MenuListBean(); mlb.setLevel(level); mlb.setLevelOrder(levelOrder); mlb.setMenu(menu); mlb.setMenuId(menuId); return mlb; } @Override public ImmutableMenuListBean mapper() { return new ImmutableMenuListBean(menuId, menu, level, levelOrder); } }
unlicense
jsakamoto/nupkg-selenium-webdriver-geckodriver
test/ProjectAB/ProjectA/program.cs
487
using System; class Program { static void Main() { using (var driver = new OpenQA.Selenium.Firefox.FirefoxDriver(AppDomain.CurrentDomain.BaseDirectory)) { driver.Navigate().GoToUrl("https://www.bing.com/"); driver.FindElementById("sb_form_q").SendKeys("Selenium WebDriver"); driver.FindElementById("sb_form_go").Click(); Console.WriteLine("OK"); Console.ReadKey(intercept: true); } } }
unlicense