code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/** * * Copyright (C) 2006 Lauri Koponen * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * */ package checker; import checker.localization.Locale; public class LogEntry { private static Locale loc = new Locale(); /* log entry priorities */ public final static int ERROR = 1; public final static int VERBOSE = 2; public final static int DEBUG = 3; private final static String levelNames[] = { "", loc.lc("ERROR"), "VERBOSE", "DEBUG" }; /* priority for this log entry */ private int priority; /* description for this log entry */ private String text; /** * Class constructor. Log entry priority and description must be supplied. * * @param priority Priority for this log entry (ERROR, VERBOSE or DEBUG) * @param text Log entry text */ public LogEntry(int priority, String text) { this.priority = priority; this.text = text; } /** * @return Log entry priority */ public int getPriority() { return priority; } /** * @return Log entry text */ public String getText() { return text; } /** * Log entry as a text string */ public String toString() { return levelNames[priority] + ": " + text; } }
PrepETNA2015/OSCL-Reload
Sources/checker-src/checker/LogEntry.java
Java
gpl-3.0
1,855
[![CodeFactor](https://www.codefactor.io/repository/github/vallieremagic/wordconscious/badge/master)](https://www.codefactor.io/repository/github/vallieremagic/wordconscious/overview/master) # WordConscious A simple word game.
ValliereMagic/WordConscious
README.md
Markdown
gpl-3.0
228
/*************************************************************************** * * * This file was automatically generated using idlc.js * * PLEASE DO NOT EDIT!!!! * * * ***************************************************************************/ #ifndef _X509Crl_base_H_ #define _X509Crl_base_H_ /** @author Leo Hoo <lion@9465.net> */ #include "../object.h" namespace fibjs { class Buffer_base; class X509Crl_base : public object_base { DECLARE_CLASS(X509Crl_base); public: // X509Crl_base static result_t _new(obj_ptr<X509Crl_base>& retVal, v8::Local<v8::Object> This = v8::Local<v8::Object>()); virtual result_t load(Buffer_base* derCrl) = 0; virtual result_t load(const char* pemCrl) = 0; virtual result_t loadFile(const char* filename) = 0; virtual result_t dump(v8::Local<v8::Array>& retVal) = 0; virtual result_t clear() = 0; public: template<typename T> static void __new(const T &args); public: static void s__new(const v8::FunctionCallbackInfo<v8::Value>& args); static void s_load(const v8::FunctionCallbackInfo<v8::Value>& args); static void s_loadFile(const v8::FunctionCallbackInfo<v8::Value>& args); static void s_dump(const v8::FunctionCallbackInfo<v8::Value>& args); static void s_clear(const v8::FunctionCallbackInfo<v8::Value>& args); }; } #include "Buffer.h" namespace fibjs { inline ClassInfo& X509Crl_base::class_info() { static ClassData::ClassMethod s_method[] = { {"load", s_load, false}, {"loadFile", s_loadFile, false}, {"dump", s_dump, false}, {"clear", s_clear, false} }; static ClassData s_cd = { "X509Crl", s__new, 4, s_method, 0, NULL, 0, NULL, NULL, NULL, &object_base::class_info() }; static ClassInfo s_ci(s_cd); return s_ci; } inline void X509Crl_base::s__new(const v8::FunctionCallbackInfo<v8::Value>& args) { CONSTRUCT_INIT(); __new(args); } template<typename T>void X509Crl_base::__new(const T& args) { obj_ptr<X509Crl_base> vr; CONSTRUCT_ENTER(0, 0); hr = _new(vr, args.This()); CONSTRUCT_RETURN(); } inline void X509Crl_base::s_load(const v8::FunctionCallbackInfo<v8::Value>& args) { METHOD_INSTANCE(X509Crl_base); METHOD_ENTER(1, 1); ARG(obj_ptr<Buffer_base>, 0); hr = pInst->load(v0); METHOD_OVER(1, 1); ARG(arg_string, 0); hr = pInst->load(v0); METHOD_VOID(); } inline void X509Crl_base::s_loadFile(const v8::FunctionCallbackInfo<v8::Value>& args) { METHOD_INSTANCE(X509Crl_base); METHOD_ENTER(1, 1); ARG(arg_string, 0); hr = pInst->loadFile(v0); METHOD_VOID(); } inline void X509Crl_base::s_dump(const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Local<v8::Array> vr; METHOD_INSTANCE(X509Crl_base); METHOD_ENTER(0, 0); hr = pInst->dump(vr); METHOD_RETURN(); } inline void X509Crl_base::s_clear(const v8::FunctionCallbackInfo<v8::Value>& args) { METHOD_INSTANCE(X509Crl_base); METHOD_ENTER(0, 0); hr = pInst->clear(); METHOD_VOID(); } } #endif
zhangf911/fibjs
fibjs/include/ifs/X509Crl.h
C
gpl-3.0
3,184
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** 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 The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "baseeditordocumentprocessor.h" #include "builtineditordocumentparser.h" #include "cppsourceprocessor.h" #include "cpptoolsplugin.h" #include "cpptoolstestcase.h" #include "editordocumenthandle.h" #include "modelmanagertesthelper.h" #include <coreplugin/documentmanager.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/fileutils.h> #include <coreplugin/testdatadir.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/session.h> #include <cplusplus/LookupContext.h> #include <utils/executeondestruction.h> #include <utils/hostosinfo.h> #include <QDebug> #include <QtTest> #define VERIFY_DOCUMENT_REVISION(document, expectedRevision) \ QVERIFY(document); \ QCOMPARE(document->revision(), expectedRevision); using namespace CppTools; using namespace CppTools::Internal; using namespace CppTools::Tests; using namespace ProjectExplorer; typedef CPlusPlus::Document Document; Q_DECLARE_METATYPE(QList<ProjectFile>) namespace { inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); } class MyTestDataDir : public Core::Tests::TestDataDir { public: MyTestDataDir(const QString &dir) : TestDataDir(_(SRCDIR "/../../../tests/cppmodelmanager/") + dir) {} QString includeDir(bool cleaned = true) const { return directory(_("include"), cleaned); } QString frameworksDir(bool cleaned = true) const { return directory(_("frameworks"), cleaned); } QString fileFromSourcesDir(const QString &fileName) const { return directory(_("sources")) + QLatin1Char('/') + fileName; } }; QStringList toAbsolutePaths(const QStringList &relativePathList, const Tests::TemporaryCopiedDir &temporaryDir) { QStringList result; foreach (const QString &file, relativePathList) result << temporaryDir.absolutePath(file.toUtf8()); return result; } // TODO: When possible, use this helper class in all tests class ProjectCreator { public: ProjectCreator(ModelManagerTestHelper *modelManagerTestHelper) : modelManagerTestHelper(modelManagerTestHelper) {} /// 'files' is expected to be a list of file names that reside in 'dir'. void create(const QString &name, const QString &dir, const QStringList &files) { const MyTestDataDir projectDir(dir); foreach (const QString &file, files) projectFiles << projectDir.file(file); Project *project = modelManagerTestHelper->createProject(name); projectInfo = ProjectInfo(project); ProjectPart::Ptr part(new ProjectPart); part->languageVersion = ProjectPart::CXX14; part->qtVersion = ProjectPart::Qt5; foreach (const QString &file, projectFiles) { ProjectFile projectFile(file, ProjectFile::classify(file)); part->files.append(projectFile); } projectInfo.appendProjectPart(part); projectInfo.finish(); } ModelManagerTestHelper *modelManagerTestHelper; ProjectInfo projectInfo; QStringList projectFiles; }; /// Changes a file on the disk and restores its original contents on destruction class FileChangerAndRestorer { public: FileChangerAndRestorer(const QString &filePath) : m_filePath(filePath) { } ~FileChangerAndRestorer() { restoreContents(); } /// Saves the contents also internally so it can be restored on destruction bool readContents(QByteArray *contents) { Utils::FileReader fileReader; const bool isFetchOk = fileReader.fetch(m_filePath); if (isFetchOk) { m_originalFileContents = fileReader.data(); if (contents) *contents = m_originalFileContents; } return isFetchOk; } bool writeContents(const QByteArray &contents) const { return TestCase::writeFile(m_filePath, contents); } private: void restoreContents() const { TestCase::writeFile(m_filePath, m_originalFileContents); } QByteArray m_originalFileContents; const QString &m_filePath; }; ProjectPart::Ptr projectPartOfEditorDocument(const QString &filePath) { auto *editorDocument = CppModelManager::instance()->cppEditorDocument(filePath); QTC_ASSERT(editorDocument, return ProjectPart::Ptr()); return editorDocument->processor()->parser()->projectPart(); } } // anonymous namespace /// Check: The preprocessor cleans include and framework paths. void CppToolsPlugin::test_modelmanager_paths_are_clean() { ModelManagerTestHelper helper; CppModelManager *mm = CppModelManager::instance(); const MyTestDataDir testDataDir(_("testdata")); Project *project = helper.createProject(_("test_modelmanager_paths_are_clean")); ProjectInfo pi = ProjectInfo(project); typedef ProjectPart::HeaderPath HeaderPath; ProjectPart::Ptr part(new ProjectPart); part->languageVersion = ProjectPart::CXX14; part->qtVersion = ProjectPart::Qt5; part->projectDefines = QByteArray("#define OH_BEHAVE -1\n"); part->headerPaths = QList<HeaderPath>() << HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath) << HeaderPath(testDataDir.frameworksDir(false), HeaderPath::FrameworkPath); pi.appendProjectPart(part); pi.finish(); mm->updateProjectInfo(pi); QList<HeaderPath> headerPaths = mm->headerPaths(); QCOMPARE(headerPaths.size(), 2); QVERIFY(headerPaths.contains(HeaderPath(testDataDir.includeDir(), HeaderPath::IncludePath))); QVERIFY(headerPaths.contains(HeaderPath(testDataDir.frameworksDir(), HeaderPath::FrameworkPath))); } /// Check: Frameworks headers are resolved. void CppToolsPlugin::test_modelmanager_framework_headers() { if (Utils::HostOsInfo::isWindowsHost()) QSKIP("Can't resolve framework soft links on Windows."); ModelManagerTestHelper helper; CppModelManager *mm = CppModelManager::instance(); const MyTestDataDir testDataDir(_("testdata")); Project *project = helper.createProject(_("test_modelmanager_framework_headers")); ProjectInfo pi = ProjectInfo(project); typedef ProjectPart::HeaderPath HeaderPath; ProjectPart::Ptr part(new ProjectPart); part->languageVersion = ProjectPart::CXX14; part->qtVersion = ProjectPart::Qt5; part->projectDefines = QByteArray("#define OH_BEHAVE -1\n"); part->headerPaths = QList<HeaderPath>() << HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath) << HeaderPath(testDataDir.frameworksDir(false), HeaderPath::FrameworkPath); const QString &source = testDataDir.fileFromSourcesDir( _("test_modelmanager_framework_headers.cpp")); part->files << ProjectFile(source, ProjectFile::CXXSource); pi.appendProjectPart(part); pi.finish(); mm->updateProjectInfo(pi).waitForFinished(); QCoreApplication::processEvents(); QVERIFY(mm->snapshot().contains(source)); Document::Ptr doc = mm->document(source); QVERIFY(!doc.isNull()); CPlusPlus::Namespace *ns = doc->globalNamespace(); QVERIFY(ns); QVERIFY(ns->memberCount() > 0); for (unsigned i = 0, ei = ns->memberCount(); i < ei; ++i) { CPlusPlus::Symbol *s = ns->memberAt(i); QVERIFY(s); QVERIFY(s->name()); const CPlusPlus::Identifier *id = s->name()->asNameId(); QVERIFY(id); QByteArray chars = id->chars(); QVERIFY(chars.startsWith("success")); } } /// QTCREATORBUG-9056 /// Check: If the project configuration changes, all project files and their /// includes have to be reparsed. void CppToolsPlugin::test_modelmanager_refresh_also_includes_of_project_files() { ModelManagerTestHelper helper; CppModelManager *mm = CppModelManager::instance(); const MyTestDataDir testDataDir(_("testdata")); const QString testCpp(testDataDir.fileFromSourcesDir(_("test_modelmanager_refresh.cpp"))); const QString testHeader(testDataDir.fileFromSourcesDir( _("test_modelmanager_refresh.h"))); Project *project = helper.createProject( _("test_modelmanager_refresh_also_includes_of_project_files")); ProjectInfo pi = ProjectInfo(project); typedef ProjectPart::HeaderPath HeaderPath; ProjectPart::Ptr part(new ProjectPart); part->languageVersion = ProjectPart::CXX14; part->qtVersion = ProjectPart::Qt5; part->projectDefines = QByteArray("#define OH_BEHAVE -1\n"); part->headerPaths = QList<HeaderPath>() << HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath); part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource)); pi.appendProjectPart(part); pi.finish(); QSet<QString> refreshedFiles = helper.updateProjectInfo(pi); QCOMPARE(refreshedFiles.size(), 1); QVERIFY(refreshedFiles.contains(testCpp)); CPlusPlus::Snapshot snapshot = mm->snapshot(); QVERIFY(snapshot.contains(testHeader)); QVERIFY(snapshot.contains(testCpp)); Document::Ptr headerDocumentBefore = snapshot.document(testHeader); const QList<CPlusPlus::Macro> macrosInHeaderBefore = headerDocumentBefore->definedMacros(); QCOMPARE(macrosInHeaderBefore.size(), 1); QVERIFY(macrosInHeaderBefore.first().name() == "test_modelmanager_refresh_h"); // Introduce a define that will enable another define once the document is reparsed. part->projectDefines = QByteArray("#define TEST_DEFINE 1\n"); pi = ProjectInfo(project); pi.appendProjectPart(part); pi.finish(); refreshedFiles = helper.updateProjectInfo(pi); QCOMPARE(refreshedFiles.size(), 1); QVERIFY(refreshedFiles.contains(testCpp)); snapshot = mm->snapshot(); QVERIFY(snapshot.contains(testHeader)); QVERIFY(snapshot.contains(testCpp)); Document::Ptr headerDocumentAfter = snapshot.document(testHeader); const QList<CPlusPlus::Macro> macrosInHeaderAfter = headerDocumentAfter->definedMacros(); QCOMPARE(macrosInHeaderAfter.size(), 2); QVERIFY(macrosInHeaderAfter.at(0).name() == "test_modelmanager_refresh_h"); QVERIFY(macrosInHeaderAfter.at(1).name() == "TEST_DEFINE_DEFINED"); } /// QTCREATORBUG-9205 /// Check: When reparsing the same files again, no errors occur /// (The CppSourceProcessor's already seen files are properly cleared!). void CppToolsPlugin::test_modelmanager_refresh_several_times() { ModelManagerTestHelper helper; CppModelManager *mm = CppModelManager::instance(); const MyTestDataDir testDataDir(_("testdata_refresh")); const QString testHeader1(testDataDir.file(_("defines.h"))); const QString testHeader2(testDataDir.file(_("header.h"))); const QString testCpp(testDataDir.file(_("source.cpp"))); Project *project = helper.createProject(_("test_modelmanager_refresh_several_times")); ProjectInfo pi = ProjectInfo(project); ProjectPart::Ptr part(new ProjectPart); part->languageVersion = ProjectPart::CXX14; part->qtVersion = ProjectPart::Qt5; part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader)); part->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader)); part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource)); pi.appendProjectPart(part); pi.finish(); mm->updateProjectInfo(pi); CPlusPlus::Snapshot snapshot; QSet<QString> refreshedFiles; CPlusPlus::Document::Ptr document; QByteArray defines = "#define FIRST_DEFINE"; for (int i = 0; i < 2; ++i) { pi = ProjectInfo(project); ProjectPart::Ptr part(new ProjectPart); // Simulate project configuration change by having different defines each time. defines += "\n#define ANOTHER_DEFINE"; part->projectDefines = defines; part->languageVersion = ProjectPart::CXX14; part->qtVersion = ProjectPart::Qt5; part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader)); part->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader)); part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource)); pi.appendProjectPart(part); pi.finish(); refreshedFiles = helper.updateProjectInfo(pi); QCOMPARE(refreshedFiles.size(), 3); QVERIFY(refreshedFiles.contains(testHeader1)); QVERIFY(refreshedFiles.contains(testHeader2)); QVERIFY(refreshedFiles.contains(testCpp)); snapshot = mm->snapshot(); QVERIFY(snapshot.contains(testHeader1)); QVERIFY(snapshot.contains(testHeader2)); QVERIFY(snapshot.contains(testCpp)); // No diagnostic messages expected document = snapshot.document(testHeader1); QVERIFY(document->diagnosticMessages().isEmpty()); document = snapshot.document(testHeader2); QVERIFY(document->diagnosticMessages().isEmpty()); document = snapshot.document(testCpp); QVERIFY(document->diagnosticMessages().isEmpty()); } } /// QTCREATORBUG-9581 /// Check: If nothing has changes, nothing should be reindexed. void CppToolsPlugin::test_modelmanager_refresh_test_for_changes() { ModelManagerTestHelper helper; CppModelManager *mm = CppModelManager::instance(); const MyTestDataDir testDataDir(_("testdata_refresh")); const QString testCpp(testDataDir.file(_("source.cpp"))); Project *project = helper.createProject(_("test_modelmanager_refresh_2")); ProjectInfo pi = ProjectInfo(project); ProjectPart::Ptr part(new ProjectPart); part->languageVersion = ProjectPart::CXX14; part->qtVersion = ProjectPart::Qt5; part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource)); pi.appendProjectPart(part); pi.finish(); // Reindexing triggers a reparsing thread helper.resetRefreshedSourceFiles(); QFuture<void> firstFuture = mm->updateProjectInfo(pi); QVERIFY(firstFuture.isStarted() || firstFuture.isRunning()); firstFuture.waitForFinished(); const QSet<QString> refreshedFiles = helper.waitForRefreshedSourceFiles(); QCOMPARE(refreshedFiles.size(), 1); QVERIFY(refreshedFiles.contains(testCpp)); // No reindexing since nothing has changed QFuture<void> subsequentFuture = mm->updateProjectInfo(pi); QVERIFY(subsequentFuture.isCanceled() && subsequentFuture.isFinished()); } /// Check: (1) Added project files are recognized and parsed. /// Check: (2) Removed project files are recognized and purged from the snapshot. void CppToolsPlugin::test_modelmanager_refresh_added_and_purge_removed() { ModelManagerTestHelper helper; CppModelManager *mm = CppModelManager::instance(); const MyTestDataDir testDataDir(_("testdata_refresh")); const QString testHeader1(testDataDir.file(_("header.h"))); const QString testHeader2(testDataDir.file(_("defines.h"))); const QString testCpp(testDataDir.file(_("source.cpp"))); Project *project = helper.createProject(_("test_modelmanager_refresh_3")); ProjectInfo pi = ProjectInfo(project); ProjectPart::Ptr part(new ProjectPart); part->languageVersion = ProjectPart::CXX14; part->qtVersion = ProjectPart::Qt5; part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource)); part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader)); pi.appendProjectPart(part); pi.finish(); CPlusPlus::Snapshot snapshot; QSet<QString> refreshedFiles; refreshedFiles = helper.updateProjectInfo(pi); QCOMPARE(refreshedFiles.size(), 2); QVERIFY(refreshedFiles.contains(testHeader1)); QVERIFY(refreshedFiles.contains(testCpp)); snapshot = mm->snapshot(); QVERIFY(snapshot.contains(testHeader1)); QVERIFY(snapshot.contains(testCpp)); // Now add testHeader2 and remove testHeader1 pi = ProjectInfo(project); ProjectPart::Ptr newPart(new ProjectPart); newPart->languageVersion = ProjectPart::CXX14; newPart->qtVersion = ProjectPart::Qt5; newPart->files.append(ProjectFile(testCpp, ProjectFile::CXXSource)); newPart->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader)); pi.appendProjectPart(newPart); pi.finish(); refreshedFiles = helper.updateProjectInfo(pi); // Only the added project file was reparsed QCOMPARE(refreshedFiles.size(), 1); QVERIFY(refreshedFiles.contains(testHeader2)); snapshot = mm->snapshot(); QVERIFY(snapshot.contains(testHeader2)); QVERIFY(snapshot.contains(testCpp)); // The removed project file is not anymore in the snapshot QVERIFY(!snapshot.contains(testHeader1)); } /// Check: Timestamp modified files are reparsed if project files are added or removed /// while the project configuration stays the same void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_change() { QFETCH(QString, fileToChange); QFETCH(QStringList, initialProjectFiles); QFETCH(QStringList, finalProjectFiles); Tests::TemporaryCopiedDir temporaryDir( MyTestDataDir(QLatin1String("testdata_refresh2")).path()); fileToChange = temporaryDir.absolutePath(fileToChange.toUtf8()); initialProjectFiles = toAbsolutePaths(initialProjectFiles, temporaryDir); finalProjectFiles = toAbsolutePaths(finalProjectFiles, temporaryDir); ModelManagerTestHelper helper; CppModelManager *mm = CppModelManager::instance(); Project *project = helper.createProject(_("test_modelmanager_refresh_timeStampModified")); ProjectInfo pi = ProjectInfo(project); ProjectPart::Ptr part(new ProjectPart); part->languageVersion = ProjectPart::CXX14; part->qtVersion = ProjectPart::Qt5; foreach (const QString &file, initialProjectFiles) part->files.append(ProjectFile(file, ProjectFile::CXXSource)); pi = ProjectInfo(project); pi.appendProjectPart(part); pi.finish(); Document::Ptr document; CPlusPlus::Snapshot snapshot; QSet<QString> refreshedFiles; refreshedFiles = helper.updateProjectInfo(pi); QCOMPARE(refreshedFiles.size(), initialProjectFiles.size()); snapshot = mm->snapshot(); foreach (const QString &file, initialProjectFiles) { QVERIFY(refreshedFiles.contains(file)); QVERIFY(snapshot.contains(file)); } document = snapshot.document(fileToChange); const QDateTime lastModifiedBefore = document->lastModified(); QCOMPARE(document->globalSymbolCount(), 1U); QCOMPARE(document->globalSymbolAt(0)->name()->identifier()->chars(), "someGlobal"); // Modify the file QTest::qSleep(1000); // Make sure the timestamp is different FileChangerAndRestorer fileChangerAndRestorer(fileToChange); QByteArray originalContents; QVERIFY(fileChangerAndRestorer.readContents(&originalContents)); const QByteArray newFileContentes = originalContents + "\nint addedOtherGlobal;"; QVERIFY(fileChangerAndRestorer.writeContents(newFileContentes)); // Add or remove source file. The configuration stays the same. part->files.clear(); foreach (const QString &file, finalProjectFiles) part->files.append(ProjectFile(file, ProjectFile::CXXSource)); pi = ProjectInfo(project); pi.appendProjectPart(part); pi.finish(); refreshedFiles = helper.updateProjectInfo(pi); QCOMPARE(refreshedFiles.size(), finalProjectFiles.size()); snapshot = mm->snapshot(); foreach (const QString &file, finalProjectFiles) { QVERIFY(refreshedFiles.contains(file)); QVERIFY(snapshot.contains(file)); } document = snapshot.document(fileToChange); const QDateTime lastModifiedAfter = document->lastModified(); QVERIFY(lastModifiedAfter > lastModifiedBefore); QCOMPARE(document->globalSymbolCount(), 2U); QCOMPARE(document->globalSymbolAt(0)->name()->identifier()->chars(), "someGlobal"); QCOMPARE(document->globalSymbolAt(1)->name()->identifier()->chars(), "addedOtherGlobal"); } void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_change_data() { QTest::addColumn<QString>("fileToChange"); QTest::addColumn<QStringList>("initialProjectFiles"); QTest::addColumn<QStringList>("finalProjectFiles"); const QString testCpp = QLatin1String("source.cpp"); const QString testCpp2 = QLatin1String("source2.cpp"); const QString fileToChange = testCpp; const QStringList projectFiles1 = QStringList() << testCpp; const QStringList projectFiles2 = QStringList() << testCpp << testCpp2; // Add a file QTest::newRow("case: add project file") << fileToChange << projectFiles1 << projectFiles2; // Remove a file QTest::newRow("case: remove project file") << fileToChange << projectFiles2 << projectFiles1; } /// Check: If a second project is opened, the code model is still aware of /// files of the first project. void CppToolsPlugin::test_modelmanager_snapshot_after_two_projects() { QSet<QString> refreshedFiles; ModelManagerTestHelper helper; ProjectCreator project1(&helper); ProjectCreator project2(&helper); CppModelManager *mm = CppModelManager::instance(); // Project 1 project1.create(_("test_modelmanager_snapshot_after_two_projects.1"), _("testdata_project1"), QStringList() << _("foo.h") << _("foo.cpp") << _("main.cpp")); refreshedFiles = helper.updateProjectInfo(project1.projectInfo); QCOMPARE(refreshedFiles, project1.projectFiles.toSet()); const int snapshotSizeAfterProject1 = mm->snapshot().size(); foreach (const QString &file, project1.projectFiles) QVERIFY(mm->snapshot().contains(file)); // Project 2 project2.create(_("test_modelmanager_snapshot_after_two_projects.2"), _("testdata_project2"), QStringList() << _("bar.h") << _("bar.cpp") << _("main.cpp")); refreshedFiles = helper.updateProjectInfo(project2.projectInfo); QCOMPARE(refreshedFiles, project2.projectFiles.toSet()); const int snapshotSizeAfterProject2 = mm->snapshot().size(); QVERIFY(snapshotSizeAfterProject2 > snapshotSizeAfterProject1); QVERIFY(snapshotSizeAfterProject2 >= snapshotSizeAfterProject1 + project2.projectFiles.size()); foreach (const QString &file, project1.projectFiles) QVERIFY(mm->snapshot().contains(file)); foreach (const QString &file, project2.projectFiles) QVERIFY(mm->snapshot().contains(file)); } /// Check: (1) For a project with a *.ui file an AbstractEditorSupport object /// is added for the ui_* file. /// Check: (2) The CppSourceProcessor can successfully resolve the ui_* file /// though it might not be actually generated in the build dir. /// void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles() { VerifyCleanCppModelManager verify; TemporaryCopiedDir temporaryDir(MyTestDataDir(QLatin1String("testdata_guiproject1")).path()); QVERIFY(temporaryDir.isValid()); const QString projectFile = temporaryDir.absolutePath("testdata_guiproject1.pro"); ProjectOpenerAndCloser projects; ProjectInfo projectInfo = projects.open(projectFile, /*configureAsExampleProject=*/ true); QVERIFY(projectInfo.isValid()); // Check working copy. // An AbstractEditorSupport object should have been added for the ui_* file. CppModelManager *mm = CppModelManager::instance(); WorkingCopy workingCopy = mm->workingCopy(); QCOMPARE(workingCopy.size(), 2); // mm->configurationFileName() and "ui_*.h" QStringList fileNamesInWorkinCopy; QHashIterator<Utils::FileName, QPair<QByteArray, unsigned> > it = workingCopy.iterator(); while (it.hasNext()) { it.next(); fileNamesInWorkinCopy << Utils::FileName::fromString(it.key().toString()).fileName(); } fileNamesInWorkinCopy.sort(); const QString expectedUiHeaderFileName = _("ui_mainwindow.h"); QCOMPARE(fileNamesInWorkinCopy.at(0), mm->configurationFileName()); QCOMPARE(fileNamesInWorkinCopy.at(1), expectedUiHeaderFileName); // Check CppSourceProcessor / includes. // The CppSourceProcessor is expected to find the ui_* file in the working copy. const QString fileIncludingTheUiFile = temporaryDir.absolutePath("mainwindow.cpp"); while (!mm->snapshot().document(fileIncludingTheUiFile)) QCoreApplication::processEvents(); const CPlusPlus::Snapshot snapshot = mm->snapshot(); const Document::Ptr document = snapshot.document(fileIncludingTheUiFile); QVERIFY(document); const QStringList includedFiles = document->includedFiles(); QCOMPARE(includedFiles.size(), 2); QCOMPARE(Utils::FileName::fromString(includedFiles.at(0)).fileName(), _("mainwindow.h")); QCOMPARE(Utils::FileName::fromString(includedFiles.at(1)).fileName(), _("ui_mainwindow.h")); } /// QTCREATORBUG-9828: Locator shows symbols of closed files /// Check: The garbage collector should be run if the last CppEditor is closed. void CppToolsPlugin::test_modelmanager_gc_if_last_cppeditor_closed() { ModelManagerTestHelper helper; MyTestDataDir testDataDirectory(_("testdata_guiproject1")); const QString file = testDataDirectory.file(_("main.cpp")); CppModelManager *mm = CppModelManager::instance(); helper.resetRefreshedSourceFiles(); // Open a file in the editor QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0); Core::IEditor *editor = Core::EditorManager::openEditor(file); QVERIFY(editor); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QVERIFY(mm->isCppEditor(editor)); QVERIFY(mm->workingCopy().contains(file)); // Wait until the file is refreshed helper.waitForRefreshedSourceFiles(); // Close file/editor Core::EditorManager::closeDocument(editor->document(), /*askAboutModifiedEditors=*/ false); helper.waitForFinishedGc(); // Check: File is removed from the snapshpt QVERIFY(!mm->workingCopy().contains(file)); QVERIFY(!mm->snapshot().contains(file)); } /// Check: Files that are open in the editor are not garbage collected. void CppToolsPlugin::test_modelmanager_dont_gc_opened_files() { ModelManagerTestHelper helper; MyTestDataDir testDataDirectory(_("testdata_guiproject1")); const QString file = testDataDirectory.file(_("main.cpp")); CppModelManager *mm = CppModelManager::instance(); helper.resetRefreshedSourceFiles(); // Open a file in the editor QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0); Core::IEditor *editor = Core::EditorManager::openEditor(file); QVERIFY(editor); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QVERIFY(mm->isCppEditor(editor)); // Wait until the file is refreshed and check whether it is in the working copy helper.waitForRefreshedSourceFiles(); QVERIFY(mm->workingCopy().contains(file)); // Run the garbage collector mm->GC(); // Check: File is still there QVERIFY(mm->workingCopy().contains(file)); QVERIFY(mm->snapshot().contains(file)); // Close editor Core::EditorManager::closeDocument(editor->document()); helper.waitForFinishedGc(); QVERIFY(mm->snapshot().isEmpty()); } namespace { struct EditorCloser { Core::IEditor *editor; EditorCloser(Core::IEditor *editor): editor(editor) {} ~EditorCloser() { using namespace CppTools; if (editor) QVERIFY(Tests::TestCase::closeEditorWithoutGarbageCollectorInvocation(editor)); } }; QString nameOfFirstDeclaration(const Document::Ptr &doc) { if (doc && doc->globalNamespace()) { if (CPlusPlus::Symbol *s = doc->globalSymbolAt(0)) { if (CPlusPlus::Declaration *decl = s->asDeclaration()) { if (const CPlusPlus::Name *name = decl->name()) { if (const CPlusPlus::Identifier *identifier = name->identifier()) return QString::fromUtf8(identifier->chars(), identifier->size()); } } } } return QString(); } } void CppToolsPlugin::test_modelmanager_defines_per_project() { ModelManagerTestHelper helper; MyTestDataDir testDataDirectory(_("testdata_defines")); const QString main1File = testDataDirectory.file(_("main1.cpp")); const QString main2File = testDataDirectory.file(_("main2.cpp")); const QString header = testDataDirectory.file(_("header.h")); CppModelManager *mm = CppModelManager::instance(); Project *project = helper.createProject(_("test_modelmanager_defines_per_project")); typedef ProjectPart::HeaderPath HeaderPath; ProjectPart::Ptr part1(new ProjectPart); part1->projectFile = QLatin1String("project1.projectfile"); part1->files.append(ProjectFile(main1File, ProjectFile::CXXSource)); part1->files.append(ProjectFile(header, ProjectFile::CXXHeader)); part1->languageVersion = ProjectPart::CXX11; part1->qtVersion = ProjectPart::NoQt; part1->projectDefines = QByteArray("#define SUB1\n"); part1->headerPaths = QList<HeaderPath>() << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath); ProjectPart::Ptr part2(new ProjectPart); part2->projectFile = QLatin1String("project1.projectfile"); part2->files.append(ProjectFile(main2File, ProjectFile::CXXSource)); part2->files.append(ProjectFile(header, ProjectFile::CXXHeader)); part2->languageVersion = ProjectPart::CXX11; part2->qtVersion = ProjectPart::NoQt; part2->projectDefines = QByteArray("#define SUB2\n"); part2->headerPaths = QList<HeaderPath>() << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath); ProjectInfo pi = ProjectInfo(project); pi.appendProjectPart(part1); pi.appendProjectPart(part2); pi.finish(); helper.updateProjectInfo(pi); QCOMPARE(mm->snapshot().size(), 4); // Open a file in the editor QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0); struct Data { QString firstDeclarationName; QString fileName; } d[] = { { _("one"), main1File }, { _("two"), main2File } }; const int size = sizeof(d) / sizeof(d[0]); for (int i = 0; i < size; ++i) { const QString firstDeclarationName = d[i].firstDeclarationName; const QString fileName = d[i].fileName; Core::IEditor *editor = Core::EditorManager::openEditor(fileName); EditorCloser closer(editor); QVERIFY(editor); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QVERIFY(mm->isCppEditor(editor)); Document::Ptr doc = mm->document(fileName); QCOMPARE(nameOfFirstDeclaration(doc), firstDeclarationName); } } void CppToolsPlugin::test_modelmanager_precompiled_headers() { ModelManagerTestHelper helper; MyTestDataDir testDataDirectory(_("testdata_defines")); const QString main1File = testDataDirectory.file(_("main1.cpp")); const QString main2File = testDataDirectory.file(_("main2.cpp")); const QString header = testDataDirectory.file(_("header.h")); const QString pch1File = testDataDirectory.file(_("pch1.h")); const QString pch2File = testDataDirectory.file(_("pch2.h")); CppModelManager *mm = CppModelManager::instance(); Project *project = helper.createProject(_("test_modelmanager_defines_per_project_pch")); typedef ProjectPart::HeaderPath HeaderPath; ProjectPart::Ptr part1(new ProjectPart); part1->projectFile = QLatin1String("project1.projectfile"); part1->files.append(ProjectFile(main1File, ProjectFile::CXXSource)); part1->files.append(ProjectFile(header, ProjectFile::CXXHeader)); part1->languageVersion = ProjectPart::CXX11; part1->qtVersion = ProjectPart::NoQt; part1->precompiledHeaders.append(pch1File); part1->headerPaths = QList<HeaderPath>() << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath); ProjectPart::Ptr part2(new ProjectPart); part2->projectFile = QLatin1String("project2.projectfile"); part2->files.append(ProjectFile(main2File, ProjectFile::CXXSource)); part2->files.append(ProjectFile(header, ProjectFile::CXXHeader)); part2->languageVersion = ProjectPart::CXX11; part2->qtVersion = ProjectPart::NoQt; part2->precompiledHeaders.append(pch2File); part2->headerPaths = QList<HeaderPath>() << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath); ProjectInfo pi = ProjectInfo(project); pi.appendProjectPart(part1); pi.appendProjectPart(part2); pi.finish(); helper.updateProjectInfo(pi); QCOMPARE(mm->snapshot().size(), 4); // Open a file in the editor QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0); struct Data { QString firstDeclarationName; QString firstClassInPchFile; QString fileName; } d[] = { { _("one"), _("ClassInPch1"), main1File }, { _("two"), _("ClassInPch2"), main2File } }; const int size = sizeof(d) / sizeof(d[0]); for (int i = 0; i < size; ++i) { const QString firstDeclarationName = d[i].firstDeclarationName; const QByteArray firstClassInPchFile = d[i].firstClassInPchFile.toUtf8(); const QString fileName = d[i].fileName; Core::IEditor *editor = Core::EditorManager::openEditor(fileName); EditorCloser closer(editor); QVERIFY(editor); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QVERIFY(mm->isCppEditor(editor)); auto parser = BuiltinEditorDocumentParser::get(fileName); QVERIFY(parser); BaseEditorDocumentParser::Configuration config = parser->configuration(); config.usePrecompiledHeaders = true; parser->setConfiguration(config); parser->update(CppModelManager::instance()->workingCopy()); // Check if defines from pch are considered Document::Ptr document = mm->document(fileName); QCOMPARE(nameOfFirstDeclaration(document), firstDeclarationName); // Check if declarations from pch are considered CPlusPlus::LookupContext context(document, parser->snapshot()); const CPlusPlus::Identifier *identifier = document->control()->identifier(firstClassInPchFile.data()); const QList<CPlusPlus::LookupItem> results = context.lookup(identifier, document->globalNamespace()); QVERIFY(!results.isEmpty()); QVERIFY(results.first().declaration()->type()->asClassType()); } } void CppToolsPlugin::test_modelmanager_defines_per_editor() { ModelManagerTestHelper helper; MyTestDataDir testDataDirectory(_("testdata_defines")); const QString main1File = testDataDirectory.file(_("main1.cpp")); const QString main2File = testDataDirectory.file(_("main2.cpp")); const QString header = testDataDirectory.file(_("header.h")); CppModelManager *mm = CppModelManager::instance(); Project *project = helper.createProject(_("test_modelmanager_defines_per_editor")); typedef ProjectPart::HeaderPath HeaderPath; ProjectPart::Ptr part1(new ProjectPart); part1->files.append(ProjectFile(main1File, ProjectFile::CXXSource)); part1->files.append(ProjectFile(header, ProjectFile::CXXHeader)); part1->languageVersion = ProjectPart::CXX11; part1->qtVersion = ProjectPart::NoQt; part1->headerPaths = QList<HeaderPath>() << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath); ProjectPart::Ptr part2(new ProjectPart); part2->files.append(ProjectFile(main2File, ProjectFile::CXXSource)); part2->files.append(ProjectFile(header, ProjectFile::CXXHeader)); part2->languageVersion = ProjectPart::CXX11; part2->qtVersion = ProjectPart::NoQt; part2->headerPaths = QList<HeaderPath>() << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath); ProjectInfo pi = ProjectInfo(project); pi.appendProjectPart(part1); pi.appendProjectPart(part2); pi.finish(); helper.updateProjectInfo(pi); QCOMPARE(mm->snapshot().size(), 4); // Open a file in the editor QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0); struct Data { QString editorDefines; QString firstDeclarationName; } d[] = { { _("#define SUB1\n"), _("one") }, { _("#define SUB2\n"), _("two") } }; const int size = sizeof(d) / sizeof(d[0]); for (int i = 0; i < size; ++i) { const QString editorDefines = d[i].editorDefines; const QString firstDeclarationName = d[i].firstDeclarationName; Core::IEditor *editor = Core::EditorManager::openEditor(main1File); EditorCloser closer(editor); QVERIFY(editor); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QVERIFY(mm->isCppEditor(editor)); const QString filePath = editor->document()->filePath().toString(); const auto parser = BaseEditorDocumentParser::get(filePath); BaseEditorDocumentParser::Configuration config = parser->configuration(); config.editorDefines = editorDefines.toUtf8(); parser->setConfiguration(config); parser->update(CppModelManager::instance()->workingCopy()); Document::Ptr doc = mm->document(main1File); QCOMPARE(nameOfFirstDeclaration(doc), firstDeclarationName); } } void CppToolsPlugin::test_modelmanager_updateEditorsAfterProjectUpdate() { ModelManagerTestHelper helper; MyTestDataDir testDataDirectory(_("testdata_defines")); const QString fileA = testDataDirectory.file(_("main1.cpp")); // content not relevant const QString fileB = testDataDirectory.file(_("main2.cpp")); // content not relevant // Open file A in editor Core::IEditor *editorA = Core::EditorManager::openEditor(fileA); QVERIFY(editorA); EditorCloser closerA(editorA); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QVERIFY(TestCase::waitForProcessedEditorDocument(fileA)); ProjectPart::Ptr documentAProjectPart = projectPartOfEditorDocument(fileA); QVERIFY(!documentAProjectPart->project); // Open file B in editor Core::IEditor *editorB = Core::EditorManager::openEditor(fileB); QVERIFY(editorB); EditorCloser closerB(editorB); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 2); QVERIFY(TestCase::waitForProcessedEditorDocument(fileB)); ProjectPart::Ptr documentBProjectPart = projectPartOfEditorDocument(fileB); QVERIFY(!documentBProjectPart->project); // Switch back to document A Core::EditorManager::activateEditor(editorA); // Open/update related project Project *project = helper.createProject(_("test_modelmanager_updateEditorsAfterProjectUpdate")); ProjectPart::Ptr part(new ProjectPart); part->project = project; part->files.append(ProjectFile(fileA, ProjectFile::CXXSource)); part->files.append(ProjectFile(fileB, ProjectFile::CXXSource)); part->languageVersion = ProjectPart::CXX11; part->qtVersion = ProjectPart::NoQt; ProjectInfo pi = ProjectInfo(project); pi.appendProjectPart(part); pi.finish(); helper.updateProjectInfo(pi); // ... and check for updated editor document A QVERIFY(TestCase::waitForProcessedEditorDocument(fileA)); documentAProjectPart = projectPartOfEditorDocument(fileA); QCOMPARE(documentAProjectPart->project, project); // Switch back to document B and check if that's updated, too Core::EditorManager::activateEditor(editorB); QVERIFY(TestCase::waitForProcessedEditorDocument(fileB)); documentBProjectPart = projectPartOfEditorDocument(fileB); QCOMPARE(documentBProjectPart->project, project); } void CppToolsPlugin::test_modelmanager_renameIncludes() { struct ModelManagerGCHelper { ~ModelManagerGCHelper() { CppModelManager::instance()->GC(); } } GCHelper; Q_UNUSED(GCHelper); // do not warn about being unused TemporaryDir tmpDir; QVERIFY(tmpDir.isValid()); const QDir workingDir(tmpDir.path()); const QStringList fileNames = QStringList() << _("foo.h") << _("foo.cpp") << _("main.cpp"); const QString oldHeader(workingDir.filePath(_("foo.h"))); const QString newHeader(workingDir.filePath(_("bar.h"))); CppModelManager *modelManager = CppModelManager::instance(); const MyTestDataDir testDir(_("testdata_project1")); // Copy test files to a temporary directory QSet<QString> sourceFiles; foreach (const QString &fileName, fileNames) { const QString &file = workingDir.filePath(fileName); QVERIFY(QFile::copy(testDir.file(fileName), file)); // Saving source file names for the model manager update, // so we can update just the relevant files. if (ProjectFile::classify(file) == ProjectFile::CXXSource) sourceFiles.insert(file); } // Update the c++ model manager and check for the old includes modelManager->updateSourceFiles(sourceFiles).waitForFinished(); QCoreApplication::processEvents(); CPlusPlus::Snapshot snapshot = modelManager->snapshot(); foreach (const QString &sourceFile, sourceFiles) QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QSet<QString>() << oldHeader); // Renaming the header QVERIFY(Core::FileUtils::renameFile(oldHeader, newHeader)); // Update the c++ model manager again and check for the new includes modelManager->updateSourceFiles(sourceFiles).waitForFinished(); QCoreApplication::processEvents(); snapshot = modelManager->snapshot(); foreach (const QString &sourceFile, sourceFiles) QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QSet<QString>() << newHeader); } void CppToolsPlugin::test_modelmanager_renameIncludesInEditor() { struct ModelManagerGCHelper { ~ModelManagerGCHelper() { CppModelManager::instance()->GC(); } } GCHelper; Q_UNUSED(GCHelper); // do not warn about being unused TemporaryDir tmpDir; QVERIFY(tmpDir.isValid()); const QDir workingDir(tmpDir.path()); const QStringList fileNames = QStringList() << _("foo.h") << _("foo.cpp") << _("main.cpp"); const QString oldHeader(workingDir.filePath(_("foo.h"))); const QString newHeader(workingDir.filePath(_("bar.h"))); const QString mainFile(workingDir.filePath(_("main.cpp"))); CppModelManager *modelManager = CppModelManager::instance(); const MyTestDataDir testDir(_("testdata_project1")); ModelManagerTestHelper helper; helper.resetRefreshedSourceFiles(); // Copy test files to a temporary directory QSet<QString> sourceFiles; foreach (const QString &fileName, fileNames) { const QString &file = workingDir.filePath(fileName); QVERIFY(QFile::copy(testDir.file(fileName), file)); // Saving source file names for the model manager update, // so we can update just the relevant files. if (ProjectFile::classify(file) == ProjectFile::CXXSource) sourceFiles.insert(file); } // Update the c++ model manager and check for the old includes modelManager->updateSourceFiles(sourceFiles).waitForFinished(); QCoreApplication::processEvents(); CPlusPlus::Snapshot snapshot = modelManager->snapshot(); foreach (const QString &sourceFile, sourceFiles) QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QSet<QString>() << oldHeader); // Open a file in the editor QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0); Core::IEditor *editor = Core::EditorManager::openEditor(mainFile); QVERIFY(editor); EditorCloser editorCloser(editor); Utils::ExecuteOnDestruction saveAllFiles([](){ Core::DocumentManager::saveAllModifiedDocumentsSilently(); }); QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1); QVERIFY(modelManager->isCppEditor(editor)); QVERIFY(modelManager->workingCopy().contains(mainFile)); // Renaming the header QVERIFY(Core::FileUtils::renameFile(oldHeader, newHeader)); // Update the c++ model manager again and check for the new includes TestCase::waitForProcessedEditorDocument(mainFile); modelManager->updateSourceFiles(sourceFiles).waitForFinished(); QCoreApplication::processEvents(); snapshot = modelManager->snapshot(); foreach (const QString &sourceFile, sourceFiles) QCOMPARE(snapshot.allIncludesForDocument(sourceFile), QSet<QString>() << newHeader); } void CppToolsPlugin::test_modelmanager_documentsAndRevisions() { TestCase helper; // Index two files const MyTestDataDir testDir(_("testdata_project1")); const QString filePath1 = testDir.file(QLatin1String("foo.h")); const QString filePath2 = testDir.file(QLatin1String("foo.cpp")); const QSet<QString> filesToIndex = QSet<QString>() << filePath1 << filePath2; QVERIFY(TestCase::parseFiles(filesToIndex)); CppModelManager *modelManager = CppModelManager::instance(); VERIFY_DOCUMENT_REVISION(modelManager->document(filePath1), 1U); VERIFY_DOCUMENT_REVISION(modelManager->document(filePath2), 1U); // Open editor for file 1 TextEditor::BaseTextEditor *editor1; QVERIFY(helper.openBaseTextEditor(filePath1, &editor1)); helper.closeEditorAtEndOfTestCase(editor1); QVERIFY(TestCase::waitForProcessedEditorDocument(filePath1)); VERIFY_DOCUMENT_REVISION(modelManager->document(filePath1), 2U); VERIFY_DOCUMENT_REVISION(modelManager->document(filePath2), 1U); // Index again QVERIFY(TestCase::parseFiles(filesToIndex)); VERIFY_DOCUMENT_REVISION(modelManager->document(filePath1), 3U); VERIFY_DOCUMENT_REVISION(modelManager->document(filePath2), 2U); // Open editor for file 2 TextEditor::BaseTextEditor *editor2; QVERIFY(helper.openBaseTextEditor(filePath2, &editor2)); helper.closeEditorAtEndOfTestCase(editor2); QVERIFY(TestCase::waitForProcessedEditorDocument(filePath2)); VERIFY_DOCUMENT_REVISION(modelManager->document(filePath1), 3U); VERIFY_DOCUMENT_REVISION(modelManager->document(filePath2), 3U); // Index again QVERIFY(TestCase::parseFiles(filesToIndex)); VERIFY_DOCUMENT_REVISION(modelManager->document(filePath1), 4U); VERIFY_DOCUMENT_REVISION(modelManager->document(filePath2), 4U); }
frostasm/qt-creator
src/plugins/cpptools/cppmodelmanager_test.cpp
C++
gpl-3.0
48,022
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - Events</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../families.html" title="Families">Families</a></li> <li class = "CurrentSection"><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="EventDetail"> <h3>Birth</h3> <table class="infolist eventlist"> <tbody> <tr> <td class="ColumnAttribute">Gramps ID</td> <td class="ColumnGRAMPSID">E18216</td> </tr> <tr> <td class="ColumnAttribute">Date</td> <td class="ColumnColumnDate"> 1853 </td> </tr> <tr> <td class="ColumnAttribute">Place</td> <td class="ColumnColumnPlace"> <a href="../../../plc/1/b/d15f6092f15267f83f3f3dd29b1.html" title=""> </a> </td> </tr> </tbody> </table> <div class="subsection" id="references"> <h4>References</h4> <ol class="Col1" role="Volume-n-Page"type = 1> <li> <a href="../../../ppl/8/0/d15f6092f032b1f6ed24b34d408.html"> ELDRIDGE, Alice <span class="grampsid"> [I18015]</span> </a> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:27<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
RossGammon/the-gammons.net
RossFamilyTree/evt/5/3/d15f6092f1075ffa0bdb8cc0b35.html
HTML
gpl-3.0
2,907
sonic = {} sonic.animations={} function create_hill(start_y,end_y,length) hill = {} -- a hill is an object hill.start_y = start_y hill.end_y = end_y hill.length = length return hill end function create_level(total_width,max_height,min_height) level = {} level.hills={} remaining_width_to_fill = total_width hill_start = love.math.random(min_height,max_height) -- create as many hills as we need to fill the level width while remaining_width_to_fill > 0 do hill_length= love.math.random(50,300) hill_end = love.math.random(min_height,max_height) the_hill=create_hill(hill_start,hill_end,hill_length) level.hills[#level.hills+1] = the_hill-- # means the position of the last thing in our bag / table remaining_width_to_fill = remaining_width_to_fill - the_hill.length -- we consumed length pixels of the level length hill_start=hill_end end return level end -- an animation is an object with several properties function create_animation (w , h, x , y , s_x, steps,name,into,fps) anim= {} -- create an object anim.steps=steps -- how many steps? anim.sprite_width=w -- size of each frame anim.sprite_height=h -- height of each frame anim.x_margin=x -- x start position of the animation im our sprite sheet anim.y_margin=y -- y start position "" "" "" anim.space_x=s_x -- x spa anim.slices={} -- slices array anim.fps=fps -- frames per second anim.name=name -- name into[name]=anim -- load it into something end current_index = 1 function load_slice(image,position_in_line,animation) return love.graphics.newQuad( animation.x_margin + ((animation.sprite_width + animation.space_x)*(position_in_line-1)), -- left animation.y_margin, -- top animation.sprite_width, -- width animation.sprite_height, -- height image:getDimensions()) -- never changes end function load_animation (animation) for i = 1,animation.steps do animation.slices[i]= load_slice(sonic.image,i,animation) end end function love.load() if arg[#arg] == "-debug" then require("mobdebug").start() end sonic.image = love.graphics.newImage("sonic2.png") create_animation (42,40 ,8 ,62, 2,7,"walk",sonic.animations,13) create_animation (36,40 ,400 ,62, 4,3,"run",sonic.animations,20) create_animation (36,40 ,8 ,15, 4,3,"stand",sonic.animations,1) create_animation (36,40 ,198 ,15, 4,5,"idle",sonic.animations,1) for name,anim in pairs (sonic.animations) do load_animation(anim) end change_animation(sonic.animations.idle) -- load the level the_level = create_level(1200,500,100) end function change_animation(to_anim) sonic.animation=to_anim current_index=1 -- reset the frame counter time_to_change=love.timer.getTime() + (1/to_anim.fps) -- also reschedule the animation timer end function love.update(dt) time = love.timer.getTime( ) -- get the time if(time >= time_to_change) then current_index = current_index + 1 if ( current_index > #sonic.animation.slices) then current_index = 1 end time_to_change = time + (1/sonic.animation.fps) end if(love.keyboard.isDown("r")) then change_animation(sonic.animations.run) end if(love.keyboard.isDown("w")) then change_animation(sonic.animations.walk) end if(love.keyboard.isDown("s")) then change_animation(sonic.animations.stand) end if(love.keyboard.isDown("i")) then change_animation(sonic.animations.idle) end end function love.draw() window_width,window_height = love.graphics.getDimensions() slice=sonic.animation.slices[current_index] love.graphics.draw(sonic.image,slice,100,300) hill_x=0 for i,hill in ipairs( the_level.hills) do love.graphics.line(hill_x,hill.start_y,hill_x+hill.length ,hill.end_y) hill_x = hill_x + hill.length end end
palad1/Yannicks-s-game
3-level/main.lua
Lua
gpl-3.0
3,940
package hu.unideb.inf.aknakeresog.Controller; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MainApp extends Application { private static Logger logger = (Logger) LoggerFactory.getLogger(MainApp.class); public static String userName = "Annonymous"; public static int bombs = 25; @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("/fxml/MainMenuScene.fxml")); logger.info("A jatek elindult!"); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage.setTitle("Aknakereső 1.0"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
sferenc/Progtech
src/main/java/hu/unideb/inf/aknakeresog/Controller/MainApp.java
Java
gpl-3.0
1,045
/* This file is part of Chummer5a. * * Chummer5a 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. * * Chummer5a 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 Chummer5a. If not, see <http://www.gnu.org/licenses/>. * * You can obtain the full source code for Chummer5a at * https://github.com/chummer5a/chummer5a */ using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Forms; using System.Xml; using System.Xml.XPath; using Chummer.Backend.Equipment; using Chummer.Skills; using MessageBox = System.Windows.Forms.MessageBox; namespace Chummer { public partial class frmKarmaMetatype : Form { private readonly Character _objCharacter; private string _strXmlFile = "metatypes.xml"; private readonly List<ListItem> _lstCategory = new List<ListItem>(); #region Character Events private void objCharacter_MAGEnabledChanged(object sender) { // Do nothing. This is just an Event trap so an exception doesn't get thrown. } private void objCharacter_RESEnabledChanged(object sender) { // Do nothing. This is just an Event trap so an exception doesn't get thrown. } private void objCharacter_DEPEnabledChanged(object sender) { // Do nothing. This is just an Event trap so an exception doesn't get thrown. } private void objCharacter_AdeptTabEnabledChanged(object sender) { // Do nothing. This is just an Event trap so an exception doesn't get thrown. } private void objCharacter_MagicianTabEnabledChanged(object sender) { // Do nothing. This is just an Event trap so an exception doesn't get thrown. } private void objCharacter_TechnomancerTabEnabledChanged(object sender) { // Do nothing. This is just an Event trap so an exception doesn't get thrown. } private void objCharacter_AdvancedProgramsTabEnabledChanged(object sender) { // Do nothing. This is just an Event trap so an exception doesn't get thrown. } private void objCharacter_CyberwareTabDisabledChanged(object sender) { // Do nothing. This is just an Event trap so an exception doesn't get thrown. } private void objCharacter_InitiationTabEnabledChanged(object sender) { // Do nothing. This is just an Event trap so an exception doesn't get thrown. } private void objCharacter_CritterTabEnabledChanged(object sender) { // Do nothing. This is just an Event trap so an exception doesn't get thrown. } #endregion #region Properties /// <summary> /// XML file to read Metatype/Critter information from. /// </summary> public string XmlFile { set { _strXmlFile = value; } } #endregion #region Form Events public frmKarmaMetatype(Character objCharacter) { _objCharacter = objCharacter; InitializeComponent(); LanguageManager.Instance.Load(GlobalOptions.Instance.Language, this); // Attach EventHandlers for MAGEnabledChange and RESEnabledChanged since some Metatypes can enable these. _objCharacter.MAGEnabledChanged += objCharacter_MAGEnabledChanged; _objCharacter.RESEnabledChanged += objCharacter_RESEnabledChanged; _objCharacter.DEPEnabledChanged += objCharacter_DEPEnabledChanged; _objCharacter.AdeptTabEnabledChanged += objCharacter_AdeptTabEnabledChanged; _objCharacter.MagicianTabEnabledChanged += objCharacter_MagicianTabEnabledChanged; _objCharacter.TechnomancerTabEnabledChanged += objCharacter_TechnomancerTabEnabledChanged; _objCharacter.AdvancedProgramsTabEnabledChanged += objCharacter_AdvancedProgramsTabEnabledChanged; _objCharacter.CyberwareTabDisabledChanged += objCharacter_CyberwareTabDisabledChanged; _objCharacter.InitiationTabEnabledChanged += objCharacter_InitiationTabEnabledChanged; _objCharacter.CritterTabEnabledChanged += objCharacter_CritterTabEnabledChanged; } private void frmMetatype_FormClosed(object sender, FormClosedEventArgs e) { // Detach EventHandlers for MAGEnabledChange and RESEnabledChanged since some Metatypes can enable these. _objCharacter.MAGEnabledChanged -= objCharacter_MAGEnabledChanged; _objCharacter.RESEnabledChanged -= objCharacter_RESEnabledChanged; _objCharacter.DEPEnabledChanged -= objCharacter_DEPEnabledChanged; _objCharacter.AdeptTabEnabledChanged -= objCharacter_AdeptTabEnabledChanged; _objCharacter.MagicianTabEnabledChanged -= objCharacter_MagicianTabEnabledChanged; _objCharacter.TechnomancerTabEnabledChanged -= objCharacter_TechnomancerTabEnabledChanged; _objCharacter.AdvancedProgramsTabEnabledChanged -= objCharacter_AdvancedProgramsTabEnabledChanged; _objCharacter.CyberwareTabDisabledChanged -= objCharacter_CyberwareTabDisabledChanged; _objCharacter.InitiationTabEnabledChanged -= objCharacter_InitiationTabEnabledChanged; _objCharacter.CritterTabEnabledChanged -= objCharacter_CritterTabEnabledChanged; } private void frmMetatype_Load(object sender, EventArgs e) { // Load the Metatype information. XmlDocument objXmlDocument = XmlManager.Instance.Load(_strXmlFile); // Populate the Metatype Category list. XmlNodeList objXmlCategoryList = objXmlDocument.SelectNodes("/chummer/categories/category"); // Create a list of any Categories that should not be in the list. List<string> lstRemoveCategory = new List<string>(); foreach (XmlNode objXmlCategory in objXmlCategoryList) { bool blnRemoveItem = true; string strXPath = "/chummer/metatypes/metatype[category = \"" + objXmlCategory.InnerText + "\" and (" + _objCharacter.Options.BookXPath() + ")]"; XmlNodeList objItems = objXmlDocument.SelectNodes(strXPath); if (objItems.Count > 0) blnRemoveItem = false; if (blnRemoveItem) lstRemoveCategory.Add(objXmlCategory.InnerText); } foreach (XmlNode objXmlCategory in objXmlCategoryList) { // Make sure the Category isn't in the exclusion list. bool blnAddItem = true; foreach (string strCategory in lstRemoveCategory) { if (strCategory == objXmlCategory.InnerText) blnAddItem = false; } // Also make sure it is not already in the Category list. foreach (ListItem objItem in _lstCategory) { if (objItem.Value == objXmlCategory.InnerText) blnAddItem = false; } if (blnAddItem) { ListItem objItem = new ListItem(); objItem.Value = objXmlCategory.InnerText; if (objXmlCategory.Attributes != null) { objItem.Name = objXmlCategory.Attributes["translate"]?.InnerText ?? objXmlCategory.InnerText; } else objItem.Name = objXmlCategory.InnerXml; _lstCategory.Add(objItem); } } SortListItem objSort = new SortListItem(); _lstCategory.Sort(objSort.Compare); cboCategory.BeginUpdate(); cboCategory.ValueMember = "Value"; cboCategory.DisplayMember = "Name"; cboCategory.DataSource = _lstCategory; // Attempt to select the default Metahuman Category. If it could not be found, select the first item in the list instead. if (cboCategory.Items.Contains("Metahuman")) { cboCategory.SelectedValue = "Metahuman"; } else { cboCategory.SelectedIndex = 0; } if (cboCategory.Items.Contains("Human")) { lstMetatypes.SelectedValue = "Human"; } else { cboCategory.SelectedIndex = 0; } cboCategory.EndUpdate(); Height = cmdOK.Bottom + 40; lstMetatypes.Height = cmdOK.Bottom - lstMetatypes.Top; // Add Possession and Inhabitation to the list of Critter Tradition variations. tipTooltip.SetToolTip(chkPossessionBased, LanguageManager.Instance.GetString("Tip_Metatype_PossessionTradition")); tipTooltip.SetToolTip(chkBloodSpirit, LanguageManager.Instance.GetString("Tip_Metatype_BloodSpirit")); objXmlDocument = XmlManager.Instance.Load("critterpowers.xml"); XmlNode objXmlPossession = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"Possession\"]"); XmlNode objXmlInhabitation = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"Inhabitation\"]"); List<ListItem> lstMethods = new List<ListItem>(); ListItem objPossession = new ListItem(); objPossession.Value = "Possession"; objPossession.Name = objXmlPossession["translate"]?.InnerText ?? objXmlPossession["name"].InnerText; ListItem objInhabitation = new ListItem(); objInhabitation.Value = "Inhabitation"; objInhabitation.Name = objXmlInhabitation["translate"]?.InnerText ?? objXmlInhabitation["name"].InnerText; lstMethods.Add(objInhabitation); lstMethods.Add(objPossession); SortListItem objSortPossession = new SortListItem(); lstMethods.Sort(objSortPossession.Compare); cboPossessionMethod.BeginUpdate(); cboPossessionMethod.ValueMember = "Value"; cboPossessionMethod.DisplayMember = "Name"; cboPossessionMethod.DataSource = lstMethods; cboPossessionMethod.SelectedIndex = cboPossessionMethod.FindStringExact(objPossession.Name); cboPossessionMethod.EndUpdate(); PopulateMetatypes(); } #endregion #region Control Events private void lstMetatypes_SelectedIndexChanged(object sender, EventArgs e) { // Don't attempt to do anything if nothing is selected. if (!string.IsNullOrEmpty(lstMetatypes.Text)) { XmlDocument objXmlDocument = XmlManager.Instance.Load(_strXmlFile); XmlDocument objXmlQualityDocument = XmlManager.Instance.Load("qualities.xml"); XmlNode objXmlMetatype = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + lstMetatypes.SelectedValue + "\"]"); lblBP.Text = objXmlMetatype["karma"].InnerText; if (objXmlMetatype["forcecreature"] == null) { lblBOD.Text = string.Format("{0}/{1} ({2})", objXmlMetatype["bodmin"].InnerText, objXmlMetatype["bodmax"].InnerText, objXmlMetatype["bodaug"].InnerText); lblAGI.Text = string.Format("{0}/{1} ({2})", objXmlMetatype["agimin"].InnerText, objXmlMetatype["agimax"].InnerText, objXmlMetatype["agiaug"].InnerText); lblREA.Text = string.Format("{0}/{1} ({2})", objXmlMetatype["reamin"].InnerText, objXmlMetatype["reamax"].InnerText, objXmlMetatype["reaaug"].InnerText); lblSTR.Text = string.Format("{0}/{1} ({2})", objXmlMetatype["strmin"].InnerText, objXmlMetatype["strmax"].InnerText, objXmlMetatype["straug"].InnerText); lblCHA.Text = string.Format("{0}/{1} ({2})", objXmlMetatype["chamin"].InnerText, objXmlMetatype["chamax"].InnerText, objXmlMetatype["chaaug"].InnerText); lblINT.Text = string.Format("{0}/{1} ({2})", objXmlMetatype["intmin"].InnerText, objXmlMetatype["intmax"].InnerText, objXmlMetatype["intaug"].InnerText); lblLOG.Text = string.Format("{0}/{1} ({2})", objXmlMetatype["logmin"].InnerText, objXmlMetatype["logmax"].InnerText, objXmlMetatype["logaug"].InnerText); lblWIL.Text = string.Format("{0}/{1} ({2})", objXmlMetatype["wilmin"].InnerText, objXmlMetatype["wilmax"].InnerText, objXmlMetatype["wilaug"].InnerText); lblINI.Text = string.Format("{0}/{1} ({2})", objXmlMetatype["inimin"].InnerText, objXmlMetatype["inimax"].InnerText, objXmlMetatype["iniaug"].InnerText); } else { lblBOD.Text = objXmlMetatype["bodmin"].InnerText; lblAGI.Text = objXmlMetatype["agimin"].InnerText; lblREA.Text = objXmlMetatype["reamin"].InnerText; lblSTR.Text = objXmlMetatype["strmin"].InnerText; lblCHA.Text = objXmlMetatype["chamin"].InnerText; lblINT.Text = objXmlMetatype["intmin"].InnerText; lblLOG.Text = objXmlMetatype["logmin"].InnerText; lblWIL.Text = objXmlMetatype["wilmin"].InnerText; lblINI.Text = objXmlMetatype["inimin"].InnerText; } List<ListItem> lstMetavariants = new List<ListItem>(); ListItem objNone = new ListItem(); objNone.Value = "None"; objNone.Name = LanguageManager.Instance.GetString("String_None"); lstMetavariants.Add(objNone); // Retrieve the list of Metavariants for the selected Metatype. XmlNodeList objXmlMetavariantList = objXmlMetatype.SelectNodes("metavariants/metavariant[" + _objCharacter.Options.BookXPath() + "]"); foreach (XmlNode objXmlMetavariant in objXmlMetavariantList) { ListItem objMetavariant = new ListItem(); objMetavariant.Value = objXmlMetavariant["name"].InnerText; objMetavariant.Name = objXmlMetavariant["translate"]?.InnerText ?? objXmlMetavariant["name"].InnerText; lstMetavariants.Add(objMetavariant); } cboMetavariant.BeginUpdate(); cboMetavariant.ValueMember = "Value"; cboMetavariant.DisplayMember = "Name"; cboMetavariant.DataSource = lstMetavariants; // Select the None item. cboMetavariant.SelectedIndex = 0; cboMetavariant.EndUpdate(); lblBP.Text = objXmlMetatype["karma"].InnerText; // If the Metatype has Force enabled, show the Force NUD. if (objXmlMetatype["forcecreature"] != null || objXmlMetatype["essmax"].InnerText.Contains("D6")) { lblForceLabel.Visible = true; nudForce.Visible = true; if (objXmlMetatype["essmax"].InnerText.Contains("D6")) { int intPos = objXmlMetatype["essmax"].InnerText.IndexOf("D6") - 1; lblForceLabel.Text = objXmlMetatype["essmax"].InnerText.Substring(intPos, 3); nudForce.Maximum = Convert.ToInt32(objXmlMetatype["essmax"].InnerText.Substring(intPos, 1)) * 6; } else { lblForceLabel.Text = LanguageManager.Instance.GetString("String_Force"); nudForce.Maximum = 100; } } else { lblForceLabel.Visible = false; nudForce.Visible = false; } string strQualities = string.Empty; // Build a list of the Metavariant's Positive Qualities. foreach (XmlNode objXmlQuality in objXmlMetatype.SelectNodes("qualities/positive/quality")) { if (GlobalOptions.Instance.Language != "en-us") { XmlNode objQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQuality.InnerText + "\"]"); strQualities += objQuality["translate"]?.InnerText ?? objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + LanguageManager.Instance.TranslateExtra(objXmlQuality.Attributes["select"].InnerText) + ")"; } else { strQualities += objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + objXmlQuality.Attributes["select"].InnerText + ")"; } strQualities += "\n"; } // Build a list of the Metavariant's Negative Qualities. foreach (XmlNode objXmlQuality in objXmlMetatype.SelectNodes("qualities/negative/quality")) { if (GlobalOptions.Instance.Language != "en-us") { XmlNode objQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQuality.InnerText + "\"]"); strQualities += objQuality["translate"]?.InnerText ?? objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + LanguageManager.Instance.TranslateExtra(objXmlQuality.Attributes["select"].InnerText) + ")"; } else { strQualities += objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + objXmlQuality.Attributes["select"].InnerText + ")"; } strQualities += "\n"; } lblQualities.Text = strQualities; } else { // Clear the Metavariant list if nothing is currently selected. List<ListItem> lstMetavariants = new List<ListItem>(); ListItem objNone = new ListItem(); objNone.Value = "None"; objNone.Name = LanguageManager.Instance.GetString("String_None"); lstMetavariants.Add(objNone); cboMetavariant.BeginUpdate(); cboMetavariant.ValueMember = "Value"; cboMetavariant.DisplayMember = "Name"; cboMetavariant.DataSource = lstMetavariants; cboMetavariant.EndUpdate(); } } private void lstMetatypes_DoubleClick(object sender, EventArgs e) { MetatypeSelected(); } private void cmdOK_Click(object sender, EventArgs e) { MetatypeSelected(); } private void cboMetavariant_SelectedIndexChanged(object sender, EventArgs e) { XmlDocument objXmlDocument = XmlManager.Instance.Load(_strXmlFile); XmlDocument objXmlQualityDocument = XmlManager.Instance.Load("qualities.xml"); if (cboMetavariant.SelectedValue.ToString() != "None") { XmlNode objXmlMetavariant = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + lstMetatypes.SelectedValue + "\"]/metavariants/metavariant[name = \"" + cboMetavariant.SelectedValue + "\"]"); XmlNode objXmlMetatype = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + lstMetatypes.SelectedValue + "\"]"); lblBP.Text = objXmlMetavariant["karma"].InnerText; if (objXmlMetatype?["forcecreature"] == null) { lblBOD.Text = string.Format("{0}/{1} ({2})", objXmlMetavariant["bodmin"]?.InnerText ?? objXmlMetatype["bodmin"]?.InnerText, objXmlMetavariant["bodmax"]?.InnerText ?? objXmlMetatype["bodmax"]?.InnerText, objXmlMetavariant["bodaug"]?.InnerText ?? objXmlMetatype["bodaug"]?.InnerText); lblAGI.Text = string.Format("{0}/{1} ({2})", objXmlMetavariant["agimin"]?.InnerText ?? objXmlMetatype["agimin"]?.InnerText, objXmlMetavariant["agimax"]?.InnerText ?? objXmlMetatype["agimax"]?.InnerText, objXmlMetavariant["agiaug"]?.InnerText ?? objXmlMetatype["agiaug"]?.InnerText); lblREA.Text = string.Format("{0}/{1} ({2})", objXmlMetavariant["reamin"]?.InnerText ?? objXmlMetatype["reamin"]?.InnerText, objXmlMetavariant["reamax"]?.InnerText ?? objXmlMetatype["reamax"]?.InnerText, objXmlMetavariant["reaaug"]?.InnerText ?? objXmlMetatype["reaaug"]?.InnerText); lblSTR.Text = string.Format("{0}/{1} ({2})", objXmlMetavariant["strmin"]?.InnerText ?? objXmlMetatype["strmin"]?.InnerText, objXmlMetavariant["strmax"]?.InnerText ?? objXmlMetatype["strmax"]?.InnerText, objXmlMetavariant["straug"]?.InnerText ?? objXmlMetatype["straug"]?.InnerText); lblCHA.Text = string.Format("{0}/{1} ({2})", objXmlMetavariant["chamin"]?.InnerText ?? objXmlMetatype["chamin"]?.InnerText, objXmlMetavariant["chamax"]?.InnerText ?? objXmlMetatype["chamax"]?.InnerText, objXmlMetavariant["chaaug"]?.InnerText ?? objXmlMetatype["chaaug"]?.InnerText); lblINT.Text = string.Format("{0}/{1} ({2})", objXmlMetavariant["intmin"]?.InnerText ?? objXmlMetatype["intmin"]?.InnerText, objXmlMetavariant["intmax"]?.InnerText ?? objXmlMetatype["intmax"]?.InnerText, objXmlMetavariant["intaug"]?.InnerText ?? objXmlMetatype["intaug"]?.InnerText); lblLOG.Text = string.Format("{0}/{1} ({2})", objXmlMetavariant["logmin"]?.InnerText ?? objXmlMetatype["logmin"]?.InnerText, objXmlMetavariant["logmax"]?.InnerText ?? objXmlMetatype["logmax"]?.InnerText, objXmlMetavariant["logaug"]?.InnerText ?? objXmlMetatype["logaug"]?.InnerText); lblWIL.Text = string.Format("{0}/{1} ({2})", objXmlMetavariant["wilmin"]?.InnerText ?? objXmlMetatype["wilmin"]?.InnerText, objXmlMetavariant["wilmax"]?.InnerText ?? objXmlMetatype["wilmax"]?.InnerText, objXmlMetavariant["wilaug"]?.InnerText ?? objXmlMetatype["wilaug"]?.InnerText); lblINI.Text = string.Format("{0}/{1} ({2})", objXmlMetavariant["inimin"]?.InnerText ?? objXmlMetatype["inimin"]?.InnerText, objXmlMetavariant["inimax"]?.InnerText ?? objXmlMetatype["inimax"]?.InnerText, objXmlMetavariant["iniaug"]?.InnerText ?? objXmlMetatype["iniaug"]?.InnerText); } else { lblBOD.Text = objXmlMetavariant["bodmin"]?.InnerText ?? objXmlMetatype["bodmin"]?.InnerText; lblAGI.Text = objXmlMetavariant["agimin"]?.InnerText ?? objXmlMetatype["agimin"]?.InnerText; lblREA.Text = objXmlMetavariant["reamin"]?.InnerText ?? objXmlMetatype["reamin"]?.InnerText; lblSTR.Text = objXmlMetavariant["strmin"]?.InnerText ?? objXmlMetatype["strmin"]?.InnerText; lblCHA.Text = objXmlMetavariant["chamin"]?.InnerText ?? objXmlMetatype["chamin"]?.InnerText; lblINT.Text = objXmlMetavariant["intmin"]?.InnerText ?? objXmlMetatype["intmin"]?.InnerText; lblLOG.Text = objXmlMetavariant["logmin"]?.InnerText ?? objXmlMetatype["logmin"]?.InnerText; lblWIL.Text = objXmlMetavariant["wilmin"]?.InnerText ?? objXmlMetatype["wilmin"]?.InnerText; lblINI.Text = objXmlMetavariant["inimin"]?.InnerText ?? objXmlMetatype["inimin"]?.InnerText; } string strQualities = string.Empty; // Build a list of the Metavariant's Positive Qualities. foreach (XmlNode objXmlQuality in objXmlMetavariant.SelectNodes("qualities/positive/quality")) { if (GlobalOptions.Instance.Language != "en-us") { XmlNode objQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQuality.InnerText + "\"]"); if (objQuality["translate"] != null) strQualities += objQuality["translate"].InnerText; else strQualities += objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + LanguageManager.Instance.TranslateExtra(objXmlQuality.Attributes["select"].InnerText) + ")"; } else { strQualities += objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + objXmlQuality.Attributes["select"].InnerText + ")"; } strQualities += "\n"; } // Build a list of the Metavariant's Negative Qualities. foreach (XmlNode objXmlQuality in objXmlMetavariant.SelectNodes("qualities/negative/quality")) { if (GlobalOptions.Instance.Language != "en-us") { XmlNode objQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQuality.InnerText + "\"]"); if (objQuality["translate"] != null) strQualities += objQuality["translate"].InnerText; else strQualities += objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + LanguageManager.Instance.TranslateExtra(objXmlQuality.Attributes["select"].InnerText) + ")"; } else { strQualities += objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + objXmlQuality.Attributes["select"].InnerText + ")"; } strQualities += "\n"; } lblQualities.Text = strQualities; } else if (lstMetatypes.SelectedValue != null) { XmlNode objXmlMetatype = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + lstMetatypes.SelectedValue + "\"]"); string strQualities = string.Empty; // Build a list of the Metavariant's Positive Qualities. foreach (XmlNode objXmlQuality in objXmlMetatype.SelectNodes("qualities/positive/quality")) { if (GlobalOptions.Instance.Language != "en-us") { XmlNode objQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQuality.InnerText + "\"]"); if (objQuality["translate"] != null) strQualities += objQuality["translate"].InnerText; else strQualities += objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + LanguageManager.Instance.TranslateExtra(objXmlQuality.Attributes["select"].InnerText) + ")"; } else { strQualities += objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + objXmlQuality.Attributes["select"].InnerText + ")"; } strQualities += "\n"; } // Build a list of the Metavariant's Negative Qualities. foreach (XmlNode objXmlQuality in objXmlMetatype.SelectNodes("qualities/negative/quality")) { if (GlobalOptions.Instance.Language != "en-us") { XmlNode objQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQuality.InnerText + "\"]"); strQualities += objQuality["translate"]?.InnerText ?? objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + LanguageManager.Instance.TranslateExtra(objXmlQuality.Attributes["select"].InnerText) + ")"; } else { strQualities += objXmlQuality.InnerText; if (!string.IsNullOrEmpty(objXmlQuality.Attributes["select"]?.InnerText)) strQualities += " (" + objXmlQuality.Attributes["select"].InnerText + ")"; } strQualities += "\n"; } lblQualities.Text = strQualities; lblBP.Text = objXmlMetatype["karma"].InnerText; } else { lblBP.Text = "0"; lblQualities.Text = "None"; } } private void cmdCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void cboCategory_SelectedIndexChanged(object sender, EventArgs e) { PopulateMetatypes(); } #endregion #region Custom Methods /// <summary> /// A Metatype has been selected, so fill in all of the necessary Character information. /// </summary> private void MetatypeSelected() { if (!string.IsNullOrEmpty(lstMetatypes.Text)) { ImprovementManager objImprovementManager = new ImprovementManager(_objCharacter); XmlDocument objXmlDocument = XmlManager.Instance.Load(_strXmlFile); XmlNode objXmlMetatype = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + lstMetatypes.SelectedValue + "\"]"); XmlNode objXmlMetavariant = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + lstMetatypes.SelectedValue + "\"]/metavariants/metavariant[name = \"" + cboMetavariant.SelectedValue + "\"]"); int intForce = 0; if (nudForce.Visible) intForce = Convert.ToInt32(nudForce.Value); // Set Metatype information. if (objXmlMetavariant != null && cboMetavariant.SelectedValue.ToString() != "None") { _objCharacter.BOD.AssignLimits(ExpressionToString(objXmlMetavariant["bodmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["bodmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["bodaug"]?.InnerText, intForce, 0)); _objCharacter.AGI.AssignLimits(ExpressionToString(objXmlMetavariant["agimin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["agimax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["agiaug"]?.InnerText, intForce, 0)); _objCharacter.REA.AssignLimits(ExpressionToString(objXmlMetavariant["reamin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["reamax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["reaaug"]?.InnerText, intForce, 0)); _objCharacter.STR.AssignLimits(ExpressionToString(objXmlMetavariant["strmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["strmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["straug"]?.InnerText, intForce, 0)); _objCharacter.CHA.AssignLimits(ExpressionToString(objXmlMetavariant["chamin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["chamax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["chaaug"]?.InnerText, intForce, 0)); _objCharacter.INT.AssignLimits(ExpressionToString(objXmlMetavariant["intmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["intmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["intaug"]?.InnerText, intForce, 0)); _objCharacter.LOG.AssignLimits(ExpressionToString(objXmlMetavariant["logmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["logmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["logaug"]?.InnerText, intForce, 0)); _objCharacter.WIL.AssignLimits(ExpressionToString(objXmlMetavariant["wilmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["wilmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["wilaug"]?.InnerText, intForce, 0)); _objCharacter.MAG.AssignLimits(ExpressionToString(objXmlMetavariant["magmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["magmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["magaug"]?.InnerText, intForce, 0)); _objCharacter.RES.AssignLimits(ExpressionToString(objXmlMetavariant["resmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["resmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["resaug"]?.InnerText, intForce, 0)); _objCharacter.EDG.AssignLimits(ExpressionToString(objXmlMetavariant["edgmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["edgmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["edgaug"]?.InnerText, intForce, 0)); _objCharacter.ESS.AssignLimits(ExpressionToString(objXmlMetavariant["essmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["essmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["essaug"]?.InnerText, intForce, 0)); _objCharacter.DEP.AssignLimits(ExpressionToString(objXmlMetavariant["depmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["depmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetavariant["depaug"]?.InnerText, intForce, 0)); } else if (objXmlMetatype != null && (_strXmlFile != "critters.xml" || lstMetatypes.SelectedValue.ToString() == "Ally Spirit")) { _objCharacter.BOD.AssignLimits(ExpressionToString(objXmlMetatype["bodmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["bodmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["bodaug"]?.InnerText, intForce, 0)); _objCharacter.AGI.AssignLimits(ExpressionToString(objXmlMetatype["agimin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["agimax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["agiaug"]?.InnerText, intForce, 0)); _objCharacter.REA.AssignLimits(ExpressionToString(objXmlMetatype["reamin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["reamax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["reaaug"]?.InnerText, intForce, 0)); _objCharacter.STR.AssignLimits(ExpressionToString(objXmlMetatype["strmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["strmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["straug"]?.InnerText, intForce, 0)); _objCharacter.CHA.AssignLimits(ExpressionToString(objXmlMetatype["chamin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["chamax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["chaaug"]?.InnerText, intForce, 0)); _objCharacter.INT.AssignLimits(ExpressionToString(objXmlMetatype["intmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["intmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["intaug"]?.InnerText, intForce, 0)); _objCharacter.LOG.AssignLimits(ExpressionToString(objXmlMetatype["logmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["logmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["logaug"]?.InnerText, intForce, 0)); _objCharacter.WIL.AssignLimits(ExpressionToString(objXmlMetatype["wilmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["wilmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["wilaug"]?.InnerText, intForce, 0)); _objCharacter.MAG.AssignLimits(ExpressionToString(objXmlMetatype["magmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["magmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["magaug"]?.InnerText, intForce, 0)); _objCharacter.RES.AssignLimits(ExpressionToString(objXmlMetatype["resmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["resmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["resaug"]?.InnerText, intForce, 0)); _objCharacter.EDG.AssignLimits(ExpressionToString(objXmlMetatype["edgmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["edgmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["edgaug"]?.InnerText, intForce, 0)); _objCharacter.ESS.AssignLimits(ExpressionToString(objXmlMetatype["essmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essaug"]?.InnerText, intForce, 0)); _objCharacter.DEP.AssignLimits(ExpressionToString(objXmlMetatype["depmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["depmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["depaug"]?.InnerText, intForce, 0)); } else if (objXmlMetatype != null) { int intMinModifier = -3; int intMaxModifier = 3; if (cboCategory.SelectedValue.ToString() == "Technocritters") { intMinModifier = -1; intMaxModifier = 1; } _objCharacter.BOD.AssignLimits(ExpressionToString(objXmlMetatype["bodmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["bodmin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["bodmin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.AGI.AssignLimits(ExpressionToString(objXmlMetatype["agimin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["agimin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["agimin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.REA.AssignLimits(ExpressionToString(objXmlMetatype["reamin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["reamin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["reamin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.STR.AssignLimits(ExpressionToString(objXmlMetatype["strmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["strmin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["strmin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.CHA.AssignLimits(ExpressionToString(objXmlMetatype["chamin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["chamin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["chamin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.INT.AssignLimits(ExpressionToString(objXmlMetatype["intmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["intmin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["intmin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.LOG.AssignLimits(ExpressionToString(objXmlMetatype["logmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["logmin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["logmin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.WIL.AssignLimits(ExpressionToString(objXmlMetatype["wilmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["wilmin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["wilmin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.MAG.AssignLimits(ExpressionToString(objXmlMetatype["magmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["magmin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["magmin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.RES.AssignLimits(ExpressionToString(objXmlMetatype["resmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["resmin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["resmin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.EDG.AssignLimits(ExpressionToString(objXmlMetatype["edgmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["edgmin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["edgmin"]?.InnerText, intForce, intMaxModifier)); _objCharacter.ESS.AssignLimits(ExpressionToString(objXmlMetatype["essmin"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essmax"]?.InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essaug"]?.InnerText, intForce, 0)); _objCharacter.DEP.AssignLimits(ExpressionToString(objXmlMetatype["depmin"]?.InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["depmin"]?.InnerText, intForce, intMaxModifier), ExpressionToString(objXmlMetatype["depmin"]?.InnerText, intForce, intMaxModifier)); } //TODO: Move this into AttributeSection when I get around to implementing that. This is an ugly hack that shouldn't be necessary, but eh. _objCharacter.AttributeList.Add(_objCharacter.BOD); _objCharacter.AttributeList.Add(_objCharacter.AGI); _objCharacter.AttributeList.Add(_objCharacter.REA); _objCharacter.AttributeList.Add(_objCharacter.STR); _objCharacter.AttributeList.Add(_objCharacter.CHA); _objCharacter.AttributeList.Add(_objCharacter.INT); _objCharacter.AttributeList.Add(_objCharacter.LOG); _objCharacter.AttributeList.Add(_objCharacter.WIL); _objCharacter.SpecialAttributeList.Add(_objCharacter.EDG); _objCharacter.SpecialAttributeList.Add(_objCharacter.MAG); _objCharacter.SpecialAttributeList.Add(_objCharacter.RES); _objCharacter.SpecialAttributeList.Add(_objCharacter.DEP); // If this is a Shapeshifter, a Metavariant must be selected. Default to Human if None is selected. if (cboCategory.SelectedValue.ToString() == "Shapeshifter" && cboMetavariant.SelectedValue.ToString() == "None") cboMetavariant.SelectedValue = "Human"; _objCharacter.Metatype = lstMetatypes.SelectedValue.ToString(); _objCharacter.MetatypeCategory = cboCategory.SelectedValue.ToString(); if (cboMetavariant.SelectedValue.ToString() == "None") { _objCharacter.Metavariant = string.Empty; _objCharacter.MetatypeBP = Convert.ToInt32(lblBP.Text); } else { _objCharacter.Metavariant = cboMetavariant.SelectedValue.ToString(); _objCharacter.MetatypeBP = Convert.ToInt32(lblBP.Text); } if (objXmlMetatype?["movement"] != null) _objCharacter.Movement = objXmlMetatype["movement"].InnerText; // Load the Qualities file. XmlDocument objXmlQualityDocument = XmlManager.Instance.Load("qualities.xml"); if (cboMetavariant.SelectedValue.ToString() == "None") { // Determine if the Metatype has any bonuses. if (objXmlMetatype?.InnerXml.Contains("bonus") == true) objImprovementManager.CreateImprovements(Improvement.ImprovementSource.Metatype, lstMetatypes.SelectedValue.ToString(), objXmlMetatype.SelectSingleNode("bonus"), false, 1, lstMetatypes.SelectedValue.ToString()); // Create the Qualities that come with the Metatype. foreach (XmlNode objXmlQualityItem in objXmlMetatype?.SelectNodes("qualities/positive/quality")) { XmlNode objXmlQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQualityItem.InnerText + "\"]"); TreeNode objNode = new TreeNode(); List<Weapon> objWeapons = new List<Weapon>(); List<TreeNode> objWeaponNodes = new List<TreeNode>(); Quality objQuality = new Quality(_objCharacter); string strForceValue = string.Empty; if (objXmlQualityItem.Attributes["select"] != null) strForceValue = objXmlQualityItem.Attributes["select"].InnerText; QualitySource objSource = QualitySource.Metatype; if (objXmlQualityItem.Attributes["removable"] != null) objSource = QualitySource.MetatypeRemovable; objQuality.Create(objXmlQuality, _objCharacter, objSource, objNode, objWeapons, objWeaponNodes, strForceValue); objQuality.ContributeToLimit = false; _objCharacter.Qualities.Add(objQuality); // Add any created Weapons to the character. foreach (Weapon objWeapon in objWeapons) _objCharacter.Weapons.Add(objWeapon); } foreach (XmlNode objXmlQualityItem in objXmlMetatype.SelectNodes("qualities/negative/quality")) { XmlNode objXmlQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQualityItem.InnerText + "\"]"); TreeNode objNode = new TreeNode(); List<Weapon> objWeapons = new List<Weapon>(); List<TreeNode> objWeaponNodes = new List<TreeNode>(); Quality objQuality = new Quality(_objCharacter); string strForceValue = string.Empty; if (objXmlQualityItem.Attributes["select"] != null) strForceValue = objXmlQualityItem.Attributes["select"].InnerText; QualitySource objSource = new QualitySource(); objSource = QualitySource.Metatype; if (objXmlQualityItem.Attributes["removable"] != null) objSource = QualitySource.MetatypeRemovable; objQuality.Create(objXmlQuality, _objCharacter, objSource, objNode, objWeapons, objWeaponNodes, strForceValue); objQuality.ContributeToLimit = false; _objCharacter.Qualities.Add(objQuality); // Add any created Weapons to the character. foreach (Weapon objWeapon in objWeapons) _objCharacter.Weapons.Add(objWeapon); } } // If a Metavariant has been selected, locate it in the file. if (cboMetavariant.SelectedValue.ToString() != "None") { // Determine if the Metavariant has any bonuses. if (objXmlMetavariant.InnerXml.Contains("bonus")) { objImprovementManager.CreateImprovements(Improvement.ImprovementSource.Metavariant, cboMetavariant.SelectedValue.ToString(), objXmlMetavariant.SelectSingleNode("bonus"), false, 1, cboMetavariant.SelectedValue.ToString()); } // Create the Qualities that come with the Metatype. foreach (XmlNode objXmlQualityItem in objXmlMetavariant.SelectNodes("qualities/positive/quality")) { XmlNode objXmlQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQualityItem.InnerText + "\"]"); TreeNode objNode = new TreeNode(); List<Weapon> objWeapons = new List<Weapon>(); List<TreeNode> objWeaponNodes = new List<TreeNode>(); Quality objQuality = new Quality(_objCharacter); string strForceValue = string.Empty; if (objXmlQualityItem.Attributes["select"] != null) strForceValue = objXmlQualityItem.Attributes["select"].InnerText; QualitySource objSource = new QualitySource(); objSource = QualitySource.Metatype; if (objXmlQualityItem.Attributes["removable"] != null) objSource = QualitySource.MetatypeRemovable; objQuality.Create(objXmlQuality, _objCharacter, objSource, objNode, objWeapons, objWeaponNodes, strForceValue); objQuality.ContributeToLimit = false; _objCharacter.Qualities.Add(objQuality); // Add any created Weapons to the character. foreach (Weapon objWeapon in objWeapons) _objCharacter.Weapons.Add(objWeapon); } foreach (XmlNode objXmlQualityItem in objXmlMetavariant.SelectNodes("qualities/negative/quality")) { XmlNode objXmlQuality = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQualityItem.InnerText + "\"]"); TreeNode objNode = new TreeNode(); List<Weapon> objWeapons = new List<Weapon>(); List<TreeNode> objWeaponNodes = new List<TreeNode>(); Quality objQuality = new Quality(_objCharacter); string strForceValue = string.Empty; if (objXmlQualityItem.Attributes["select"] != null) strForceValue = objXmlQualityItem.Attributes["select"].InnerText; QualitySource objSource = QualitySource.Metatype; if (objXmlQualityItem.Attributes["removable"] != null) objSource = QualitySource.MetatypeRemovable; objQuality.Create(objXmlQuality, _objCharacter, objSource, objNode, objWeapons, objWeaponNodes, strForceValue); objQuality.ContributeToLimit = false; _objCharacter.Qualities.Add(objQuality); // Add any created Weapons to the character. foreach (Weapon objWeapon in objWeapons) _objCharacter.Weapons.Add(objWeapon); } } // Add any Critter Powers the Metatype/Critter should have. XmlNode objXmlCritter = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + _objCharacter.Metatype + "\"]"); objXmlDocument = XmlManager.Instance.Load("critterpowers.xml"); foreach (XmlNode objXmlPower in objXmlCritter.SelectNodes("powers/power")) { XmlNode objXmlCritterPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"" + objXmlPower.InnerText + "\"]"); TreeNode objNode = new TreeNode(); CritterPower objPower = new CritterPower(_objCharacter); string strForcedValue = string.Empty; int intRating = 0; if (objXmlPower.Attributes["rating"] != null) intRating = Convert.ToInt32(objXmlPower.Attributes["rating"].InnerText); if (objXmlPower.Attributes["select"] != null) strForcedValue = objXmlPower.Attributes["select"].InnerText; objPower.Create(objXmlCritterPower, _objCharacter, objNode, intRating, strForcedValue); objPower.CountTowardsLimit = false; _objCharacter.CritterPowers.Add(objPower); } // Add any Critter Powers the Metavariant should have. if (cboMetavariant.SelectedValue.ToString() != "None") { foreach (XmlNode objXmlPower in objXmlMetavariant.SelectNodes("powers/power")) { XmlNode objXmlCritterPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"" + objXmlPower.InnerText + "\"]"); TreeNode objNode = new TreeNode(); CritterPower objPower = new CritterPower(_objCharacter); string strForcedValue = string.Empty; int intRating = 0; if (objXmlPower.Attributes["rating"] != null) intRating = Convert.ToInt32(objXmlPower.Attributes["rating"].InnerText); if (objXmlPower.Attributes["select"] != null) strForcedValue = objXmlPower.Attributes["select"].InnerText; objPower.Create(objXmlCritterPower, _objCharacter, objNode, intRating, strForcedValue); objPower.CountTowardsLimit = false; _objCharacter.CritterPowers.Add(objPower); } } // Add any Natural Weapons the Metavariant should have. if (cboMetavariant.SelectedValue.ToString() != "None") { if (objXmlMetavariant["naturalweapons"] != null) { foreach (XmlNode objXmlNaturalWeapon in objXmlMetavariant["naturalweapons"].SelectNodes("naturalweapon")) { Weapon objWeapon = new Weapon(_objCharacter); objWeapon.Name = objXmlNaturalWeapon["name"].InnerText; objWeapon.Category = LanguageManager.Instance.GetString("Tab_Critter"); objWeapon.WeaponType = "Melee"; objWeapon.Reach = Convert.ToInt32(objXmlNaturalWeapon["reach"].InnerText); objWeapon.Damage = objXmlNaturalWeapon["damage"].InnerText; objWeapon.AP = objXmlNaturalWeapon["ap"].InnerText; objWeapon.Mode = "0"; objWeapon.RC = "0"; objWeapon.Concealability = 0; objWeapon.Avail = "0"; objWeapon.Cost = 0; objWeapon.UseSkill = objXmlNaturalWeapon["useskill"].InnerText; objWeapon.Source = objXmlNaturalWeapon["source"].InnerText; objWeapon.Page = objXmlNaturalWeapon["page"].InnerText; _objCharacter.Weapons.Add(objWeapon); } } } if (cboCategory.SelectedValue.ToString() == "Spirits") { if (objXmlMetatype["optionalpowers"] != null) { //For every 3 full points of Force a spirit has, it may gain one Optional Power. for (int i = intForce -3; i >= 0; i -= 3) { XmlDocument objDummyDocument = new XmlDocument(); XmlNode bonusNode = objDummyDocument.CreateNode(XmlNodeType.Element, "bonus", null); objDummyDocument.AppendChild(bonusNode); XmlNode powerNode = objDummyDocument.ImportNode(objXmlMetatype["optionalpowers"].CloneNode(true),true); objDummyDocument.ImportNode(powerNode, true); bonusNode.AppendChild(powerNode); objImprovementManager.CreateImprovements(Improvement.ImprovementSource.Metatype, lstMetatypes.SelectedValue.ToString(), bonusNode, false, 1, lstMetatypes.SelectedValue.ToString()); } } //If this is a Blood Spirit, add their free Critter Powers. if (chkBloodSpirit.Checked) { XmlNode objXmlCritterPower; TreeNode objNode; CritterPower objPower; bool blnAddPower = _objCharacter.CritterPowers.All(objFindPower => objFindPower.Name != "Energy Drain"); //Energy Drain. if (blnAddPower) { objXmlCritterPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"Energy Drain\"]"); objNode = new TreeNode(); objPower = new CritterPower(_objCharacter); objPower.Create(objXmlCritterPower, _objCharacter, objNode, 0, string.Empty); objPower.CountTowardsLimit = false; _objCharacter.CritterPowers.Add(objPower); } //Fear. blnAddPower = _objCharacter.CritterPowers.All(objFindPower => objFindPower.Name != "Fear"); if (blnAddPower) { objXmlCritterPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"Fear\"]"); objNode = new TreeNode(); objPower = new CritterPower(_objCharacter); objPower.Create(objXmlCritterPower, _objCharacter, objNode, 0, string.Empty); objPower.CountTowardsLimit = false; _objCharacter.CritterPowers.Add(objPower); } //Natural Weapon. objXmlCritterPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"Natural Weapon\"]"); objNode = new TreeNode(); objPower = new CritterPower(_objCharacter); objPower.Create(objXmlCritterPower, _objCharacter, objNode, 0, "DV " + intForce.ToString() + "P, AP 0"); objPower.CountTowardsLimit = false; _objCharacter.CritterPowers.Add(objPower); //Evanescence. blnAddPower = _objCharacter.CritterPowers.All(objFindPower => objFindPower.Name != "Evanescence"); if (blnAddPower) { objXmlCritterPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"Evanescence\"]"); objNode = new TreeNode(); objPower = new CritterPower(_objCharacter); objPower.Create(objXmlCritterPower, _objCharacter, objNode, 0, string.Empty); objPower.CountTowardsLimit = false; _objCharacter.CritterPowers.Add(objPower); } } //Remove the Critter's Materialization Power if they have it. Add the Possession or Inhabitation Power if the Possession-based Tradition checkbox is checked. if (chkPossessionBased.Checked) { foreach ( CritterPower objCritterPower in _objCharacter.CritterPowers.Where(objCritterPower => objCritterPower.Name == "Materialization")) { _objCharacter.CritterPowers.Remove(objCritterPower); break; } //Add the selected Power. XmlNode objXmlCritterPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"" + cboPossessionMethod.SelectedValue.ToString() + "\"]"); TreeNode objNode = new TreeNode(); CritterPower objPower = new CritterPower(_objCharacter); objPower.Create(objXmlCritterPower, _objCharacter, objNode, 0, string.Empty); objPower.CountTowardsLimit = false; _objCharacter.CritterPowers.Add(objPower); } } XmlDocument objSkillDocument = XmlManager.Instance.Load("skills.xml"); //Set the Active Skill Ratings for the Critter. foreach (XmlNode objXmlSkill in objXmlCritter.SelectNodes("skills/skill")) { XmlNode objXmlSkillNode = objSkillDocument.SelectSingleNode("/chummer/skills/skill[name = \"" + objXmlSkill.InnerText + "\"]"); Skill.FromData(objXmlSkillNode, _objCharacter); foreach (Skill objSkill in _objCharacter.SkillsSection.Skills.Where(objSkill => objSkill.Name == objXmlSkill.InnerText)) { objSkill.Karma = objXmlSkill.Attributes["rating"].InnerText == "F" ? intForce : Convert.ToInt32(objXmlSkill.Attributes["rating"].InnerText); } } //Set the Skill Group Ratings for the Critter. foreach (XmlNode objXmlSkill in objXmlCritter.SelectNodes("skills/group")) { foreach (SkillGroup objSkill in _objCharacter.SkillsSection.SkillGroups.Where(objSkill => objSkill.Name == objXmlSkill.InnerText)) { if (objXmlSkill.Attributes?["rating"]?.InnerText != null) { objSkill.Karma = objXmlSkill.Attributes["rating"].InnerText == "F" ? intForce : Convert.ToInt32(objXmlSkill.Attributes["rating"].InnerText); } } } //Set the Knowledge Skill Ratings for the Critter. foreach (XmlNode objXmlSkill in objXmlCritter.SelectNodes("skills/knowledge")) { XmlNode objXmlSkillNode = objSkillDocument.SelectSingleNode("/chummer/knowledgeskills/skill[name = \"" + objXmlSkill.InnerText + "\"]"); if (_objCharacter.SkillsSection.KnowledgeSkills.Any(objSkill => objSkill.Name == objXmlSkill.InnerText)) { foreach ( KnowledgeSkill objSkill in _objCharacter.SkillsSection.KnowledgeSkills.Where(objSkill => objSkill.Name == objXmlSkill.InnerText)) { if (objXmlSkill.Attributes?["rating"]?.InnerText != null) { objSkill.Karma = objXmlSkill.Attributes["rating"].InnerText == "F" ? intForce : Convert.ToInt32(objXmlSkill.Attributes["rating"].InnerText); } } } else { if (objXmlSkillNode != null) { KnowledgeSkill objSkill = Skill.FromData(objXmlSkillNode, _objCharacter) as KnowledgeSkill; if (objXmlSkill.Attributes?["rating"]?.InnerText != null) { objSkill.Karma = objXmlSkill.Attributes["rating"].InnerText == "F" ? intForce : Convert.ToInt32(objXmlSkill.Attributes["rating"].InnerText); } _objCharacter.SkillsSection.KnowledgeSkills.Add(objSkill); } else { var objSkill = new KnowledgeSkill(_objCharacter, objXmlSkill.InnerText) { Type = objXmlSkill.Attributes?["category"]?.InnerText }; if (objXmlSkill.Attributes?["rating"]?.InnerText != null) { objSkill.Karma = objXmlSkill.Attributes["rating"].InnerText == "F" ? intForce : Convert.ToInt32(objXmlSkill.Attributes["rating"].InnerText); } _objCharacter.SkillsSection.KnowledgeSkills.Add(objSkill); } } } // Add any Complex Forms the Critter comes with (typically Sprites) XmlDocument objXmlProgramDocument = XmlManager.Instance.Load("complexforms.xml"); foreach (XmlNode objXmlComplexForm in objXmlCritter.SelectNodes("complexforms/complexform")) { string strForceValue = string.Empty; if (objXmlComplexForm.Attributes["select"] != null) strForceValue = objXmlComplexForm.Attributes["select"].InnerText; XmlNode objXmlProgram = objXmlProgramDocument.SelectSingleNode("/chummer/complexforms/complexform[name = \"" + objXmlComplexForm.InnerText + "\"]"); TreeNode objNode = new TreeNode(); ComplexForm objProgram = new ComplexForm(_objCharacter); objProgram.Create(objXmlProgram, _objCharacter, objNode, strForceValue); _objCharacter.ComplexForms.Add(objProgram); } // Add any Advanced Programs the Critter comes with (typically Sprites) XmlDocument objXmlAIProgramDocument = XmlManager.Instance.Load("programs.xml"); foreach (XmlNode objXmlAIProgram in objXmlCritter.SelectNodes("programs/program")) { string strForceValue = string.Empty; if (objXmlAIProgram.Attributes["select"] != null) strForceValue = objXmlAIProgram.Attributes["select"].InnerText; XmlNode objXmlProgram = objXmlAIProgramDocument.SelectSingleNode("/chummer/programs/program[name = \"" + objXmlAIProgram.InnerText + "\"]"); if (objXmlProgram != null) { TreeNode objNode = new TreeNode(); AIProgram objProgram = new AIProgram(_objCharacter); objProgram.Create(objXmlProgram, _objCharacter, objNode, objXmlProgram["category"]?.InnerText == "Advanced Programs", strForceValue); _objCharacter.AIPrograms.Add(objProgram); } } // Add any Gear the Critter comes with (typically Programs for A.I.s) XmlDocument objXmlGearDocument = XmlManager.Instance.Load("gear.xml"); foreach (XmlNode objXmlGear in objXmlCritter.SelectNodes("gears/gear")) { int intRating = 0; if (objXmlGear.Attributes["rating"] != null) intRating = Convert.ToInt32(ExpressionToString(objXmlGear.Attributes["rating"].InnerText, Convert.ToInt32(nudForce.Value), 0)); string strForceValue = string.Empty; if (objXmlGear.Attributes["select"] != null) strForceValue = objXmlGear.Attributes["select"].InnerText; XmlNode objXmlGearItem = objXmlGearDocument.SelectSingleNode("/chummer/gears/gear[name = \"" + objXmlGear.InnerText + "\"]"); TreeNode objNode = new TreeNode(); Gear objGear = new Gear(_objCharacter); List<Weapon> lstWeapons = new List<Weapon>(); List<TreeNode> lstWeaponNodes = new List<TreeNode>(); objGear.Create(objXmlGearItem, _objCharacter, objNode, intRating, lstWeapons, lstWeaponNodes, strForceValue); objGear.Cost = "0"; objGear.Cost3 = "0"; objGear.Cost6 = "0"; objGear.Cost10 = "0"; _objCharacter.Gear.Add(objGear); } // Sprites can never have Physical Attributes if (_objCharacter.DEPEnabled || lstMetatypes.SelectedValue.ToString().EndsWith("Sprite")) { _objCharacter.BOD.AssignLimits("0", "0", "0"); _objCharacter.AGI.AssignLimits("0", "0", "0"); _objCharacter.REA.AssignLimits("0", "0", "0"); _objCharacter.STR.AssignLimits("0", "0", "0"); _objCharacter.MAG.AssignLimits("0", "0", "0"); } int x; int.TryParse(lblBP.Text, out x); //_objCharacter.BuildKarma = _objCharacter.BuildKarma - x; DialogResult = DialogResult.OK; Close(); } else { MessageBox.Show(LanguageManager.Instance.GetString("Message_Metatype_SelectMetatype"), LanguageManager.Instance.GetString("MessageTitle_Metatype_SelectMetatype"), MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Convert Force, 1D6, or 2D6 into a usable value. /// </summary> /// <param name="strIn">Expression to convert.</param> /// <param name="intForce">Force value to use.</param> /// <param name="intOffset">Dice offset.</param> /// <returns></returns> private string ExpressionToString(string strIn, int intForce, int intOffset) { if (string.IsNullOrWhiteSpace(strIn)) return intOffset.ToString(); int intValue = 1; XmlDocument objXmlDocument = new XmlDocument(); XPathNavigator nav = objXmlDocument.CreateNavigator(); XPathExpression xprAttribute = nav.Compile(strIn.Replace("/", " div ").Replace("F", intForce.ToString()).Replace("1D6", intForce.ToString()).Replace("2D6", intForce.ToString())); object xprEvaluateResult = null; // This statement is wrapped in a try/catch since trying 1 div 2 results in an error with XSLT. try { xprEvaluateResult = nav.Evaluate(xprAttribute); } catch(XPathException) { } if (xprEvaluateResult is double) intValue = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(xprEvaluateResult.ToString(), GlobalOptions.InvariantCultureInfo))); intValue += intOffset; if (intForce > 0) { if (intValue < 1) intValue = 1; } else if (intValue < 0) intValue = 0; return intValue.ToString(); } /// <summary> /// Populate the list of Metatypes. /// </summary> void PopulateMetatypes() { XmlDocument objXmlDocument = XmlManager.Instance.Load(_strXmlFile); List<ListItem> lstMetatype = new List<ListItem>(); XmlNodeList objXmlMetatypeList = objXmlDocument.SelectNodes("/chummer/metatypes/metatype[(" + _objCharacter.Options.BookXPath() + ") and category = \"" + cboCategory.SelectedValue + "\"]"); foreach (XmlNode objXmlMetatype in objXmlMetatypeList) { ListItem objItem = new ListItem(); objItem.Value = objXmlMetatype["name"]?.InnerText; objItem.Name = objXmlMetatype["translate"]?.InnerText ?? objItem.Value; lstMetatype.Add(objItem); } SortListItem objSort = new SortListItem(); lstMetatype.Sort(objSort.Compare); lstMetatypes.BeginUpdate(); lstMetatypes.DataSource = null; lstMetatypes.ValueMember = "Value"; lstMetatypes.DisplayMember = "Name"; lstMetatypes.DataSource = lstMetatype; lstMetatypes.SelectedIndex = -1; lstMetatypes.EndUpdate(); if (cboCategory.SelectedValue.ToString().EndsWith("Spirits")) { chkBloodSpirit.Visible = true; chkPossessionBased.Visible = true; cboPossessionMethod.Visible = true; } else { chkBloodSpirit.Checked = false; chkBloodSpirit.Visible = false; chkPossessionBased.Visible = false; chkPossessionBased.Checked = false; cboPossessionMethod.Visible = false; } } private void chkPossessionBased_CheckedChanged(object sender, EventArgs e) { cboPossessionMethod.Enabled = chkPossessionBased.Checked; } #endregion } }
OLStefan/chummer5a
Chummer/Character Creation/frmKarmaMetatype.cs
C#
gpl-3.0
67,173
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2012 University of California, Los Angeles * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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 * * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu> * : Saran Tarnoi <saran.tarnoi@gmail.com> */ // ndn-simple-with-link-failure.cc #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/point-to-point-module.h" #include "ns3/ndnSIM-module.h" // for LinkStatusControl::FailLinks and LinkStatusControl::UpLinks #include "ns3/ndn-link-control-helper.h" using namespace ns3; using ns3::ndn::LinkControlHelper; using ns3::ndn::StackHelper; using ns3::ndn::AppHelper; /** * This scenario simulates a very simple network topology: * * * +----------+ 1Mbps +--------+ 1Mbps +----------+ * | consumer | <------------> | router | <------------> | producer | * +----------+ 10ms +--------+ 10ms +----------+ * * * Consumer requests data from producer with frequency 10 interests per second * (interests contain constantly increasing sequence number). * * For every received interest, producer replies with a data packet, containing * 1024 bytes of virtual payload. * * To run scenario and see what is happening, use the following command: * * NS_LOG=ndn.Consumer:ndn.Producer ./waf --run=ndn-simple */ int main (int argc, char *argv[]) { // setting default parameters for PointToPoint links and channels Config::SetDefault ("ns3::PointToPointNetDevice::DataRate", StringValue ("1Mbps")); Config::SetDefault ("ns3::PointToPointChannel::Delay", StringValue ("10ms")); Config::SetDefault ("ns3::DropTailQueue::MaxPackets", StringValue ("20")); // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize CommandLine cmd; cmd.Parse (argc, argv); // Creating nodes NodeContainer nodes; nodes.Create (3); // Connecting nodes using two links PointToPointHelper p2p; p2p.Install (nodes.Get (0), nodes.Get (1)); p2p.Install (nodes.Get (1), nodes.Get (2)); // Install NDN stack on all nodes StackHelper ndnHelper; ndnHelper.SetDefaultRoutes (true); ndnHelper.InstallAll (); // Installing applications // Consumer AppHelper consumerHelper ("ns3::ndn::ConsumerCbr"); // Consumer will request /prefix/0, /prefix/1, ... consumerHelper.SetPrefix ("/prefix"); consumerHelper.SetAttribute ("Frequency", StringValue ("10")); // 10 interests a second consumerHelper.Install (nodes.Get (0)); // first node // Producer AppHelper producerHelper ("ns3::ndn::Producer"); // Producer will reply to all requests starting with /prefix producerHelper.SetPrefix ("/prefix"); producerHelper.SetAttribute ("PayloadSize", StringValue("1024")); producerHelper.Install (nodes.Get (2)); // last node // The failure of the link connecting consumer and router will start from seconds 10.0 to 15.0 Simulator::Schedule (Seconds (10.0), LinkControlHelper::FailLink, nodes.Get (0), nodes.Get (1)); Simulator::Schedule (Seconds (15.0), LinkControlHelper::UpLink, nodes.Get (0), nodes.Get (1)); Simulator::Stop (Seconds (20.0)); Simulator::Run (); Simulator::Destroy (); return 0; }
spirosmastorakis/ndnSIM-development
examples/ndn-simple-with-link-failure.cc
C++
gpl-3.0
3,861
Imports System ' ' * Copyright (c) 2000, 2004, Oracle and/or its affiliates. All rights reserved. ' * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' Namespace javax.print.attribute.standard ''' <summary> ''' Class PrintQuality is a printing attribute class, an enumeration, ''' that specifies the print quality that the printer uses for the job. ''' <P> ''' <B>IPP Compatibility:</B> The category name returned by ''' <CODE>getName()</CODE> is the IPP attribute name. The enumeration's ''' integer value is the IPP enum value. The <code>toString()</code> method ''' returns the IPP string representation of the attribute value. ''' <P> ''' ''' @author David Mendenhall ''' @author Alan Kaminsky ''' </summary> Public Class PrintQuality Inherits javax.print.attribute.EnumSyntax Implements javax.print.attribute.DocAttribute, javax.print.attribute.PrintRequestAttribute, javax.print.attribute.PrintJobAttribute Private Const serialVersionUID As Long = -3072341285225858365L ''' <summary> ''' Lowest quality available on the printer. ''' </summary> Public Shared ReadOnly DRAFT As New PrintQuality(3) ''' <summary> ''' Normal or intermediate quality on the printer. ''' </summary> Public Shared ReadOnly NORMAL As New PrintQuality(4) ''' <summary> ''' Highest quality available on the printer. ''' </summary> Public Shared ReadOnly HIGH As New PrintQuality(5) ''' <summary> ''' Construct a new print quality enumeration value with the given integer ''' value. ''' </summary> ''' <param name="value"> Integer value. </param> Protected Friend Sub New(ByVal value As Integer) MyBase.New(value) End Sub Private Shared ReadOnly myStringTable As String() = { "draft", "normal", "high" } Private Shared ReadOnly myEnumValueTable As PrintQuality() = { DRAFT, NORMAL, HIGH } ''' <summary> ''' Returns the string table for class PrintQuality. ''' </summary> Protected Friend Property Overrides stringTable As String() Get Return CType(myStringTable.clone(), String()) End Get End Property ''' <summary> ''' Returns the enumeration value table for class PrintQuality. ''' </summary> Protected Friend Property Overrides enumValueTable As javax.print.attribute.EnumSyntax() Get Return CType(myEnumValueTable.clone(), javax.print.attribute.EnumSyntax()) End Get End Property ''' <summary> ''' Returns the lowest integer value used by class PrintQuality. ''' </summary> Protected Friend Property Overrides offset As Integer Get Return 3 End Get End Property ''' <summary> ''' Get the printing attribute class which is to be used as the "category" ''' for this printing attribute value. ''' <P> ''' For class PrintQuality and any vendor-defined subclasses, the category is ''' class PrintQuality itself. ''' </summary> ''' <returns> Printing attribute class (category), an instance of class ''' <seealso cref="java.lang.Class java.lang.Class"/>. </returns> Public Property category As Type Get Return GetType(PrintQuality) End Get End Property ''' <summary> ''' Get the name of the category of which this attribute value is an ''' instance. ''' <P> ''' For class PrintQuality and any vendor-defined subclasses, the category ''' name is <CODE>"print-quality"</CODE>. ''' </summary> ''' <returns> Attribute category name. </returns> Public Property name As String Get Return "print-quality" End Get End Property End Class End Namespace
amethyst-asuka/java_dotnet
javax/print/attribute/standard/PrintQuality.vb
Visual Basic
gpl-3.0
3,638
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <meta name="theme-color" content="#323838"> <meta name="keywords" content="web, converters"> <title>InputZone - Web ffmpeg Beta</title> <meta name="description" content="Convert mp4,webm,mkv,mp3 and others Audio/Video with your web browser without sending any data." /> <link rel="import" href="packages/polymer/polymer.html"> <script src="packages/browser/dart.js"></script> <link rel="stylesheet" href="res/main.css" shim-shadowdom> <link href="/res/icon.png" rel="shortcut icon"/> <link rel="import" href="packages/inputzone/iz_app.html"> </head> <body touch-action="auto" unresolved fullbleed> <iz-app name="ffmpeg" pnaclbin="converters/ffmpeg/bin/ffmpeg.pexe.nmf" inputExt="" chdir="/" naclsize="10312460" isolated fit> <h1>ffmpeg beta</h1> <h2>Convert your video files</h2> <short>Version 2.1.3 - Original code by ffmpegTeam - </short> <div id="params" data-presets="/converters/ffmpeg/ffmpeg_presets.json"> </div> </iz-app> <script type="application/dart">export 'package:polymer/init.dart';</script> </body> </html>
Vloz/inputzone-client
web/ffmpeg.html
HTML
gpl-3.0
1,240
#!/bin/bash # ============================================================================ # Copyright © 2017, Robert Gollagher. # SPDX-License-Identifier: GPL-3.0+ # # Program: mk.sh # Copyright © Robert Gollagher 2017 # Author : Robert Gollagher robert.gollagher@freeputer.net # Created: 20150713 # Updated: 20170513-1710 # Version: pre-alpha-0.0.0.2 for FVM 2.0 # # Instructions # ============ # # Run this script to make a file called 'prgBase64.js' which declares # a JavaScript variable named prgBase64 and defines its value as a base64 # string representing a compiled Freelang program. # # Specify the Freelang source file to be compiled: # # ./mk.sh source.fl # # For this to work, 'flx.rb' (or a symbolic link to it) must exist # locally. The usual information produced by 'flx.rb' will also be produced, # namely the files 'debug.flx' and 'map.info'. # # The generated 'prgBase64.js' can be used by 'fvmui.html'. # # ============================================================================ if [ -z "$1" ] ; then echo "Must specify Freelang source to be compiled, such as: ./mk.sh source.fl" exit 1 fi ./flx.rb $1 rom.fp && echo "// Base64-encoded Freeputer program bytecode" > prgBase64.js && echo -n "var prgBase64 = \"" >> prgBase64.js && base64 -w 0 rom.fp >> prgBase64.js && echo "\";" >> prgBase64.js
RobertGollagher/Freeputer
pre-alpha/pre-alpha2.0/dev/fvm/js/mk.sh
Shell
gpl-3.0
1,351
<?php /** * @version $Id: default.php 2013-07-11 * @copyright Copyright (C) 2013 Leonardo Alviarez - Edén Arreaza. All Rights Reserved. * @license GNU General Public License version 3, or later * @note Note : All ini files need to be saved as UTF-8 - No BOM */ defined('_JEXEC') or die; // Include the component HTML helpers. JHtml::addIncludePath(JPATH_COMPONENT.'/helpers'); JHtml::_('behavior.framework'); JHtml::_('bootstrap.framework'); JHtml::_('bootstrap.framework'); //JHtml::_('jquery.ui'); $document = JFactory::getDocument(); $document->addStyleSheet('media/com_thorhospedaje/css/th_availabilityrooms.css'); $document->addStyleSheet('media/com_thorhospedaje/css/jquery-themes/jquery-ui.min.css'); $document->addStyleSheet(JURI::base().'media/jui/css/chosen.css'); $document->addScript('media/com_thorhospedaje/js/jquery-ui.min.js'); $document->addScript(JURI::base().'media/jui/js/chosen.jquery.js'); $document->addScriptDeclaration(" jQuery(document).ready(function($) { $('#checkin').datepicker({ numberOfMonths: 2, showButtonPanel: true, dateFormat: 'yy-mm-dd', minDate: new Date(), onClose: function( selectedDate ) { //var dateCheckin = $( '#checkout' ).datepicker('getDate'); var dateCheckout = new Date(Date.parse(selectedDate)); dateCheckout.setDate(dateCheckout.getDate() + 1); $( '#checkout' ).datepicker( 'option', 'minDate', dateCheckout); $( '#checkout' ).datepicker( 'setDate', dateCheckout); } }); $('#checkout').datepicker({ numberOfMonths: 2, showButtonPanel: true, dateFormat: 'yy-mm-dd', }); $('#country_id').chosen({ disable_search_threshold: 10, allow_single_deselect: true, }); $('#state_id').chosen({ disable_search_threshold: 10, allow_single_deselect: true, }); $('#th_asset_id').chosen({ disable_search_threshold: 10, allow_single_deselect: true, }); $('#n_adults').chosen({ disable_search_threshold: 10, allow_single_deselect: true, }); $('#n_childrens').chosen({ disable_search_threshold: 10, allow_single_deselect: true, }); $('#country_id').bind('change',function(){ var country_id = $('#country_id').val(); if (country_id == '') { country_id='-1' } $('#state_id').load('index.php?option=com_thorhospedaje&task=states.statesAjax&id_country='+country_id,function(){ $('#state_id').val('').trigger('liszt:updated'); $('#th_asset_id').empty(); $('#th_asset_id').html('<option value=\"\"></option>'); $('#th_asset_id').val('').trigger('liszt:updated'); }); }); $('#state_id').bind('change',function(){ var state_id = $('#state_id').val(); if (state_id == '') { state_id='-1' } $('#th_asset_id').load('index.php?option=com_thorhospedaje&task=assets.assetsAjax&id_state='+state_id,function(){ $('#th_asset_id').val('').trigger('liszt:updated'); }); }); }); "); ?> <form action="" method="GET" class="form-inline" style="background-color: rgb(255, 255, 255); border: 1px solid rgb(255, 204, 0); border-radius: 10px; box-shadow: 0px 0px 5px rgb(153, 153, 153); margin: 2% 1%; padding: 1%;"> <input type="hidden" name="option" value="com_thorhospedaje"> <input type="hidden" name="view" value="availabilityrooms"> <div class="row-fluid"> <div class="control-group"> <!-- <div class="span1"></div> --> <div class="span4"> <div class="control-label"><label for="country_id" title=""><?php echo JText::_('TH_AR_FIELD_COUNTRY_LABEL'); ?></label></div> <div class="controls"> <select name="country_id" id="country_id" data-no_results_text="<?php echo JText::_('TH_AR_FIELD_COUNTRY_NO_RESULTS_TEXT'); ?>" data-placeholder="<?php echo JText::_('TH_AR_FIELD_COUNTRY_PLACEHOLDER'); ?>"> <option value=""></option> <?php foreach($this->countries as $country): ?> <option value="<?php echo $country->id;?>"><?php echo $country->country;?></option> <?php endforeach; ?> </select> </div> </div> <div class="span4"> <div class="control-label"><label for="state_id" title=""><?php echo JText::_('TH_AR_FIELD_STATE_LABEL'); ?></label></div> <div class="controls"> <select name="state_id" id="state_id" data-no_results_text="<?php echo JText::_('TH_AR_FIELD_STATE_NO_RESULTS_TEXT'); ?>" data-placeholder="<?php echo JText::_('TH_AR_FIELD_STATE_PLACEHOLDER'); ?>"> <option></option> </select> </div> </div> <div class="span4"> <div class="control-label"><label for="th_asset_id" title=""><?php echo JText::_('TH_AR_FIELD_ASSET_LABEL'); ?></label></div> <div class="controls"> <select name="th_asset_id" id="th_asset_id" data-no_results_text="<?php echo JText::_('TH_AR_FIELD_ASSET_NO_RESULTS_TEXT'); ?>" data-placeholder="<?php echo JText::_('TH_AR_FIELD_ASSET_PLACEHOLDER'); ?>"> <option></option> </select> </div> </div> <!-- <div class="span1"></div> --> </div> </div> <br /> <div class="row-fluid"> <div class="control-group"> <div class="span3"></div> <div class="span4"> <div class="control-label"><label title="" for="checkin"><?php echo JText::_('TH_AR_FIELD_CHECKIN_LABEL'); ?></label></div> <div class="controls"><div class="input-append"> <input type="text" class="input-small" size="10" placeholder="yyyy/mm/dd" value="" id="checkin" name="checkin" title="" readonly="readonly"> <span class="add-on"><span class="icon-calendar"></span></span></div></div> </div> <div class="span3"> <div class="control-label"><label title="" for="checkout"><?php echo JText::_('TH_AR_FIELD_CHECKOUT_LABEL'); ?></label></div> <div class="controls"><div class="input-append"> <input type="text" class="input-small" size="10" placeholder="yyyy/mm/dd" value="" id="checkout" name="checkout" title="" readonly="readonly"> <span class="add-on"><span class="icon-calendar"></span></span></div></div> </div> <div class="span2"></div> </div> </div> <br /> <div class="row-fluid"> <div class="control-group"> <div class="span4"></div> <div class="span3"> <div class="control-label"><label title="" for="n_adults"><?php echo JText::_('TH_AR_FIELD_N_ADULTS_LABEL'); ?></label></div> <div class="controls"> <select class="input-mini" name="n_adults" id="n_adults" data-no_results_text="<?php echo JText::_('TH_AR_FIELD_N_ADULTS_NO_RESULTS_TEXT'); ?>" data-placeholder="<?php echo JText::_('TH_AR_FIELD_N_ADULTS_PLACEHOLDER'); ?>"> <option value="0"></option> <?php for($i=1;$i < 11; $i++): ?> <option value="<?php echo $i;?>"><?php echo $i;?></option> <?php endfor; ?> </select> </div> </div> <div class="span3"> <div class="control-label"><label title="" for="n_childrens"><?php echo JText::_('TH_AR_FIELD_N_CHILDRENS_LABEL'); ?></label></div> <div class="controls"> <select class="input-mini" name="n_childrens" id="n_childrens" data-no_results_text="<?php echo JText::_('TH_AR_FIELD_N_CHILDRENS_NO_RESULTS_TEXT'); ?>" data-placeholder="<?php echo JText::_('TH_AR_FIELD_N_CHILDRENS_PLACEHOLDER'); ?>"> <option value="0"></option> <?php for($i=1;$i < 11; $i++): ?> <option value="<?php echo $i;?>"><?php echo $i;?></option> <?php endfor; ?> </select> </div> </div> <div class="span2"></div> </div> </div> <div class="row-fluid"> <div class="control-group"> <div class="span5"></div> <div class="span2"> <div class="controls"> <button class="btn btn-primary btn" name="Submit" type="submit">&nbsp; &nbsp; <?php echo JText::_('TH_AR_FIELD_SEARCH_BUTTOM'); ?>&nbsp; &nbsp; </button> </div> </div> <div class="span1"></div> </div> </div> </form> <!-- <hr style="margin: 0px; border-width: 2px 0;"/> --> <?php echo $this->loadTemplate('assets'); ?>
lalviarez/thor_hospedaje
site/views/availabilityrooms/tmpl/default.php
PHP
gpl-3.0
7,513
-- -- Table structure for table galette_paypal_types_cotisation_prices -- DROP TABLE IF EXISTS galette_paypal_types_cotisation_prices; CREATE TABLE galette_paypal_types_cotisation_prices ( id_type_cotis integer REFERENCES galette_types_cotisation ON DELETE CASCADE, amount real DEFAULT '0', PRIMARY KEY (id_type_cotis) ); -- -- Table structure for table galette_paypal_history -- DROP SEQUENCE IF EXISTS galette_paypal_history_id_seq; CREATE SEQUENCE galette_paypal_history_id_seq START 1 INCREMENT 1 MAXVALUE 2147483647 MINVALUE 1 CACHE 1; DROP TABLE IF EXISTS galette_paypal_history; CREATE TABLE galette_paypal_history ( id_paypal integer DEFAULT nextval('galette_paypal_history_id_seq'::text) NOT NULL, history_date date NOT NULL, amount real NOT NULL, comments character varying(255), request text, signature character varying(255), state smallint DEFAULT 0 NOT NULL, PRIMARY KEY (id_paypal) ); -- -- Table structure for table `galette_paypal_preferences` -- DROP SEQUENCE IF EXISTS galette_paypal_preferences_id_seq; CREATE SEQUENCE galette_paypal_preferences_id_seq START 1 INCREMENT 1 MAXVALUE 2147483647 MINVALUE 1 CACHE 1; DROP TABLE IF EXISTS galette_paypal_preferences; CREATE TABLE galette_paypal_preferences ( id_pref integer DEFAULT nextval('galette_paypal_preferences_id_seq'::text) NOT NULL, nom_pref character varying(100) NOT NULL default '', val_pref character varying(200) NOT NULL default '', PRIMARY KEY (id_pref) ); CREATE UNIQUE INDEX galette_paypal_preferences_unique_idx ON galette_paypal_preferences (nom_pref); INSERT INTO galette_paypal_preferences (nom_pref, val_pref) VALUES ('paypal_id', ''); INSERT INTO galette_paypal_preferences (nom_pref, val_pref) VALUES ('paypal_inactives', '4,6,7');
galette/plugin-paypal
scripts/pgsql.sql
SQL
gpl-3.0
1,802
/** * @file * * Point cloud support for the Stanford PLY format. */ #if HAVE_CONFIG_H # include <config.h> #endif #include <vector> #include <string> #include <map> #include <istream> #include <sstream> #include <iterator> #include <algorithm> #include <boost/lexical_cast.hpp> #include <boost/utility.hpp> #include <boost/foreach.hpp> #include <stdexcept> #include "ply.h" #include "ascii_io.h" #include "binary_io.h" using namespace std; namespace PLY { namespace detail { /** * Wrapper around @c boost::lexical_cast that ensures that the result is * reversible. It can be used to validate user input, although it is * stricter than necessary (e.g. it will not accept leading zeros or * plus signs). It is probably not a good idea to use this for floating-point * values, since non-canonical representations are generally used. * * @param s The value to convert. */ template<typename T, typename S> static T validateLexicalCast(S s) { T t = boost::lexical_cast<T>(s); if (boost::lexical_cast<S>(t) != s) throw boost::bad_lexical_cast(); return t; } /** * Splits a string on whitespace, using operator>>. * * @param line The string to split. * @return A vector of tokens, not containing whitespace. */ static vector<string> splitLine(const string &line) { istringstream splitter(line); return vector<string>(istream_iterator<string>(splitter), istream_iterator<string>()); } /** * Maps the label for a type in the PLY header to a type token. * The types int, uint and float are mapped to INT32, UINT32 and FLOAT32 * respectively. * * @param t The name of the type from the PLY header. * @return The #FieldType value corresponding to @a t. * @throw #FormatError if @a t is not recognized. */ static FieldType parseType(const string &t) throw(FormatError) { if (t == "int8" || t == "char") return INT8; else if (t == "uint8" || t == "uchar") return UINT8; else if (t == "int16") return INT16; else if (t == "uint16") return UINT16; else if (t == "int32" || t == "int") return INT32; else if (t == "uint32" || t == "uint") return UINT32; else if (t == "float32" || t == "float") return FLOAT32; else if (t == "float64") return FLOAT64; else throw FormatError("Unknown type `" + t + "'"); } /** * Retrieve a line from the header, throwing a suitable exception on failure. * * @param in The input stream containing the header * @return A line from @a in * @throw FormatError on EOF * @throw std::ios::failure on other I/O error */ static string getHeaderLine(istream &in) throw(FormatError) { try { string line; getline(in, line); return line; } catch (ios::failure &e) { if (in.eof()) throw FormatError("End of file in PLY header"); else throw; } } } // namespace detail template<typename T> long ElementRangeReaderBase::PropertyAsLong::operator()(T) { return long(reader.readField<T>()); } void ElementRangeReaderBase::skip() { assert(getNumber() == 0 || &*reader.currentReader == this); PropertyAsLong convertHelper(reader); detail::FieldTypeFunction<PropertyAsLong> converter(convertHelper); while (&*reader.currentReader == this) { BOOST_FOREACH(const PropertyType &p, getProperties()) { // TODO: handle lists if (p.isList) { long length = converter(p.lengthType); for (long i = 0; i < length; i++) (void) converter(p.valueType); } else (void) converter(p.valueType); } reader.increment(); } } void Reader::increment() { assert(currentReader != end()); assert(currentPos < currentReader->getNumber()); ++currentPos; while (currentReader != end() && currentPos == currentReader->getNumber()) { ++currentReader; currentPos = 0; } } ElementRangeReaderBase &Reader::skipToBase(const std::string &name) { std::size_t currentIdx = currentReader - begin(); for (size_t i = 0; i < readers.size(); ++i) if (readers[i].getName() == name) { if (i < currentIdx) { // This is legal only if everything from i to currentIdx // is empty. bool legal = (currentPos == 0); for (size_t j = i; j < currentIdx && legal; j++) if (readers[j].getNumber()) legal = false; if (legal) return readers[i]; else throw FormatError("Element `" + name + "' has already been read"); } else { while (size_t(currentReader - begin()) < i) currentReader->skip(); if (currentPos > 0) { throw FormatError("Element `" + name + "' has already been started"); } return readers[i]; } } // Should hit one of the returns or throw above if we matched throw FormatError("No element called `" + name + "'"); } void Reader::addElement(const std::string &name, const std::tr1::uintmax_t number, const PropertyTypeSet &properties) { // Check for duplicates (TODO: use a SequencedMapType to speed this up?) BOOST_FOREACH(const ElementRangeReaderBase &e, readers) { if (e.getName() == name) throw FormatError("Duplicate element name `" + name + "'"); } boost::ptr_map<std::string, FactoryBase>::const_iterator factory = factories.find(name); if (factory == factories.end()) readers.push_back(new ElementRangeReader<EmptyBuilder>(*this, name, number, properties, EmptyBuilder())); else readers.push_back((*factory->second)(*this, name, number, properties)); } void Reader::readHeader() { using namespace detail; string elementName = ""; std::tr1::uintmax_t elementNumber = 0; PropertyTypeSet elementProperties; bool haveElement = false; in.exceptions(ios::failbit); string line = getHeaderLine(in); if (line != "ply") throw FormatError("PLY signature missing"); format = FILE_FORMAT_ASCII; // read the header while (true) { vector<string> tokens; line = getHeaderLine(in); tokens = splitLine(line); if (tokens.empty()) continue; // ignore blank lines if (tokens[0] == "end_header") break; else if (tokens[0] == "format") { if (tokens.size() != 3) throw FormatError("Malformed format line"); if (tokens[1] == "ascii") format = FILE_FORMAT_ASCII; else if (tokens[1] == "binary_big_endian") format = FILE_FORMAT_BIG_ENDIAN; else if (tokens[1] == "binary_little_endian") format = FILE_FORMAT_LITTLE_ENDIAN; else throw FormatError("Unknown PLY format " + tokens[1]); if (tokens[2] != "1.0") throw FormatError("Unknown PLY version " + tokens[2]); } else if (tokens[0] == "element") { if (haveElement) { addElement(elementName, elementNumber, elementProperties); haveElement = false; elementProperties.clear(); } if (tokens.size() != 3) throw FormatError("Malformed element line"); elementName = tokens[1]; try { elementNumber = validateLexicalCast<std::tr1::uintmax_t>(tokens[2]); } catch (boost::bad_lexical_cast &e) { throw FormatError("Malformed element line"); } haveElement = true; } else if (tokens[0] == "property") { PropertyType p; if (tokens.size() < 3) throw FormatError("Malformed property line"); if (tokens[1] == "list") { if (tokens.size() != 5) throw FormatError("Malformed property line"); p.isList = true; p.lengthType = parseType(tokens[2]); p.valueType = parseType(tokens[3]); if (p.lengthType == FLOAT32 || p.lengthType == FLOAT64) throw FormatError("List cannot have floating-point count"); p.name = tokens[4]; } else { if (tokens.size() != 3) throw FormatError("Malformed property line"); p.isList = false; p.lengthType = INT32; // unused, just to avoid undefined values p.valueType = parseType(tokens[1]); p.name = tokens[2]; } if (!haveElement) throw FormatError("Property `" + p.name + "' appears before any element declaration"); if (!elementProperties.push_back(p).second) throw FormatError("Duplicate property `" + p.name + "'"); } else if (tokens[0] == "comment" || tokens[0] == "obj_info") { /* Ignore comments */ } else { throw FormatError("Unknown header token `" + tokens[0] + "'"); } } if (haveElement) { addElement(elementName, elementNumber, elementProperties); } currentReader = begin(); currentPos = 0; while (currentReader != end() && currentPos == currentReader->getNumber()) { ++currentReader; currentPos = 0; } } } // namespace PLY
bmerry/mlsgpu
extras/ply.cpp
C++
gpl-3.0
9,765
/* Copyright (C) 2007-2011 Database Group - Universita' della Basilicata Giansalvatore Mecca - giansalvatore.mecca@unibas.it Salvatore Raunich - salrau@gmail.com This file is part of ++Spicy - a Schema Mapping and Data Exchange Tool ++Spicy 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 any later version. ++Spicy 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 ++Spicy. If not, see <http://www.gnu.org/licenses/>. */ // $ANTLR 3.3 Nov 30, 2010 12:45:30 D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g 2011-08-28 20:16:26 package it.unibas.spicy.parser.output; import it.unibas.spicy.model.expressions.Expression; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import it.unibas.spicy.parser.operators.IParseMappingTask; import it.unibas.spicy.parser.*; import org.antlr.runtime.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; import org.antlr.runtime.tree.*; public class TGDMappingTaskParser extends Parser { public static final String[] tokenNames = new String[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "FILEPATH", "NUMBER", "IDENTIFIER", "OPERATOR", "STRING", "NULL", "EXPRESSION", "LETTER", "DIGIT", "WHITESPACE", "LINE_COMMENT", "'Mapping task:'", "'Source schema:'", "'Source instance:'", "'Target schema:'", "'SOURCE TO TARGET TGDs:'", "'TARGET TGDs:'", "'SOURCE FDs:'", "'TARGET FDs:'", "'SOURCE INSTANCE:'", "'CONFIG:'", "'SOURCENULLS:'", "'SUBSUMPTIONS:'", "'COVERAGES:'", "'SELFJOINS:'", "'NOREWRITING:'", "'EGDS:'", "'OVERLAPS:'", "'SKOLEMSFOREGDS:'", "'SKOLEMSTRINGS:'", "'LOCALSKOLEMS:'", "'SORTSTRATEGY:'", "'SKOLEMTABLESTRATEGY:'", "'->'", "'.'", "','", "'and not exists'", "'('", "'with'", "')'", "'='", "'_'", "'\\$'", "':'", "'[pk]'", "'[key]'" }; public static final int EOF=-1; public static final int T__15=15; public static final int T__16=16; public static final int T__17=17; public static final int T__18=18; public static final int T__19=19; public static final int T__20=20; public static final int T__21=21; public static final int T__22=22; public static final int T__23=23; public static final int T__24=24; public static final int T__25=25; public static final int T__26=26; public static final int T__27=27; public static final int T__28=28; public static final int T__29=29; public static final int T__30=30; public static final int T__31=31; public static final int T__32=32; public static final int T__33=33; public static final int T__34=34; public static final int T__35=35; public static final int T__36=36; public static final int T__37=37; public static final int T__38=38; public static final int T__39=39; public static final int T__40=40; public static final int T__41=41; public static final int T__42=42; public static final int T__43=43; public static final int T__44=44; public static final int T__45=45; public static final int T__46=46; public static final int T__47=47; public static final int T__48=48; public static final int T__49=49; public static final int FILEPATH=4; public static final int NUMBER=5; public static final int IDENTIFIER=6; public static final int OPERATOR=7; public static final int STRING=8; public static final int NULL=9; public static final int EXPRESSION=10; public static final int LETTER=11; public static final int DIGIT=12; public static final int WHITESPACE=13; public static final int LINE_COMMENT=14; // delegates // delegators public TGDMappingTaskParser(TokenStream input) { this(input, new RecognizerSharedState()); } public TGDMappingTaskParser(TokenStream input, RecognizerSharedState state) { super(input, state); } protected TreeAdaptor adaptor = new CommonTreeAdaptor(); public void setTreeAdaptor(TreeAdaptor adaptor) { this.adaptor = adaptor; } public TreeAdaptor getTreeAdaptor() { return adaptor; } public String[] getTokenNames() { return TGDMappingTaskParser.tokenNames; } public String getGrammarFileName() { return "D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g"; } private static Log logger = LogFactory.getLog(TGDMappingTaskParser.class); private IParseMappingTask generator; private ParserTGD currentTGD; private ParserView currentView; private ParserAtom currentAtom; private ParserAttribute currentAttribute; private ParserBuiltinFunction currentFunction; private ParserBuiltinOperator currentOperator; private ParserArgument currentArgument; private List<ParserArgument> currentArgumentList; private ParserFact currentFact; private ParserFD currentFD; private ParserEquality currentEquality; private ParserInstance currentInstance; private List<String> currentStringList; private List<ParserFD> currentFDList; private List<ParserView> currentViewList; public void setGenerator(IParseMappingTask generator) { this.generator = generator; } public static class prog_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "prog" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:54:1: prog : mappingTask ; public final TGDMappingTaskParser.prog_return prog() throws RecognitionException { TGDMappingTaskParser.prog_return retval = new TGDMappingTaskParser.prog_return(); retval.start = input.LT(1); CommonTree root_0 = null; TGDMappingTaskParser.mappingTask_return mappingTask1 = null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:54:5: ( mappingTask ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:54:7: mappingTask { root_0 = (CommonTree)adaptor.nil(); pushFollow(FOLLOW_mappingTask_in_prog54); mappingTask1=mappingTask(); state._fsp--; adaptor.addChild(root_0, mappingTask1.getTree()); if (logger.isDebugEnabled()) logger.debug((mappingTask1!=null?((CommonTree)mappingTask1.tree):null).toStringTree()); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "prog" public static class mappingTask_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "mappingTask" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:56:1: mappingTask : 'Mapping task:' ( 'Source schema:' ssf= FILEPATH 'Source instance:' sif= FILEPATH )+ 'Target schema:' stf= FILEPATH 'SOURCE TO TARGET TGDs:' ( sttgd )+ ( 'TARGET TGDs:' ( ttgd )+ )? ( 'SOURCE FDs:' ( fd )+ )? ( 'TARGET FDs:' ( fd )+ )? ( 'SOURCE INSTANCE:' ( fact )+ )* ( 'CONFIG:' ( 'SOURCENULLS:' sourceNulls= NUMBER )? ( 'SUBSUMPTIONS:' subsumptions= NUMBER )? ( 'COVERAGES:' coverages= NUMBER )? ( 'SELFJOINS:' selfJoins= NUMBER )? ( 'NOREWRITING:' noRewriting= NUMBER )? ( 'EGDS:' egds= NUMBER )? ( 'OVERLAPS:' overlaps= NUMBER )? ( 'SKOLEMSFOREGDS:' skolemForEgds= NUMBER )? ( 'SKOLEMSTRINGS:' skolemStrings= NUMBER )? ( 'LOCALSKOLEMS:' localSkolems= NUMBER )? ( 'SORTSTRATEGY:' sortStrategy= NUMBER )? ( 'SKOLEMTABLESTRATEGY:' skolemTableStrategy= NUMBER )? )? ; public final TGDMappingTaskParser.mappingTask_return mappingTask() throws RecognitionException { TGDMappingTaskParser.mappingTask_return retval = new TGDMappingTaskParser.mappingTask_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token ssf=null; Token sif=null; Token stf=null; Token sourceNulls=null; Token subsumptions=null; Token coverages=null; Token selfJoins=null; Token noRewriting=null; Token egds=null; Token overlaps=null; Token skolemForEgds=null; Token skolemStrings=null; Token localSkolems=null; Token sortStrategy=null; Token skolemTableStrategy=null; Token string_literal2=null; Token string_literal3=null; Token string_literal4=null; Token string_literal5=null; Token string_literal6=null; Token string_literal8=null; Token string_literal10=null; Token string_literal12=null; Token string_literal14=null; Token string_literal16=null; Token string_literal17=null; Token string_literal18=null; Token string_literal19=null; Token string_literal20=null; Token string_literal21=null; Token string_literal22=null; Token string_literal23=null; Token string_literal24=null; Token string_literal25=null; Token string_literal26=null; Token string_literal27=null; Token string_literal28=null; TGDMappingTaskParser.sttgd_return sttgd7 = null; TGDMappingTaskParser.ttgd_return ttgd9 = null; TGDMappingTaskParser.fd_return fd11 = null; TGDMappingTaskParser.fd_return fd13 = null; TGDMappingTaskParser.fact_return fact15 = null; CommonTree ssf_tree=null; CommonTree sif_tree=null; CommonTree stf_tree=null; CommonTree sourceNulls_tree=null; CommonTree subsumptions_tree=null; CommonTree coverages_tree=null; CommonTree selfJoins_tree=null; CommonTree noRewriting_tree=null; CommonTree egds_tree=null; CommonTree overlaps_tree=null; CommonTree skolemForEgds_tree=null; CommonTree skolemStrings_tree=null; CommonTree localSkolems_tree=null; CommonTree sortStrategy_tree=null; CommonTree skolemTableStrategy_tree=null; CommonTree string_literal2_tree=null; CommonTree string_literal3_tree=null; CommonTree string_literal4_tree=null; CommonTree string_literal5_tree=null; CommonTree string_literal6_tree=null; CommonTree string_literal8_tree=null; CommonTree string_literal10_tree=null; CommonTree string_literal12_tree=null; CommonTree string_literal14_tree=null; CommonTree string_literal16_tree=null; CommonTree string_literal17_tree=null; CommonTree string_literal18_tree=null; CommonTree string_literal19_tree=null; CommonTree string_literal20_tree=null; CommonTree string_literal21_tree=null; CommonTree string_literal22_tree=null; CommonTree string_literal23_tree=null; CommonTree string_literal24_tree=null; CommonTree string_literal25_tree=null; CommonTree string_literal26_tree=null; CommonTree string_literal27_tree=null; CommonTree string_literal28_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:56:12: ( 'Mapping task:' ( 'Source schema:' ssf= FILEPATH 'Source instance:' sif= FILEPATH )+ 'Target schema:' stf= FILEPATH 'SOURCE TO TARGET TGDs:' ( sttgd )+ ( 'TARGET TGDs:' ( ttgd )+ )? ( 'SOURCE FDs:' ( fd )+ )? ( 'TARGET FDs:' ( fd )+ )? ( 'SOURCE INSTANCE:' ( fact )+ )* ( 'CONFIG:' ( 'SOURCENULLS:' sourceNulls= NUMBER )? ( 'SUBSUMPTIONS:' subsumptions= NUMBER )? ( 'COVERAGES:' coverages= NUMBER )? ( 'SELFJOINS:' selfJoins= NUMBER )? ( 'NOREWRITING:' noRewriting= NUMBER )? ( 'EGDS:' egds= NUMBER )? ( 'OVERLAPS:' overlaps= NUMBER )? ( 'SKOLEMSFOREGDS:' skolemForEgds= NUMBER )? ( 'SKOLEMSTRINGS:' skolemStrings= NUMBER )? ( 'LOCALSKOLEMS:' localSkolems= NUMBER )? ( 'SORTSTRATEGY:' sortStrategy= NUMBER )? ( 'SKOLEMTABLESTRATEGY:' skolemTableStrategy= NUMBER )? )? ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:56:17: 'Mapping task:' ( 'Source schema:' ssf= FILEPATH 'Source instance:' sif= FILEPATH )+ 'Target schema:' stf= FILEPATH 'SOURCE TO TARGET TGDs:' ( sttgd )+ ( 'TARGET TGDs:' ( ttgd )+ )? ( 'SOURCE FDs:' ( fd )+ )? ( 'TARGET FDs:' ( fd )+ )? ( 'SOURCE INSTANCE:' ( fact )+ )* ( 'CONFIG:' ( 'SOURCENULLS:' sourceNulls= NUMBER )? ( 'SUBSUMPTIONS:' subsumptions= NUMBER )? ( 'COVERAGES:' coverages= NUMBER )? ( 'SELFJOINS:' selfJoins= NUMBER )? ( 'NOREWRITING:' noRewriting= NUMBER )? ( 'EGDS:' egds= NUMBER )? ( 'OVERLAPS:' overlaps= NUMBER )? ( 'SKOLEMSFOREGDS:' skolemForEgds= NUMBER )? ( 'SKOLEMSTRINGS:' skolemStrings= NUMBER )? ( 'LOCALSKOLEMS:' localSkolems= NUMBER )? ( 'SORTSTRATEGY:' sortStrategy= NUMBER )? ( 'SKOLEMTABLESTRATEGY:' skolemTableStrategy= NUMBER )? )? { root_0 = (CommonTree)adaptor.nil(); string_literal2=(Token)match(input,15,FOLLOW_15_in_mappingTask68); string_literal2_tree = (CommonTree)adaptor.create(string_literal2); adaptor.addChild(root_0, string_literal2_tree); List<String> sourceSchemas = new ArrayList<String>(); List<String> sourceInstances = new ArrayList<String>(); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:61:10: ( 'Source schema:' ssf= FILEPATH 'Source instance:' sif= FILEPATH )+ int cnt1=0; loop1: do { int alt1=2; int LA1_0 = input.LA(1); if ( (LA1_0==16) ) { alt1=1; } switch (alt1) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:61:11: 'Source schema:' ssf= FILEPATH 'Source instance:' sif= FILEPATH { string_literal3=(Token)match(input,16,FOLLOW_16_in_mappingTask99); string_literal3_tree = (CommonTree)adaptor.create(string_literal3); adaptor.addChild(root_0, string_literal3_tree); ssf=(Token)match(input,FILEPATH,FOLLOW_FILEPATH_in_mappingTask103); ssf_tree = (CommonTree)adaptor.create(ssf); adaptor.addChild(root_0, ssf_tree); sourceSchemas.add(ssf.getText()); string_literal4=(Token)match(input,17,FOLLOW_17_in_mappingTask116); string_literal4_tree = (CommonTree)adaptor.create(string_literal4); adaptor.addChild(root_0, string_literal4_tree); sif=(Token)match(input,FILEPATH,FOLLOW_FILEPATH_in_mappingTask120); sif_tree = (CommonTree)adaptor.create(sif); adaptor.addChild(root_0, sif_tree); sourceInstances.add(sif.getText()); } break; default : if ( cnt1 >= 1 ) break loop1; EarlyExitException eee = new EarlyExitException(1, input); throw eee; } cnt1++; } while (true); string_literal5=(Token)match(input,18,FOLLOW_18_in_mappingTask135); string_literal5_tree = (CommonTree)adaptor.create(string_literal5); adaptor.addChild(root_0, string_literal5_tree); stf=(Token)match(input,FILEPATH,FOLLOW_FILEPATH_in_mappingTask139); stf_tree = (CommonTree)adaptor.create(stf); adaptor.addChild(root_0, stf_tree); try { generator.createMappingTask(sourceSchemas, sourceInstances, stf.getText()); } catch (Exception ex) { throw new ParserException(ex); } string_literal6=(Token)match(input,19,FOLLOW_19_in_mappingTask154); string_literal6_tree = (CommonTree)adaptor.create(string_literal6); adaptor.addChild(root_0, string_literal6_tree); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:70:35: ( sttgd )+ int cnt2=0; loop2: do { int alt2=2; int LA2_0 = input.LA(1); if ( (LA2_0==IDENTIFIER) ) { alt2=1; } switch (alt2) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:70:35: sttgd { pushFollow(FOLLOW_sttgd_in_mappingTask156); sttgd7=sttgd(); state._fsp--; adaptor.addChild(root_0, sttgd7.getTree()); } break; default : if ( cnt2 >= 1 ) break loop2; EarlyExitException eee = new EarlyExitException(2, input); throw eee; } cnt2++; } while (true); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:71:10: ( 'TARGET TGDs:' ( ttgd )+ )? int alt4=2; int LA4_0 = input.LA(1); if ( (LA4_0==20) ) { alt4=1; } switch (alt4) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:71:11: 'TARGET TGDs:' ( ttgd )+ { string_literal8=(Token)match(input,20,FOLLOW_20_in_mappingTask169); string_literal8_tree = (CommonTree)adaptor.create(string_literal8); adaptor.addChild(root_0, string_literal8_tree); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:71:26: ( ttgd )+ int cnt3=0; loop3: do { int alt3=2; int LA3_0 = input.LA(1); if ( (LA3_0==IDENTIFIER) ) { alt3=1; } switch (alt3) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:71:26: ttgd { pushFollow(FOLLOW_ttgd_in_mappingTask171); ttgd9=ttgd(); state._fsp--; adaptor.addChild(root_0, ttgd9.getTree()); } break; default : if ( cnt3 >= 1 ) break loop3; EarlyExitException eee = new EarlyExitException(3, input); throw eee; } cnt3++; } while (true); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:72:10: ( 'SOURCE FDs:' ( fd )+ )? int alt6=2; int LA6_0 = input.LA(1); if ( (LA6_0==21) ) { alt6=1; } switch (alt6) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:72:11: 'SOURCE FDs:' ( fd )+ { string_literal10=(Token)match(input,21,FOLLOW_21_in_mappingTask186); string_literal10_tree = (CommonTree)adaptor.create(string_literal10); adaptor.addChild(root_0, string_literal10_tree); currentFDList = new ArrayList<ParserFD>(); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:72:72: ( fd )+ int cnt5=0; loop5: do { int alt5=2; int LA5_0 = input.LA(1); if ( (LA5_0==IDENTIFIER) ) { alt5=1; } switch (alt5) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:72:72: fd { pushFollow(FOLLOW_fd_in_mappingTask190); fd11=fd(); state._fsp--; adaptor.addChild(root_0, fd11.getTree()); } break; default : if ( cnt5 >= 1 ) break loop5; EarlyExitException eee = new EarlyExitException(5, input); throw eee; } cnt5++; } while (true); generator.setSourceFDs(currentFDList); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:73:10: ( 'TARGET FDs:' ( fd )+ )? int alt8=2; int LA8_0 = input.LA(1); if ( (LA8_0==22) ) { alt8=1; } switch (alt8) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:73:11: 'TARGET FDs:' ( fd )+ { string_literal12=(Token)match(input,22,FOLLOW_22_in_mappingTask207); string_literal12_tree = (CommonTree)adaptor.create(string_literal12); adaptor.addChild(root_0, string_literal12_tree); currentFDList = new ArrayList<ParserFD>(); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:73:72: ( fd )+ int cnt7=0; loop7: do { int alt7=2; int LA7_0 = input.LA(1); if ( (LA7_0==IDENTIFIER) ) { alt7=1; } switch (alt7) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:73:72: fd { pushFollow(FOLLOW_fd_in_mappingTask211); fd13=fd(); state._fsp--; adaptor.addChild(root_0, fd13.getTree()); } break; default : if ( cnt7 >= 1 ) break loop7; EarlyExitException eee = new EarlyExitException(7, input); throw eee; } cnt7++; } while (true); generator.setTargetFDs(currentFDList); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:74:10: ( 'SOURCE INSTANCE:' ( fact )+ )* loop10: do { int alt10=2; int LA10_0 = input.LA(1); if ( (LA10_0==23) ) { alt10=1; } switch (alt10) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:74:11: 'SOURCE INSTANCE:' ( fact )+ { string_literal14=(Token)match(input,23,FOLLOW_23_in_mappingTask228); string_literal14_tree = (CommonTree)adaptor.create(string_literal14); adaptor.addChild(root_0, string_literal14_tree); currentInstance = new ParserInstance(); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:74:74: ( fact )+ int cnt9=0; loop9: do { int alt9=2; int LA9_0 = input.LA(1); if ( (LA9_0==IDENTIFIER) ) { alt9=1; } switch (alt9) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:74:74: fact { pushFollow(FOLLOW_fact_in_mappingTask232); fact15=fact(); state._fsp--; adaptor.addChild(root_0, fact15.getTree()); } break; default : if ( cnt9 >= 1 ) break loop9; EarlyExitException eee = new EarlyExitException(9, input); throw eee; } cnt9++; } while (true); generator.addSourceInstance(currentInstance); } break; default : break loop10; } } while (true); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:75:10: ( 'CONFIG:' ( 'SOURCENULLS:' sourceNulls= NUMBER )? ( 'SUBSUMPTIONS:' subsumptions= NUMBER )? ( 'COVERAGES:' coverages= NUMBER )? ( 'SELFJOINS:' selfJoins= NUMBER )? ( 'NOREWRITING:' noRewriting= NUMBER )? ( 'EGDS:' egds= NUMBER )? ( 'OVERLAPS:' overlaps= NUMBER )? ( 'SKOLEMSFOREGDS:' skolemForEgds= NUMBER )? ( 'SKOLEMSTRINGS:' skolemStrings= NUMBER )? ( 'LOCALSKOLEMS:' localSkolems= NUMBER )? ( 'SORTSTRATEGY:' sortStrategy= NUMBER )? ( 'SKOLEMTABLESTRATEGY:' skolemTableStrategy= NUMBER )? )? int alt23=2; int LA23_0 = input.LA(1); if ( (LA23_0==24) ) { alt23=1; } switch (alt23) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:75:11: 'CONFIG:' ( 'SOURCENULLS:' sourceNulls= NUMBER )? ( 'SUBSUMPTIONS:' subsumptions= NUMBER )? ( 'COVERAGES:' coverages= NUMBER )? ( 'SELFJOINS:' selfJoins= NUMBER )? ( 'NOREWRITING:' noRewriting= NUMBER )? ( 'EGDS:' egds= NUMBER )? ( 'OVERLAPS:' overlaps= NUMBER )? ( 'SKOLEMSFOREGDS:' skolemForEgds= NUMBER )? ( 'SKOLEMSTRINGS:' skolemStrings= NUMBER )? ( 'LOCALSKOLEMS:' localSkolems= NUMBER )? ( 'SORTSTRATEGY:' sortStrategy= NUMBER )? ( 'SKOLEMTABLESTRATEGY:' skolemTableStrategy= NUMBER )? { string_literal16=(Token)match(input,24,FOLLOW_24_in_mappingTask249); string_literal16_tree = (CommonTree)adaptor.create(string_literal16); adaptor.addChild(root_0, string_literal16_tree); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:76:13: ( 'SOURCENULLS:' sourceNulls= NUMBER )? int alt11=2; int LA11_0 = input.LA(1); if ( (LA11_0==25) ) { alt11=1; } switch (alt11) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:76:14: 'SOURCENULLS:' sourceNulls= NUMBER { string_literal17=(Token)match(input,25,FOLLOW_25_in_mappingTask264); string_literal17_tree = (CommonTree)adaptor.create(string_literal17); adaptor.addChild(root_0, string_literal17_tree); sourceNulls=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask268); sourceNulls_tree = (CommonTree)adaptor.create(sourceNulls); adaptor.addChild(root_0, sourceNulls_tree); generator.setSourceNulls(sourceNulls.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:77:13: ( 'SUBSUMPTIONS:' subsumptions= NUMBER )? int alt12=2; int LA12_0 = input.LA(1); if ( (LA12_0==26) ) { alt12=1; } switch (alt12) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:77:14: 'SUBSUMPTIONS:' subsumptions= NUMBER { string_literal18=(Token)match(input,26,FOLLOW_26_in_mappingTask287); string_literal18_tree = (CommonTree)adaptor.create(string_literal18); adaptor.addChild(root_0, string_literal18_tree); subsumptions=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask291); subsumptions_tree = (CommonTree)adaptor.create(subsumptions); adaptor.addChild(root_0, subsumptions_tree); generator.setSubsumptions(subsumptions.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:78:13: ( 'COVERAGES:' coverages= NUMBER )? int alt13=2; int LA13_0 = input.LA(1); if ( (LA13_0==27) ) { alt13=1; } switch (alt13) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:78:14: 'COVERAGES:' coverages= NUMBER { string_literal19=(Token)match(input,27,FOLLOW_27_in_mappingTask311); string_literal19_tree = (CommonTree)adaptor.create(string_literal19); adaptor.addChild(root_0, string_literal19_tree); coverages=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask315); coverages_tree = (CommonTree)adaptor.create(coverages); adaptor.addChild(root_0, coverages_tree); generator.setCoverages(coverages.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:79:13: ( 'SELFJOINS:' selfJoins= NUMBER )? int alt14=2; int LA14_0 = input.LA(1); if ( (LA14_0==28) ) { alt14=1; } switch (alt14) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:79:14: 'SELFJOINS:' selfJoins= NUMBER { string_literal20=(Token)match(input,28,FOLLOW_28_in_mappingTask335); string_literal20_tree = (CommonTree)adaptor.create(string_literal20); adaptor.addChild(root_0, string_literal20_tree); selfJoins=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask339); selfJoins_tree = (CommonTree)adaptor.create(selfJoins); adaptor.addChild(root_0, selfJoins_tree); generator.setSelfJoins(selfJoins.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:80:13: ( 'NOREWRITING:' noRewriting= NUMBER )? int alt15=2; int LA15_0 = input.LA(1); if ( (LA15_0==29) ) { alt15=1; } switch (alt15) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:80:14: 'NOREWRITING:' noRewriting= NUMBER { string_literal21=(Token)match(input,29,FOLLOW_29_in_mappingTask358); string_literal21_tree = (CommonTree)adaptor.create(string_literal21); adaptor.addChild(root_0, string_literal21_tree); noRewriting=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask362); noRewriting_tree = (CommonTree)adaptor.create(noRewriting); adaptor.addChild(root_0, noRewriting_tree); generator.setNoRewriting(noRewriting.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:81:13: ( 'EGDS:' egds= NUMBER )? int alt16=2; int LA16_0 = input.LA(1); if ( (LA16_0==30) ) { alt16=1; } switch (alt16) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:81:14: 'EGDS:' egds= NUMBER { string_literal22=(Token)match(input,30,FOLLOW_30_in_mappingTask382); string_literal22_tree = (CommonTree)adaptor.create(string_literal22); adaptor.addChild(root_0, string_literal22_tree); egds=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask386); egds_tree = (CommonTree)adaptor.create(egds); adaptor.addChild(root_0, egds_tree); generator.setEgds(egds.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:82:13: ( 'OVERLAPS:' overlaps= NUMBER )? int alt17=2; int LA17_0 = input.LA(1); if ( (LA17_0==31) ) { alt17=1; } switch (alt17) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:82:14: 'OVERLAPS:' overlaps= NUMBER { string_literal23=(Token)match(input,31,FOLLOW_31_in_mappingTask405); string_literal23_tree = (CommonTree)adaptor.create(string_literal23); adaptor.addChild(root_0, string_literal23_tree); overlaps=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask409); overlaps_tree = (CommonTree)adaptor.create(overlaps); adaptor.addChild(root_0, overlaps_tree); generator.setOverlaps(overlaps.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:83:13: ( 'SKOLEMSFOREGDS:' skolemForEgds= NUMBER )? int alt18=2; int LA18_0 = input.LA(1); if ( (LA18_0==32) ) { alt18=1; } switch (alt18) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:83:14: 'SKOLEMSFOREGDS:' skolemForEgds= NUMBER { string_literal24=(Token)match(input,32,FOLLOW_32_in_mappingTask428); string_literal24_tree = (CommonTree)adaptor.create(string_literal24); adaptor.addChild(root_0, string_literal24_tree); skolemForEgds=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask432); skolemForEgds_tree = (CommonTree)adaptor.create(skolemForEgds); adaptor.addChild(root_0, skolemForEgds_tree); generator.setSkolemsForEgds(skolemForEgds.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:84:13: ( 'SKOLEMSTRINGS:' skolemStrings= NUMBER )? int alt19=2; int LA19_0 = input.LA(1); if ( (LA19_0==33) ) { alt19=1; } switch (alt19) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:84:14: 'SKOLEMSTRINGS:' skolemStrings= NUMBER { string_literal25=(Token)match(input,33,FOLLOW_33_in_mappingTask451); string_literal25_tree = (CommonTree)adaptor.create(string_literal25); adaptor.addChild(root_0, string_literal25_tree); skolemStrings=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask455); skolemStrings_tree = (CommonTree)adaptor.create(skolemStrings); adaptor.addChild(root_0, skolemStrings_tree); generator.setSkolemStrings(skolemStrings.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:85:13: ( 'LOCALSKOLEMS:' localSkolems= NUMBER )? int alt20=2; int LA20_0 = input.LA(1); if ( (LA20_0==34) ) { alt20=1; } switch (alt20) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:85:14: 'LOCALSKOLEMS:' localSkolems= NUMBER { string_literal26=(Token)match(input,34,FOLLOW_34_in_mappingTask474); string_literal26_tree = (CommonTree)adaptor.create(string_literal26); adaptor.addChild(root_0, string_literal26_tree); localSkolems=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask478); localSkolems_tree = (CommonTree)adaptor.create(localSkolems); adaptor.addChild(root_0, localSkolems_tree); generator.setLocalSkolems(localSkolems.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:86:13: ( 'SORTSTRATEGY:' sortStrategy= NUMBER )? int alt21=2; int LA21_0 = input.LA(1); if ( (LA21_0==35) ) { alt21=1; } switch (alt21) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:86:14: 'SORTSTRATEGY:' sortStrategy= NUMBER { string_literal27=(Token)match(input,35,FOLLOW_35_in_mappingTask497); string_literal27_tree = (CommonTree)adaptor.create(string_literal27); adaptor.addChild(root_0, string_literal27_tree); sortStrategy=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask501); sortStrategy_tree = (CommonTree)adaptor.create(sortStrategy); adaptor.addChild(root_0, sortStrategy_tree); generator.setSortStrategy(sortStrategy.getText()); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:87:13: ( 'SKOLEMTABLESTRATEGY:' skolemTableStrategy= NUMBER )? int alt22=2; int LA22_0 = input.LA(1); if ( (LA22_0==36) ) { alt22=1; } switch (alt22) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:87:14: 'SKOLEMTABLESTRATEGY:' skolemTableStrategy= NUMBER { string_literal28=(Token)match(input,36,FOLLOW_36_in_mappingTask520); string_literal28_tree = (CommonTree)adaptor.create(string_literal28); adaptor.addChild(root_0, string_literal28_tree); skolemTableStrategy=(Token)match(input,NUMBER,FOLLOW_NUMBER_in_mappingTask524); skolemTableStrategy_tree = (CommonTree)adaptor.create(skolemTableStrategy); adaptor.addChild(root_0, skolemTableStrategy_tree); generator.setSkolemTableStrategy(skolemTableStrategy.getText()); } break; } } break; } generator.processTGDs(); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "mappingTask" public static class sttgd_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "sttgd" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:91:1: sttgd : view ( negatedview )* '->' view '.' ; public final TGDMappingTaskParser.sttgd_return sttgd() throws RecognitionException { TGDMappingTaskParser.sttgd_return retval = new TGDMappingTaskParser.sttgd_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token string_literal31=null; Token char_literal33=null; TGDMappingTaskParser.view_return view29 = null; TGDMappingTaskParser.negatedview_return negatedview30 = null; TGDMappingTaskParser.view_return view32 = null; CommonTree string_literal31_tree=null; CommonTree char_literal33_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:91:6: ( view ( negatedview )* '->' view '.' ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:91:10: view ( negatedview )* '->' view '.' { root_0 = (CommonTree)adaptor.nil(); currentTGD = new ParserTGD(); currentView = new ParserView(); pushFollow(FOLLOW_view_in_sttgd557); view29=view(); state._fsp--; adaptor.addChild(root_0, view29.getTree()); currentTGD.setSourceView(currentView.clone()); currentViewList = new ArrayList<ParserView>(); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:94:17: ( negatedview )* loop24: do { int alt24=2; int LA24_0 = input.LA(1); if ( (LA24_0==40) ) { alt24=1; } switch (alt24) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:94:19: negatedview { pushFollow(FOLLOW_negatedview_in_sttgd585); negatedview30=negatedview(); state._fsp--; adaptor.addChild(root_0, negatedview30.getTree()); currentTGD.addNegatedSourceView (currentView.clone()); currentViewList = new ArrayList<ParserView>(); } break; default : break loop24; } } while (true); string_literal31=(Token)match(input,37,FOLLOW_37_in_sttgd594); string_literal31_tree = (CommonTree)adaptor.create(string_literal31); adaptor.addChild(root_0, string_literal31_tree); currentView = new ParserView(); pushFollow(FOLLOW_view_in_sttgd598); view32=view(); state._fsp--; adaptor.addChild(root_0, view32.getTree()); char_literal33=(Token)match(input,38,FOLLOW_38_in_sttgd600); char_literal33_tree = (CommonTree)adaptor.create(char_literal33); adaptor.addChild(root_0, char_literal33_tree); currentTGD.setTargetView(currentView.clone()); generator.addSTTGD(currentTGD); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "sttgd" public static class ttgd_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "ttgd" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:98:1: ttgd : atom '->' atom '.' ; public final TGDMappingTaskParser.ttgd_return ttgd() throws RecognitionException { TGDMappingTaskParser.ttgd_return retval = new TGDMappingTaskParser.ttgd_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token string_literal35=null; Token char_literal37=null; TGDMappingTaskParser.atom_return atom34 = null; TGDMappingTaskParser.atom_return atom36 = null; CommonTree string_literal35_tree=null; CommonTree char_literal37_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:98:5: ( atom '->' atom '.' ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:98:9: atom '->' atom '.' { root_0 = (CommonTree)adaptor.nil(); currentTGD = new ParserTGD(); currentView = new ParserView(); pushFollow(FOLLOW_atom_in_ttgd617); atom34=atom(); state._fsp--; adaptor.addChild(root_0, atom34.getTree()); currentTGD.setSourceView(currentView.clone()); currentView = new ParserView(); string_literal35=(Token)match(input,37,FOLLOW_37_in_ttgd623); string_literal35_tree = (CommonTree)adaptor.create(string_literal35); adaptor.addChild(root_0, string_literal35_tree); pushFollow(FOLLOW_atom_in_ttgd625); atom36=atom(); state._fsp--; adaptor.addChild(root_0, atom36.getTree()); char_literal37=(Token)match(input,38,FOLLOW_38_in_ttgd627); char_literal37_tree = (CommonTree)adaptor.create(char_literal37); adaptor.addChild(root_0, char_literal37_tree); currentTGD.setTargetView(currentView.clone()); generator.addTargetTGD(currentTGD); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "ttgd" public static class view_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "view" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:104:1: view : atom ( ',' ( atom | builtin ) )* ; public final TGDMappingTaskParser.view_return view() throws RecognitionException { TGDMappingTaskParser.view_return retval = new TGDMappingTaskParser.view_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token char_literal39=null; TGDMappingTaskParser.atom_return atom38 = null; TGDMappingTaskParser.atom_return atom40 = null; TGDMappingTaskParser.builtin_return builtin41 = null; CommonTree char_literal39_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:104:5: ( atom ( ',' ( atom | builtin ) )* ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:104:15: atom ( ',' ( atom | builtin ) )* { root_0 = (CommonTree)adaptor.nil(); pushFollow(FOLLOW_atom_in_view647); atom38=atom(); state._fsp--; adaptor.addChild(root_0, atom38.getTree()); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:104:21: ( ',' ( atom | builtin ) )* loop26: do { int alt26=2; int LA26_0 = input.LA(1); if ( (LA26_0==39) ) { alt26=1; } switch (alt26) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:104:22: ',' ( atom | builtin ) { char_literal39=(Token)match(input,39,FOLLOW_39_in_view651); char_literal39_tree = (CommonTree)adaptor.create(char_literal39); adaptor.addChild(root_0, char_literal39_tree); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:104:26: ( atom | builtin ) int alt25=2; int LA25_0 = input.LA(1); if ( (LA25_0==IDENTIFIER) ) { alt25=1; } else if ( (LA25_0==NUMBER||LA25_0==STRING||(LA25_0>=45 && LA25_0<=46)) ) { alt25=2; } else { NoViableAltException nvae = new NoViableAltException("", 25, 0, input); throw nvae; } switch (alt25) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:104:27: atom { pushFollow(FOLLOW_atom_in_view654); atom40=atom(); state._fsp--; adaptor.addChild(root_0, atom40.getTree()); } break; case 2 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:104:34: builtin { pushFollow(FOLLOW_builtin_in_view658); builtin41=builtin(); state._fsp--; adaptor.addChild(root_0, builtin41.getTree()); } break; } } break; default : break loop26; } } while (true); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "view" public static class negatedview_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "negatedview" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:106:1: negatedview : 'and not exists' '(' ( view ( negatedview )* ( 'with' equalities )? ) ')' ; public final TGDMappingTaskParser.negatedview_return negatedview() throws RecognitionException { TGDMappingTaskParser.negatedview_return retval = new TGDMappingTaskParser.negatedview_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token string_literal42=null; Token char_literal43=null; Token string_literal46=null; Token char_literal48=null; TGDMappingTaskParser.view_return view44 = null; TGDMappingTaskParser.negatedview_return negatedview45 = null; TGDMappingTaskParser.equalities_return equalities47 = null; CommonTree string_literal42_tree=null; CommonTree char_literal43_tree=null; CommonTree string_literal46_tree=null; CommonTree char_literal48_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:106:12: ( 'and not exists' '(' ( view ( negatedview )* ( 'with' equalities )? ) ')' ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:106:17: 'and not exists' '(' ( view ( negatedview )* ( 'with' equalities )? ) ')' { root_0 = (CommonTree)adaptor.nil(); string_literal42=(Token)match(input,40,FOLLOW_40_in_negatedview672); string_literal42_tree = (CommonTree)adaptor.create(string_literal42); adaptor.addChild(root_0, string_literal42_tree); char_literal43=(Token)match(input,41,FOLLOW_41_in_negatedview673); char_literal43_tree = (CommonTree)adaptor.create(char_literal43); adaptor.addChild(root_0, char_literal43_tree); currentView = new ParserView(); currentViewList.add(currentView); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:107:17: ( view ( negatedview )* ( 'with' equalities )? ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:107:19: view ( negatedview )* ( 'with' equalities )? { pushFollow(FOLLOW_view_in_negatedview695); view44=view(); state._fsp--; adaptor.addChild(root_0, view44.getTree()); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:108:19: ( negatedview )* loop27: do { int alt27=2; int LA27_0 = input.LA(1); if ( (LA27_0==40) ) { alt27=1; } switch (alt27) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:108:21: negatedview { pushFollow(FOLLOW_negatedview_in_negatedview718); negatedview45=negatedview(); state._fsp--; adaptor.addChild(root_0, negatedview45.getTree()); currentViewList.get(currentViewList.size() - 2).addSubView(currentView); currentView = currentViewList.get(currentViewList.size() - 2); currentViewList.remove(currentViewList.size() - 1); } break; default : break loop27; } } while (true); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:115:17: ( 'with' equalities )? int alt28=2; int LA28_0 = input.LA(1); if ( (LA28_0==42) ) { alt28=1; } switch (alt28) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:115:18: 'with' equalities { string_literal46=(Token)match(input,42,FOLLOW_42_in_negatedview783); string_literal46_tree = (CommonTree)adaptor.create(string_literal46); adaptor.addChild(root_0, string_literal46_tree); pushFollow(FOLLOW_equalities_in_negatedview785); equalities47=equalities(); state._fsp--; adaptor.addChild(root_0, equalities47.getTree()); } break; } } char_literal48=(Token)match(input,43,FOLLOW_43_in_negatedview790); char_literal48_tree = (CommonTree)adaptor.create(char_literal48); adaptor.addChild(root_0, char_literal48_tree); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "negatedview" public static class equalities_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "equalities" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:117:1: equalities : equality ( ',' equality )* ; public final TGDMappingTaskParser.equalities_return equalities() throws RecognitionException { TGDMappingTaskParser.equalities_return retval = new TGDMappingTaskParser.equalities_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token char_literal50=null; TGDMappingTaskParser.equality_return equality49 = null; TGDMappingTaskParser.equality_return equality51 = null; CommonTree char_literal50_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:117:11: ( equality ( ',' equality )* ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:117:13: equality ( ',' equality )* { root_0 = (CommonTree)adaptor.nil(); pushFollow(FOLLOW_equality_in_equalities798); equality49=equality(); state._fsp--; adaptor.addChild(root_0, equality49.getTree()); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:117:22: ( ',' equality )* loop29: do { int alt29=2; int LA29_0 = input.LA(1); if ( (LA29_0==39) ) { alt29=1; } switch (alt29) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:117:23: ',' equality { char_literal50=(Token)match(input,39,FOLLOW_39_in_equalities801); char_literal50_tree = (CommonTree)adaptor.create(char_literal50); adaptor.addChild(root_0, char_literal50_tree); pushFollow(FOLLOW_equality_in_equalities804); equality51=equality(); state._fsp--; adaptor.addChild(root_0, equality51.getTree()); } break; default : break loop29; } } while (true); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "equalities" public static class equality_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "equality" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:119:1: equality : ( value '=' value ) ; public final TGDMappingTaskParser.equality_return equality() throws RecognitionException { TGDMappingTaskParser.equality_return retval = new TGDMappingTaskParser.equality_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token char_literal53=null; TGDMappingTaskParser.value_return value52 = null; TGDMappingTaskParser.value_return value54 = null; CommonTree char_literal53_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:119:9: ( ( value '=' value ) ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:119:11: ( value '=' value ) { root_0 = (CommonTree)adaptor.nil(); currentEquality = new ParserEquality(); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:120:17: ( value '=' value ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:120:19: value '=' value { currentAttribute = new ParserAttribute(""); pushFollow(FOLLOW_value_in_equality837); value52=value(); state._fsp--; adaptor.addChild(root_0, value52.getTree()); currentEquality.setLeftAttribute(currentAttribute); char_literal53=(Token)match(input,44,FOLLOW_44_in_equality859); char_literal53_tree = (CommonTree)adaptor.create(char_literal53); adaptor.addChild(root_0, char_literal53_tree); currentAttribute = new ParserAttribute(""); pushFollow(FOLLOW_value_in_equality881); value54=value(); state._fsp--; adaptor.addChild(root_0, value54.getTree()); currentEquality.setRightAttribute(currentAttribute); } currentView.addEquality(currentEquality); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "equality" public static class atom_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "atom" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:125:1: atom : name= IDENTIFIER '(' attribute ( ',' attribute )* ')' ; public final TGDMappingTaskParser.atom_return atom() throws RecognitionException { TGDMappingTaskParser.atom_return retval = new TGDMappingTaskParser.atom_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token name=null; Token char_literal55=null; Token char_literal57=null; Token char_literal59=null; TGDMappingTaskParser.attribute_return attribute56 = null; TGDMappingTaskParser.attribute_return attribute58 = null; CommonTree name_tree=null; CommonTree char_literal55_tree=null; CommonTree char_literal57_tree=null; CommonTree char_literal59_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:125:5: (name= IDENTIFIER '(' attribute ( ',' attribute )* ')' ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:125:8: name= IDENTIFIER '(' attribute ( ',' attribute )* ')' { root_0 = (CommonTree)adaptor.nil(); name=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_atom912); name_tree = (CommonTree)adaptor.create(name); adaptor.addChild(root_0, name_tree); currentAtom = new ParserAtom(name.getText()); char_literal55=(Token)match(input,41,FOLLOW_41_in_atom916); char_literal55_tree = (CommonTree)adaptor.create(char_literal55); adaptor.addChild(root_0, char_literal55_tree); pushFollow(FOLLOW_attribute_in_atom918); attribute56=attribute(); state._fsp--; adaptor.addChild(root_0, attribute56.getTree()); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:125:88: ( ',' attribute )* loop30: do { int alt30=2; int LA30_0 = input.LA(1); if ( (LA30_0==39) ) { alt30=1; } switch (alt30) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:125:89: ',' attribute { char_literal57=(Token)match(input,39,FOLLOW_39_in_atom921); char_literal57_tree = (CommonTree)adaptor.create(char_literal57); adaptor.addChild(root_0, char_literal57_tree); pushFollow(FOLLOW_attribute_in_atom923); attribute58=attribute(); state._fsp--; adaptor.addChild(root_0, attribute58.getTree()); } break; default : break loop30; } } while (true); char_literal59=(Token)match(input,43,FOLLOW_43_in_atom927); char_literal59_tree = (CommonTree)adaptor.create(char_literal59); adaptor.addChild(root_0, char_literal59_tree); currentView.addAtom(currentAtom); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "atom" public static class builtin_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "builtin" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:128:1: builtin : ( '_' func= IDENTIFIER '(' ( argument )+ ')' | argument oper= OPERATOR argument ) ; public final TGDMappingTaskParser.builtin_return builtin() throws RecognitionException { TGDMappingTaskParser.builtin_return retval = new TGDMappingTaskParser.builtin_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token func=null; Token oper=null; Token char_literal60=null; Token char_literal61=null; Token char_literal63=null; TGDMappingTaskParser.argument_return argument62 = null; TGDMappingTaskParser.argument_return argument64 = null; TGDMappingTaskParser.argument_return argument65 = null; CommonTree func_tree=null; CommonTree oper_tree=null; CommonTree char_literal60_tree=null; CommonTree char_literal61_tree=null; CommonTree char_literal63_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:128:9: ( ( '_' func= IDENTIFIER '(' ( argument )+ ')' | argument oper= OPERATOR argument ) ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:128:11: ( '_' func= IDENTIFIER '(' ( argument )+ ')' | argument oper= OPERATOR argument ) { root_0 = (CommonTree)adaptor.nil(); currentArgumentList = new ArrayList<ParserArgument>(); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:129:17: ( '_' func= IDENTIFIER '(' ( argument )+ ')' | argument oper= OPERATOR argument ) int alt32=2; int LA32_0 = input.LA(1); if ( (LA32_0==45) ) { alt32=1; } else if ( (LA32_0==NUMBER||LA32_0==STRING||LA32_0==46) ) { alt32=2; } else { NoViableAltException nvae = new NoViableAltException("", 32, 0, input); throw nvae; } switch (alt32) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:129:18: '_' func= IDENTIFIER '(' ( argument )+ ')' { char_literal60=(Token)match(input,45,FOLLOW_45_in_builtin958); char_literal60_tree = (CommonTree)adaptor.create(char_literal60); adaptor.addChild(root_0, char_literal60_tree); func=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_builtin961); func_tree = (CommonTree)adaptor.create(func); adaptor.addChild(root_0, func_tree); char_literal61=(Token)match(input,41,FOLLOW_41_in_builtin963); char_literal61_tree = (CommonTree)adaptor.create(char_literal61); adaptor.addChild(root_0, char_literal61_tree); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:129:41: ( argument )+ int cnt31=0; loop31: do { int alt31=2; int LA31_0 = input.LA(1); if ( (LA31_0==NUMBER||LA31_0==STRING||LA31_0==46) ) { alt31=1; } switch (alt31) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:129:41: argument { pushFollow(FOLLOW_argument_in_builtin965); argument62=argument(); state._fsp--; adaptor.addChild(root_0, argument62.getTree()); } break; default : if ( cnt31 >= 1 ) break loop31; EarlyExitException eee = new EarlyExitException(31, input); throw eee; } cnt31++; } while (true); char_literal63=(Token)match(input,43,FOLLOW_43_in_builtin968); char_literal63_tree = (CommonTree)adaptor.create(char_literal63); adaptor.addChild(root_0, char_literal63_tree); currentFunction = new ParserBuiltinFunction(func.getText(), currentArgumentList); currentView.addFunction(currentFunction); } break; case 2 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:131:17: argument oper= OPERATOR argument { currentOperator = new ParserBuiltinOperator(); pushFollow(FOLLOW_argument_in_builtin1024); argument64=argument(); state._fsp--; adaptor.addChild(root_0, argument64.getTree()); currentOperator.setFirstArgument(currentArgumentList.get(0)); oper=(Token)match(input,OPERATOR,FOLLOW_OPERATOR_in_builtin1046); oper_tree = (CommonTree)adaptor.create(oper); adaptor.addChild(root_0, oper_tree); currentOperator.setOperator(oper.getText()); pushFollow(FOLLOW_argument_in_builtin1066); argument65=argument(); state._fsp--; adaptor.addChild(root_0, argument65.getTree()); currentOperator.setSecondArgument(currentArgumentList.get(1)); currentView.addOperator(currentOperator); } break; } } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "builtin" public static class argument_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "argument" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:138:1: argument : ( '\\$' var= IDENTIFIER | constant= ( STRING | NUMBER ) ) ; public final TGDMappingTaskParser.argument_return argument() throws RecognitionException { TGDMappingTaskParser.argument_return retval = new TGDMappingTaskParser.argument_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token var=null; Token constant=null; Token char_literal66=null; CommonTree var_tree=null; CommonTree constant_tree=null; CommonTree char_literal66_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:138:9: ( ( '\\$' var= IDENTIFIER | constant= ( STRING | NUMBER ) ) ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:138:11: ( '\\$' var= IDENTIFIER | constant= ( STRING | NUMBER ) ) { root_0 = (CommonTree)adaptor.nil(); currentArgument = new ParserArgument(); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:139:17: ( '\\$' var= IDENTIFIER | constant= ( STRING | NUMBER ) ) int alt33=2; int LA33_0 = input.LA(1); if ( (LA33_0==46) ) { alt33=1; } else if ( (LA33_0==NUMBER||LA33_0==STRING) ) { alt33=2; } else { NoViableAltException nvae = new NoViableAltException("", 33, 0, input); throw nvae; } switch (alt33) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:139:18: '\\$' var= IDENTIFIER { char_literal66=(Token)match(input,46,FOLLOW_46_in_argument1130); char_literal66_tree = (CommonTree)adaptor.create(char_literal66); adaptor.addChild(root_0, char_literal66_tree); var=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_argument1133); var_tree = (CommonTree)adaptor.create(var); adaptor.addChild(root_0, var_tree); currentArgument.setVariable(var.getText()); } break; case 2 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:140:17: constant= ( STRING | NUMBER ) { constant=(Token)input.LT(1); if ( input.LA(1)==NUMBER||input.LA(1)==STRING ) { input.consume(); adaptor.addChild(root_0, (CommonTree)adaptor.create(constant)); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } currentArgument.setValue(constant.getText()); } break; } currentArgumentList.add(currentArgument); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "argument" public static class attribute_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "attribute" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:143:1: attribute : attr= IDENTIFIER ':' value ; public final TGDMappingTaskParser.attribute_return attribute() throws RecognitionException { TGDMappingTaskParser.attribute_return retval = new TGDMappingTaskParser.attribute_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token attr=null; Token char_literal67=null; TGDMappingTaskParser.value_return value68 = null; CommonTree attr_tree=null; CommonTree char_literal67_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:143:10: (attr= IDENTIFIER ':' value ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:143:12: attr= IDENTIFIER ':' value { root_0 = (CommonTree)adaptor.nil(); attr=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_attribute1194); attr_tree = (CommonTree)adaptor.create(attr); adaptor.addChild(root_0, attr_tree); char_literal67=(Token)match(input,47,FOLLOW_47_in_attribute1196); char_literal67_tree = (CommonTree)adaptor.create(char_literal67); adaptor.addChild(root_0, char_literal67_tree); currentAttribute = new ParserAttribute(attr.getText()); pushFollow(FOLLOW_value_in_attribute1200); value68=value(); state._fsp--; adaptor.addChild(root_0, value68.getTree()); currentAtom.addAttribute(currentAttribute); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "attribute" public static class value_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "value" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:146:1: value : ( '\\$' var= IDENTIFIER | nullValue= NULL | constant= ( STRING | NUMBER ) | expression= EXPRESSION ); public final TGDMappingTaskParser.value_return value() throws RecognitionException { TGDMappingTaskParser.value_return retval = new TGDMappingTaskParser.value_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token var=null; Token nullValue=null; Token constant=null; Token expression=null; Token char_literal69=null; CommonTree var_tree=null; CommonTree nullValue_tree=null; CommonTree constant_tree=null; CommonTree expression_tree=null; CommonTree char_literal69_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:146:7: ( '\\$' var= IDENTIFIER | nullValue= NULL | constant= ( STRING | NUMBER ) | expression= EXPRESSION ) int alt34=4; switch ( input.LA(1) ) { case 46: { alt34=1; } break; case NULL: { alt34=2; } break; case NUMBER: case STRING: { alt34=3; } break; case EXPRESSION: { alt34=4; } break; default: NoViableAltException nvae = new NoViableAltException("", 34, 0, input); throw nvae; } switch (alt34) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:146:9: '\\$' var= IDENTIFIER { root_0 = (CommonTree)adaptor.nil(); char_literal69=(Token)match(input,46,FOLLOW_46_in_value1213); char_literal69_tree = (CommonTree)adaptor.create(char_literal69); adaptor.addChild(root_0, char_literal69_tree); var=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_value1216); var_tree = (CommonTree)adaptor.create(var); adaptor.addChild(root_0, var_tree); currentAttribute.setVariable(var.getText()); } break; case 2 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:147:17: nullValue= NULL { root_0 = (CommonTree)adaptor.nil(); nullValue=(Token)match(input,NULL,FOLLOW_NULL_in_value1240); nullValue_tree = (CommonTree)adaptor.create(nullValue); adaptor.addChild(root_0, nullValue_tree); currentAttribute.setValue(nullValue.getText()); } break; case 3 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:148:17: constant= ( STRING | NUMBER ) { root_0 = (CommonTree)adaptor.nil(); constant=(Token)input.LT(1); if ( input.LA(1)==NUMBER||input.LA(1)==STRING ) { input.consume(); adaptor.addChild(root_0, (CommonTree)adaptor.create(constant)); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } currentAttribute.setValue(constant.getText()); } break; case 4 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:149:17: expression= EXPRESSION { root_0 = (CommonTree)adaptor.nil(); expression=(Token)match(input,EXPRESSION,FOLLOW_EXPRESSION_in_value1294); expression_tree = (CommonTree)adaptor.create(expression); adaptor.addChild(root_0, expression_tree); currentAttribute.setValue(new Expression(generator.clean(expression.getText()))); } break; } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "value" public static class fd_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "fd" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:151:1: fd : set= IDENTIFIER ':' path ( ',' path )* '->' path ( ',' path )* ( '[pk]' )? ( '[key]' )? ; public final TGDMappingTaskParser.fd_return fd() throws RecognitionException { TGDMappingTaskParser.fd_return retval = new TGDMappingTaskParser.fd_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token set=null; Token char_literal70=null; Token char_literal72=null; Token string_literal74=null; Token char_literal76=null; Token string_literal78=null; Token string_literal79=null; TGDMappingTaskParser.path_return path71 = null; TGDMappingTaskParser.path_return path73 = null; TGDMappingTaskParser.path_return path75 = null; TGDMappingTaskParser.path_return path77 = null; CommonTree set_tree=null; CommonTree char_literal70_tree=null; CommonTree char_literal72_tree=null; CommonTree string_literal74_tree=null; CommonTree char_literal76_tree=null; CommonTree string_literal78_tree=null; CommonTree string_literal79_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:151:9: (set= IDENTIFIER ':' path ( ',' path )* '->' path ( ',' path )* ( '[pk]' )? ( '[key]' )? ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:151:11: set= IDENTIFIER ':' path ( ',' path )* '->' path ( ',' path )* ( '[pk]' )? ( '[key]' )? { root_0 = (CommonTree)adaptor.nil(); set=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_fd1311); set_tree = (CommonTree)adaptor.create(set); adaptor.addChild(root_0, set_tree); currentFD = new ParserFD(set.getText()); char_literal70=(Token)match(input,47,FOLLOW_47_in_fd1315); char_literal70_tree = (CommonTree)adaptor.create(char_literal70); adaptor.addChild(root_0, char_literal70_tree); currentStringList = new ArrayList<String>(); pushFollow(FOLLOW_path_in_fd1321); path71=path(); state._fsp--; adaptor.addChild(root_0, path71.getTree()); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:152:57: ( ',' path )* loop35: do { int alt35=2; int LA35_0 = input.LA(1); if ( (LA35_0==39) ) { alt35=1; } switch (alt35) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:152:58: ',' path { char_literal72=(Token)match(input,39,FOLLOW_39_in_fd1324); char_literal72_tree = (CommonTree)adaptor.create(char_literal72); adaptor.addChild(root_0, char_literal72_tree); pushFollow(FOLLOW_path_in_fd1326); path73=path(); state._fsp--; adaptor.addChild(root_0, path73.getTree()); } break; default : break loop35; } } while (true); currentFD.setLeftAttributes(currentStringList); string_literal74=(Token)match(input,37,FOLLOW_37_in_fd1332); string_literal74_tree = (CommonTree)adaptor.create(string_literal74); adaptor.addChild(root_0, string_literal74_tree); currentStringList = new ArrayList<String>(); pushFollow(FOLLOW_path_in_fd1338); path75=path(); state._fsp--; adaptor.addChild(root_0, path75.getTree()); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:153:57: ( ',' path )* loop36: do { int alt36=2; int LA36_0 = input.LA(1); if ( (LA36_0==39) ) { alt36=1; } switch (alt36) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:153:58: ',' path { char_literal76=(Token)match(input,39,FOLLOW_39_in_fd1341); char_literal76_tree = (CommonTree)adaptor.create(char_literal76); adaptor.addChild(root_0, char_literal76_tree); pushFollow(FOLLOW_path_in_fd1343); path77=path(); state._fsp--; adaptor.addChild(root_0, path77.getTree()); } break; default : break loop36; } } while (true); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:154:3: ( '[pk]' )? int alt37=2; int LA37_0 = input.LA(1); if ( (LA37_0==48) ) { alt37=1; } switch (alt37) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:154:4: '[pk]' { string_literal78=(Token)match(input,48,FOLLOW_48_in_fd1350); string_literal78_tree = (CommonTree)adaptor.create(string_literal78); adaptor.addChild(root_0, string_literal78_tree); currentFD.setPrimaryKey(true); } break; } // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:155:3: ( '[key]' )? int alt38=2; int LA38_0 = input.LA(1); if ( (LA38_0==49) ) { alt38=1; } switch (alt38) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:155:4: '[key]' { string_literal79=(Token)match(input,49,FOLLOW_49_in_fd1360); string_literal79_tree = (CommonTree)adaptor.create(string_literal79); adaptor.addChild(root_0, string_literal79_tree); currentFD.setKey(true); } break; } currentFD.setRightAttributes(currentStringList); currentFDList.add(currentFD); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "fd" public static class path_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "path" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:158:1: path : name= IDENTIFIER ; public final TGDMappingTaskParser.path_return path() throws RecognitionException { TGDMappingTaskParser.path_return retval = new TGDMappingTaskParser.path_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token name=null; CommonTree name_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:158:9: (name= IDENTIFIER ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:158:11: name= IDENTIFIER { root_0 = (CommonTree)adaptor.nil(); name=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_path1382); name_tree = (CommonTree)adaptor.create(name); adaptor.addChild(root_0, name_tree); currentStringList.add(name.getText()); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "path" public static class fact_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "fact" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:160:1: fact : set= IDENTIFIER '(' attrValue ( ',' attrValue )* ')' ; public final TGDMappingTaskParser.fact_return fact() throws RecognitionException { TGDMappingTaskParser.fact_return retval = new TGDMappingTaskParser.fact_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token set=null; Token char_literal80=null; Token char_literal82=null; Token char_literal84=null; TGDMappingTaskParser.attrValue_return attrValue81 = null; TGDMappingTaskParser.attrValue_return attrValue83 = null; CommonTree set_tree=null; CommonTree char_literal80_tree=null; CommonTree char_literal82_tree=null; CommonTree char_literal84_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:160:9: (set= IDENTIFIER '(' attrValue ( ',' attrValue )* ')' ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:160:11: set= IDENTIFIER '(' attrValue ( ',' attrValue )* ')' { root_0 = (CommonTree)adaptor.nil(); set=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_fact1397); set_tree = (CommonTree)adaptor.create(set); adaptor.addChild(root_0, set_tree); currentFact = new ParserFact(set.getText()); char_literal80=(Token)match(input,41,FOLLOW_41_in_fact1401); char_literal80_tree = (CommonTree)adaptor.create(char_literal80); adaptor.addChild(root_0, char_literal80_tree); pushFollow(FOLLOW_attrValue_in_fact1403); attrValue81=attrValue(); state._fsp--; adaptor.addChild(root_0, attrValue81.getTree()); // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:160:89: ( ',' attrValue )* loop39: do { int alt39=2; int LA39_0 = input.LA(1); if ( (LA39_0==39) ) { alt39=1; } switch (alt39) { case 1 : // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:160:90: ',' attrValue { char_literal82=(Token)match(input,39,FOLLOW_39_in_fact1406); char_literal82_tree = (CommonTree)adaptor.create(char_literal82); adaptor.addChild(root_0, char_literal82_tree); pushFollow(FOLLOW_attrValue_in_fact1408); attrValue83=attrValue(); state._fsp--; adaptor.addChild(root_0, attrValue83.getTree()); } break; default : break loop39; } } while (true); char_literal84=(Token)match(input,43,FOLLOW_43_in_fact1412); char_literal84_tree = (CommonTree)adaptor.create(char_literal84); adaptor.addChild(root_0, char_literal84_tree); currentInstance.addFact(currentFact); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "fact" public static class attrValue_return extends ParserRuleReturnScope { CommonTree tree; public Object getTree() { return tree; } }; // $ANTLR start "attrValue" // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:162:1: attrValue : attr= IDENTIFIER ':' val= ( NULL | STRING | NUMBER ) ; public final TGDMappingTaskParser.attrValue_return attrValue() throws RecognitionException { TGDMappingTaskParser.attrValue_return retval = new TGDMappingTaskParser.attrValue_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token attr=null; Token val=null; Token char_literal85=null; CommonTree attr_tree=null; CommonTree val_tree=null; CommonTree char_literal85_tree=null; try { // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:162:10: (attr= IDENTIFIER ':' val= ( NULL | STRING | NUMBER ) ) // D:\\Dropbox\\dati\\codice\\java\\spicyPlusPlus\\spicyEngine\\src\\it\\unibas\\spicy\\parser\\TGDMappingTask.g:162:12: attr= IDENTIFIER ':' val= ( NULL | STRING | NUMBER ) { root_0 = (CommonTree)adaptor.nil(); attr=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_attrValue1423); attr_tree = (CommonTree)adaptor.create(attr); adaptor.addChild(root_0, attr_tree); char_literal85=(Token)match(input,47,FOLLOW_47_in_attrValue1425); char_literal85_tree = (CommonTree)adaptor.create(char_literal85); adaptor.addChild(root_0, char_literal85_tree); val=(Token)input.LT(1); if ( input.LA(1)==NUMBER||(input.LA(1)>=STRING && input.LA(1)<=NULL) ) { input.consume(); adaptor.addChild(root_0, (CommonTree)adaptor.create(val)); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } currentFact.addAttribute(new ParserAttribute(attr.getText(), val.getText())); } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } // $ANTLR end "attrValue" // Delegated rules public static final BitSet FOLLOW_mappingTask_in_prog54 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_15_in_mappingTask68 = new BitSet(new long[]{0x0000000000010000L}); public static final BitSet FOLLOW_16_in_mappingTask99 = new BitSet(new long[]{0x0000000000000010L}); public static final BitSet FOLLOW_FILEPATH_in_mappingTask103 = new BitSet(new long[]{0x0000000000020000L}); public static final BitSet FOLLOW_17_in_mappingTask116 = new BitSet(new long[]{0x0000000000000010L}); public static final BitSet FOLLOW_FILEPATH_in_mappingTask120 = new BitSet(new long[]{0x0000000000050000L}); public static final BitSet FOLLOW_18_in_mappingTask135 = new BitSet(new long[]{0x0000000000000010L}); public static final BitSet FOLLOW_FILEPATH_in_mappingTask139 = new BitSet(new long[]{0x0000000000080000L}); public static final BitSet FOLLOW_19_in_mappingTask154 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_sttgd_in_mappingTask156 = new BitSet(new long[]{0x0000000001F00042L}); public static final BitSet FOLLOW_20_in_mappingTask169 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_ttgd_in_mappingTask171 = new BitSet(new long[]{0x0000000001E00042L}); public static final BitSet FOLLOW_21_in_mappingTask186 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_fd_in_mappingTask190 = new BitSet(new long[]{0x0000000001C00042L}); public static final BitSet FOLLOW_22_in_mappingTask207 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_fd_in_mappingTask211 = new BitSet(new long[]{0x0000000001800042L}); public static final BitSet FOLLOW_23_in_mappingTask228 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_fact_in_mappingTask232 = new BitSet(new long[]{0x0000000001800042L}); public static final BitSet FOLLOW_24_in_mappingTask249 = new BitSet(new long[]{0x0000001FFE000002L}); public static final BitSet FOLLOW_25_in_mappingTask264 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask268 = new BitSet(new long[]{0x0000001FFC000002L}); public static final BitSet FOLLOW_26_in_mappingTask287 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask291 = new BitSet(new long[]{0x0000001FF8000002L}); public static final BitSet FOLLOW_27_in_mappingTask311 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask315 = new BitSet(new long[]{0x0000001FF0000002L}); public static final BitSet FOLLOW_28_in_mappingTask335 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask339 = new BitSet(new long[]{0x0000001FE0000002L}); public static final BitSet FOLLOW_29_in_mappingTask358 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask362 = new BitSet(new long[]{0x0000001FC0000002L}); public static final BitSet FOLLOW_30_in_mappingTask382 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask386 = new BitSet(new long[]{0x0000001F80000002L}); public static final BitSet FOLLOW_31_in_mappingTask405 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask409 = new BitSet(new long[]{0x0000001F00000002L}); public static final BitSet FOLLOW_32_in_mappingTask428 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask432 = new BitSet(new long[]{0x0000001E00000002L}); public static final BitSet FOLLOW_33_in_mappingTask451 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask455 = new BitSet(new long[]{0x0000001C00000002L}); public static final BitSet FOLLOW_34_in_mappingTask474 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask478 = new BitSet(new long[]{0x0000001800000002L}); public static final BitSet FOLLOW_35_in_mappingTask497 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask501 = new BitSet(new long[]{0x0000001000000002L}); public static final BitSet FOLLOW_36_in_mappingTask520 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_NUMBER_in_mappingTask524 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_view_in_sttgd557 = new BitSet(new long[]{0x0000012000000000L}); public static final BitSet FOLLOW_negatedview_in_sttgd585 = new BitSet(new long[]{0x0000012000000000L}); public static final BitSet FOLLOW_37_in_sttgd594 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_view_in_sttgd598 = new BitSet(new long[]{0x0000004000000000L}); public static final BitSet FOLLOW_38_in_sttgd600 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_atom_in_ttgd617 = new BitSet(new long[]{0x0000002000000000L}); public static final BitSet FOLLOW_37_in_ttgd623 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_atom_in_ttgd625 = new BitSet(new long[]{0x0000004000000000L}); public static final BitSet FOLLOW_38_in_ttgd627 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_atom_in_view647 = new BitSet(new long[]{0x0000008000000002L}); public static final BitSet FOLLOW_39_in_view651 = new BitSet(new long[]{0x0000600000000160L}); public static final BitSet FOLLOW_atom_in_view654 = new BitSet(new long[]{0x0000008000000002L}); public static final BitSet FOLLOW_builtin_in_view658 = new BitSet(new long[]{0x0000008000000002L}); public static final BitSet FOLLOW_40_in_negatedview672 = new BitSet(new long[]{0x0000020000000000L}); public static final BitSet FOLLOW_41_in_negatedview673 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_view_in_negatedview695 = new BitSet(new long[]{0x00000D0000000000L}); public static final BitSet FOLLOW_negatedview_in_negatedview718 = new BitSet(new long[]{0x00000D0000000000L}); public static final BitSet FOLLOW_42_in_negatedview783 = new BitSet(new long[]{0x0000400000000720L}); public static final BitSet FOLLOW_equalities_in_negatedview785 = new BitSet(new long[]{0x0000080000000000L}); public static final BitSet FOLLOW_43_in_negatedview790 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_equality_in_equalities798 = new BitSet(new long[]{0x0000008000000002L}); public static final BitSet FOLLOW_39_in_equalities801 = new BitSet(new long[]{0x0000400000000720L}); public static final BitSet FOLLOW_equality_in_equalities804 = new BitSet(new long[]{0x0000008000000002L}); public static final BitSet FOLLOW_value_in_equality837 = new BitSet(new long[]{0x0000100000000000L}); public static final BitSet FOLLOW_44_in_equality859 = new BitSet(new long[]{0x0000400000000720L}); public static final BitSet FOLLOW_value_in_equality881 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_IDENTIFIER_in_atom912 = new BitSet(new long[]{0x0000020000000000L}); public static final BitSet FOLLOW_41_in_atom916 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_attribute_in_atom918 = new BitSet(new long[]{0x0000088000000000L}); public static final BitSet FOLLOW_39_in_atom921 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_attribute_in_atom923 = new BitSet(new long[]{0x0000088000000000L}); public static final BitSet FOLLOW_43_in_atom927 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_45_in_builtin958 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_IDENTIFIER_in_builtin961 = new BitSet(new long[]{0x0000020000000000L}); public static final BitSet FOLLOW_41_in_builtin963 = new BitSet(new long[]{0x0000600000000160L}); public static final BitSet FOLLOW_argument_in_builtin965 = new BitSet(new long[]{0x0000680000000160L}); public static final BitSet FOLLOW_43_in_builtin968 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_argument_in_builtin1024 = new BitSet(new long[]{0x0000000000000080L}); public static final BitSet FOLLOW_OPERATOR_in_builtin1046 = new BitSet(new long[]{0x0000600000000160L}); public static final BitSet FOLLOW_argument_in_builtin1066 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_46_in_argument1130 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_IDENTIFIER_in_argument1133 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_argument1157 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_IDENTIFIER_in_attribute1194 = new BitSet(new long[]{0x0000800000000000L}); public static final BitSet FOLLOW_47_in_attribute1196 = new BitSet(new long[]{0x0000400000000720L}); public static final BitSet FOLLOW_value_in_attribute1200 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_46_in_value1213 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_IDENTIFIER_in_value1216 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_NULL_in_value1240 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_set_in_value1264 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_EXPRESSION_in_value1294 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_IDENTIFIER_in_fd1311 = new BitSet(new long[]{0x0000800000000000L}); public static final BitSet FOLLOW_47_in_fd1315 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_path_in_fd1321 = new BitSet(new long[]{0x000000A000000000L}); public static final BitSet FOLLOW_39_in_fd1324 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_path_in_fd1326 = new BitSet(new long[]{0x000000A000000000L}); public static final BitSet FOLLOW_37_in_fd1332 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_path_in_fd1338 = new BitSet(new long[]{0x0003008000000002L}); public static final BitSet FOLLOW_39_in_fd1341 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_path_in_fd1343 = new BitSet(new long[]{0x0003008000000002L}); public static final BitSet FOLLOW_48_in_fd1350 = new BitSet(new long[]{0x0002000000000002L}); public static final BitSet FOLLOW_49_in_fd1360 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_IDENTIFIER_in_path1382 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_IDENTIFIER_in_fact1397 = new BitSet(new long[]{0x0000020000000000L}); public static final BitSet FOLLOW_41_in_fact1401 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_attrValue_in_fact1403 = new BitSet(new long[]{0x0000088000000000L}); public static final BitSet FOLLOW_39_in_fact1406 = new BitSet(new long[]{0x0000000000000040L}); public static final BitSet FOLLOW_attrValue_in_fact1408 = new BitSet(new long[]{0x0000088000000000L}); public static final BitSet FOLLOW_43_in_fact1412 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_IDENTIFIER_in_attrValue1423 = new BitSet(new long[]{0x0000800000000000L}); public static final BitSet FOLLOW_47_in_attrValue1425 = new BitSet(new long[]{0x0000000000000320L}); public static final BitSet FOLLOW_set_in_attrValue1429 = new BitSet(new long[]{0x0000000000000002L}); }
dbunibas/spicy
spicyEngine/src/it/unibas/spicy/parser/output/TGDMappingTaskParser.java
Java
gpl-3.0
123,460
/* * irc-message.c - functions for IRC messages * * Copyright (C) 2003-2018 Sébastien Helleu <flashcode@flashtux.org> * * This file is part of WeeChat, the extensible chat client. * * WeeChat 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. * * WeeChat 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 WeeChat. If not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <limits.h> #include <stdio.h> #include <string.h> #include "../weechat-plugin.h" #include "irc.h" #include "irc-channel.h" #include "irc-config.h" #include "irc-server.h" /* * Parses an IRC message and returns: * - tags (string) * - message without tags (string) * - nick (string) * - host (string) * - command (string) * - channel (string) * - arguments (string) * - text (string) * - pos_command (integer: command index in message) * - pos_arguments (integer: arguments index in message) * - pos_channel (integer: channel index in message) * - pos_text (integer: text index in message) * * Example: * @time=2015-06-27T16:40:35.000Z :nick!user@host PRIVMSG #weechat :hello! * * Result: * tags: "time=2015-06-27T16:40:35.000Z" * msg_without_tags: ":nick!user@host PRIVMSG #weechat :hello!" * nick: "nick" * host: "nick!user@host" * command: "PRIVMSG" * channel: "#weechat" * arguments: "#weechat :hello!" * text: "hello!" * pos_command: 47 * pos_arguments: 55 * pos_channel: 55 * pos_text: 65 */ void irc_message_parse (struct t_irc_server *server, const char *message, char **tags, char **message_without_tags, char **nick, char **host, char **command, char **channel, char **arguments, char **text, int *pos_command, int *pos_arguments, int *pos_channel, int *pos_text) { const char *ptr_message, *pos, *pos2, *pos3, *pos4; if (tags) *tags = NULL; if (message_without_tags) *message_without_tags = NULL; if (nick) *nick = NULL; if (host) *host = NULL; if (command) *command = NULL; if (channel) *channel = NULL; if (arguments) *arguments = NULL; if (text) *text = NULL; if (pos_command) *pos_command = -1; if (pos_arguments) *pos_arguments = -1; if (pos_channel) *pos_channel = -1; if (pos_text) *pos_text = -1; if (!message) return; ptr_message = message; /* * we will use this message as example: * * @time=2015-06-27T16:40:35.000Z :nick!user@host PRIVMSG #weechat :hello! */ if (ptr_message[0] == '@') { /* * Read tags: they are optional and enabled only if client enabled * a server capability. * See: https://ircv3.net/specs/core/message-tags-3.2.html */ pos = strchr (ptr_message, ' '); if (pos) { if (tags) { *tags = weechat_strndup (ptr_message + 1, pos - (ptr_message + 1)); } ptr_message = pos + 1; while (ptr_message[0] == ' ') { ptr_message++; } } } if (message_without_tags) *message_without_tags = strdup (ptr_message); /* now we have: ptr_message --> ":nick!user@host PRIVMSG #weechat :hello!" */ if (ptr_message[0] == ':') { /* read host/nick */ pos3 = strchr (ptr_message, '@'); pos2 = strchr (ptr_message, '!'); pos = strchr (ptr_message, ' '); /* if the prefix doesn't contain a '!', split the nick at '@' */ if (!pos2 || (pos && pos2 > pos)) pos2 = pos3; if (pos2 && (!pos || pos > pos2)) { if (nick) *nick = weechat_strndup (ptr_message + 1, pos2 - (ptr_message + 1)); } else if (pos) { if (nick) *nick = weechat_strndup (ptr_message + 1, pos - (ptr_message + 1)); } if (pos) { if (host) *host = weechat_strndup (ptr_message + 1, pos - (ptr_message + 1)); ptr_message = pos + 1; while (ptr_message[0] == ' ') { ptr_message++; } } else { if (host) *host = strdup (ptr_message + 1); ptr_message += strlen (ptr_message); } } /* now we have: ptr_message --> "PRIVMSG #weechat :hello!" */ if (ptr_message[0]) { pos = strchr (ptr_message, ' '); if (pos) { if (command) *command = weechat_strndup (ptr_message, pos - ptr_message); if (pos_command) *pos_command = ptr_message - message; pos++; while (pos[0] == ' ') { pos++; } /* now we have: pos --> "#weechat :hello!" */ if (arguments) *arguments = strdup (pos); if (pos_arguments) *pos_arguments = pos - message; if ((pos[0] == ':') && ((strncmp (ptr_message, "JOIN ", 5) == 0) || (strncmp (ptr_message, "PART ", 5) == 0))) { pos++; } if (pos[0] == ':') { if (text) *text = strdup (pos + 1); if (pos_text) *pos_text = pos - message + 1; } else { if (irc_channel_is_channel (server, pos)) { pos2 = strchr (pos, ' '); if (channel) { if (pos2) *channel = weechat_strndup (pos, pos2 - pos); else *channel = strdup (pos); } if (pos_channel) *pos_channel = pos - message; if (pos2) { while (pos2[0] == ' ') { pos2++; } if (pos2[0] == ':') pos2++; if (text) *text = strdup (pos2); if (pos_text) *pos_text = pos2 - message; } } else { pos2 = strchr (pos, ' '); if (nick && !*nick) { if (pos2) *nick = weechat_strndup (pos, pos2 - pos); else *nick = strdup (pos); } if (pos2) { pos3 = pos2; pos2++; while (pos2[0] == ' ') { pos2++; } if (irc_channel_is_channel (server, pos2)) { pos4 = strchr (pos2, ' '); if (channel) { if (pos4) *channel = weechat_strndup (pos2, pos4 - pos2); else *channel = strdup (pos2); } if (pos_channel) *pos_channel = pos2 - message; if (pos4) { while (pos4[0] == ' ') { pos4++; } if (pos4[0] == ':') pos4++; if (text) *text = strdup (pos4); if (pos_text) *pos_text = pos4 - message; } } else { if (channel) *channel = weechat_strndup (pos, pos3 - pos); if (pos_channel) *pos_channel = pos - message; pos4 = strchr (pos3, ' '); if (pos4) { while (pos4[0] == ' ') { pos4++; } if (pos4[0] == ':') pos4++; if (text) *text = strdup (pos4); if (pos_text) *pos_text = pos4 - message; } } } } } } else { if (command) *command = strdup (ptr_message); if (pos_command) *pos_command = ptr_message - message; } } } /* * Parses an IRC message and returns hashtable with keys: * - tags * - message_without_tags * - nick * - host * - command * - channel * - arguments * - text * - pos_command * - pos_arguments * - pos_channel * - pos_text * * Note: hashtable must be freed after use. */ struct t_hashtable * irc_message_parse_to_hashtable (struct t_irc_server *server, const char *message) { char *tags,*message_without_tags, *nick, *host, *command, *channel; char *arguments, *text, str_pos[32]; char empty_str[1] = { '\0' }; int pos_command, pos_arguments, pos_channel, pos_text; struct t_hashtable *hashtable; irc_message_parse (server, message, &tags, &message_without_tags, &nick, &host, &command, &channel, &arguments, &text, &pos_command, &pos_arguments, &pos_channel, &pos_text); hashtable = weechat_hashtable_new (32, WEECHAT_HASHTABLE_STRING, WEECHAT_HASHTABLE_STRING, NULL, NULL); if (!hashtable) return NULL; weechat_hashtable_set (hashtable, "tags", (tags) ? tags : empty_str); weechat_hashtable_set (hashtable, "message_without_tags", (message_without_tags) ? message_without_tags : empty_str); weechat_hashtable_set (hashtable, "nick", (nick) ? nick : empty_str); weechat_hashtable_set (hashtable, "host", (host) ? host : empty_str); weechat_hashtable_set (hashtable, "command", (command) ? command : empty_str); weechat_hashtable_set (hashtable, "channel", (channel) ? channel : empty_str); weechat_hashtable_set (hashtable, "arguments", (arguments) ? arguments : empty_str); weechat_hashtable_set (hashtable, "text", (text) ? text : empty_str); snprintf (str_pos, sizeof (str_pos), "%d", pos_command); weechat_hashtable_set (hashtable, "pos_command", str_pos); snprintf (str_pos, sizeof (str_pos), "%d", pos_arguments); weechat_hashtable_set (hashtable, "pos_arguments", str_pos); snprintf (str_pos, sizeof (str_pos), "%d", pos_channel); weechat_hashtable_set (hashtable, "pos_channel", str_pos); snprintf (str_pos, sizeof (str_pos), "%d", pos_text); weechat_hashtable_set (hashtable, "pos_text", str_pos); if (tags) free (tags); if (message_without_tags) free (message_without_tags); if (nick) free (nick); if (host) free (host); if (command) free (command); if (channel) free (channel); if (arguments) free (arguments); if (text) free (text); return hashtable; } /* * Encodes/decodes an IRC message using a charset. * * Note: result must be freed after use. */ char * irc_message_convert_charset (const char *message, int pos_start, const char *modifier, const char *modifier_data) { char *text, *msg_result; int length; text = weechat_hook_modifier_exec (modifier, modifier_data, message + pos_start); if (!text) return NULL; length = pos_start + strlen (text) + 1; msg_result = malloc (length); if (msg_result) { msg_result[0] = '\0'; if (pos_start > 0) { memcpy (msg_result, message, pos_start); msg_result[pos_start] = '\0'; } strcat (msg_result, text); } free (text); return msg_result; } /* * Gets nick from host in an IRC message. */ const char * irc_message_get_nick_from_host (const char *host) { static char nick[128]; char host2[128], *pos_space, *pos; const char *ptr_host; if (!host) return NULL; nick[0] = '\0'; if (host) { ptr_host = host; pos_space = strchr (host, ' '); if (pos_space) { if (pos_space - host < (int)sizeof (host2)) { strncpy (host2, host, pos_space - host); host2[pos_space - host] = '\0'; } else snprintf (host2, sizeof (host2), "%s", host); ptr_host = host2; } if (ptr_host[0] == ':') ptr_host++; pos = strchr (ptr_host, '!'); if (pos && (pos - ptr_host < (int)sizeof (nick))) { strncpy (nick, ptr_host, pos - ptr_host); nick[pos - ptr_host] = '\0'; } else { snprintf (nick, sizeof (nick), "%s", ptr_host); } } return nick; } /* * Gets address from host in an IRC message. */ const char * irc_message_get_address_from_host (const char *host) { static char address[256]; char host2[256], *pos_space, *pos; const char *ptr_host; address[0] = '\0'; if (host) { ptr_host = host; pos_space = strchr (host, ' '); if (pos_space) { if (pos_space - host < (int)sizeof (host2)) { strncpy (host2, host, pos_space - host); host2[pos_space - host] = '\0'; } else snprintf (host2, sizeof (host2), "%s", host); ptr_host = host2; } if (ptr_host[0] == ':') ptr_host++; pos = strchr (ptr_host, '!'); if (pos) snprintf (address, sizeof (address), "%s", pos + 1); else snprintf (address, sizeof (address), "%s", ptr_host); } return address; } /* * Replaces special IRC vars ($nick, $channel, $server) in a string. * * Note: result must be freed after use. */ char * irc_message_replace_vars (struct t_irc_server *server, const char *channel_name, const char *string) { const char *var_nick, *var_channel, *var_server; char empty_string[1] = { '\0' }; char *res, *temp; var_nick = (server && server->nick) ? server->nick : empty_string; var_channel = (channel_name) ? channel_name : empty_string; var_server = (server) ? server->name : empty_string; /* replace nick */ temp = weechat_string_replace (string, "$nick", var_nick); if (!temp) return NULL; res = temp; /* replace channel */ temp = weechat_string_replace (res, "$channel", var_channel); free (res); if (!temp) return NULL; res = temp; /* replace server */ temp = weechat_string_replace (res, "$server", var_server); free (res); if (!temp) return NULL; res = temp; /* return result */ return res; } /* * Adds a message + arguments in hashtable. */ void irc_message_split_add (struct t_hashtable *hashtable, int number, const char *tags, const char *message, const char *arguments) { char key[32], value[32], *buf; int length; if (message) { length = ((tags) ? strlen (tags) : 0) + strlen (message) + 1; buf = malloc (length); if (buf) { snprintf (key, sizeof (key), "msg%d", number); snprintf (buf, length, "%s%s", (tags) ? tags : "", message); weechat_hashtable_set (hashtable, key, buf); if (weechat_irc_plugin->debug >= 2) { weechat_printf (NULL, "irc_message_split_add >> %s='%s' (%d bytes)", key, buf, length - 1); } free (buf); } } if (arguments) { snprintf (key, sizeof (key), "args%d", number); weechat_hashtable_set (hashtable, key, arguments); if (weechat_irc_plugin->debug >= 2) { weechat_printf (NULL, "irc_message_split_add >> %s='%s'", key, arguments); } } snprintf (value, sizeof (value), "%d", number); weechat_hashtable_set (hashtable, "count", value); } /* * Splits "arguments" using delimiter and max length. * * Examples of arguments for this function: * * message..: :nick!user@host.com PRIVMSG #channel :Hello world! * arguments: * host : ":nick!user@host.com" * command : "PRIVMSG" * target : "#channel" * prefix : ":" * arguments: "Hello world!" * suffix : "" * * message..: :nick!user@host.com PRIVMSG #channel :\01ACTION is eating\01 * arguments: * host : ":nick!user@host.com" * command : "PRIVMSG" * target : "#channel" * prefix : ":\01ACTION " * arguments: "is eating" * suffix : "\01" * * Messages added to hashtable are: * host + command + target + prefix + XXX + suffix * (where XXX is part of "arguments") * * Returns: * 1: OK * 0: error */ int irc_message_split_string (struct t_hashtable *hashtable, const char *tags, const char *host, const char *command, const char *target, const char *prefix, const char *arguments, const char *suffix, const char delimiter, int max_length_host, int max_length) { const char *pos, *pos_max, *pos_next, *pos_last_delim; char message[8192], *dup_arguments; int number; max_length -= 2; /* by default: 512 - 2 = 510 bytes */ if (max_length_host >= 0) max_length -= max_length_host; else max_length -= (host) ? strlen (host) + 1 : 0; max_length -= strlen (command) + 1; if (target) max_length -= strlen (target); if (prefix) max_length -= strlen (prefix); if (suffix) max_length -= strlen (suffix); if (max_length < 2) return 0; /* debug message */ if (weechat_irc_plugin->debug >= 2) { weechat_printf (NULL, "irc_message_split_string: tags='%s', host='%s', " "command='%s', target='%s', prefix='%s', " "arguments='%s', suffix='%s', max_length=%d", tags, host, command, target, prefix, arguments, suffix, max_length); } number = 1; if (!arguments || !arguments[0]) { snprintf (message, sizeof (message), "%s%s%s %s%s%s%s", (host) ? host : "", (host) ? " " : "", command, (target) ? target : "", (target && target[0]) ? " " : "", (prefix) ? prefix : "", (suffix) ? suffix : ""); irc_message_split_add (hashtable, 1, tags, message, ""); return 1; } while (arguments && arguments[0]) { pos = arguments; pos_max = pos + max_length; pos_last_delim = NULL; while (pos[0]) { if (pos[0] == delimiter) pos_last_delim = pos; pos_next = weechat_utf8_next_char (pos); if (pos_next > pos_max) break; pos = pos_next; } if (pos[0] && pos_last_delim) pos = pos_last_delim; dup_arguments = weechat_strndup (arguments, pos - arguments); if (dup_arguments) { snprintf (message, sizeof (message), "%s%s%s %s%s%s%s%s", (host) ? host : "", (host) ? " " : "", command, (target) ? target : "", (target && target[0]) ? " " : "", (prefix) ? prefix : "", dup_arguments, (suffix) ? suffix : ""); irc_message_split_add (hashtable, number, tags, message, dup_arguments); number++; free (dup_arguments); } arguments = (pos == pos_last_delim) ? pos + 1 : pos; } return 1; } /* * Splits a JOIN message, taking care of keeping channel keys with channel * names. * * Returns: * 1: OK * 0: error */ int irc_message_split_join (struct t_hashtable *hashtable, const char *tags, const char *host, const char *arguments, int max_length) { int number, channels_count, keys_count, length, length_no_channel; int length_to_add, index_channel; char **channels, **keys, *pos, *str; char msg_to_send[16384], keys_to_add[16384]; max_length -= 2; /* by default: 512 - 2 = 510 bytes */ number = 1; channels = NULL; channels_count = 0; keys = NULL; keys_count = 0; pos = strchr (arguments, ' '); if (pos) { str = weechat_strndup (arguments, pos - arguments); if (!str) return 0; channels = weechat_string_split (str, ",", 0, 0, &channels_count); free (str); while (pos[0] == ' ') { pos++; } if (pos[0]) keys = weechat_string_split (pos, ",", 0, 0, &keys_count); } else { channels = weechat_string_split (arguments, ",", 0, 0, &channels_count); } snprintf (msg_to_send, sizeof (msg_to_send), "%s%sJOIN", (host) ? host : "", (host) ? " " : ""); length = strlen (msg_to_send); length_no_channel = length; keys_to_add[0] = '\0'; index_channel = 0; while (index_channel < channels_count) { length_to_add = 1 + strlen (channels[index_channel]); if (index_channel < keys_count) length_to_add += 1 + strlen (keys[index_channel]); if ((length + length_to_add < max_length) || (length == length_no_channel)) { if (length + length_to_add < (int)sizeof (msg_to_send)) { strcat (msg_to_send, (length == length_no_channel) ? " " : ","); strcat (msg_to_send, channels[index_channel]); } if (index_channel < keys_count) { if (strlen (keys_to_add) + 1 + strlen (keys[index_channel]) < (int)sizeof (keys_to_add)) { strcat (keys_to_add, (keys_to_add[0]) ? "," : " "); strcat (keys_to_add, keys[index_channel]); } } length += length_to_add; index_channel++; } else { strcat (msg_to_send, keys_to_add); irc_message_split_add (hashtable, number, tags, msg_to_send, msg_to_send + length_no_channel + 1); number++; snprintf (msg_to_send, sizeof (msg_to_send), "%s%sJOIN", (host) ? host : "", (host) ? " " : ""); length = strlen (msg_to_send); keys_to_add[0] = '\0'; } } if (length > length_no_channel) { strcat (msg_to_send, keys_to_add); irc_message_split_add (hashtable, number, tags, msg_to_send, msg_to_send + length_no_channel + 1); } if (channels) weechat_string_free_split (channels); if (keys) weechat_string_free_split (keys); return 1; } /* * Splits a PRIVMSG or NOTICE message, taking care of keeping the '\01' char * used in CTCP messages. * * Returns: * 1: OK * 0: error */ int irc_message_split_privmsg_notice (struct t_hashtable *hashtable, char *tags, char *host, char *command, char *target, char *arguments, int max_length_host, int max_length) { char prefix[4096], suffix[2], *pos, saved_char; int length, rc; /* * message sent looks like: * PRIVMSG #channel :hello world! * * when IRC server sends message to other people, message looks like: * :nick!user@host.com PRIVMSG #channel :hello world! */ /* for CTCP, prefix will be ":\01xxxx " and suffix "\01" */ prefix[0] = '\0'; suffix[0] = '\0'; length = strlen (arguments); if ((arguments[0] == '\01') && (arguments[length - 1] == '\01')) { pos = strchr (arguments, ' '); if (pos) { pos++; saved_char = pos[0]; pos[0] = '\0'; snprintf (prefix, sizeof (prefix), ":%s", arguments); pos[0] = saved_char; arguments[length - 1] = '\0'; arguments = pos; suffix[0] = '\01'; suffix[1] = '\0'; } } if (!prefix[0]) strcpy (prefix, ":"); rc = irc_message_split_string (hashtable, tags, host, command, target, prefix, arguments, suffix, ' ', max_length_host, max_length); return rc; } /* * Splits a 005 message (isupport). * * Returns: * 1: OK * 0: error */ int irc_message_split_005 (struct t_hashtable *hashtable, char *tags, char *host, char *command, char *target, char *arguments, int max_length) { char *pos, suffix[4096]; /* * 005 message looks like: * :server 005 mynick MODES=4 CHANLIMIT=#:20 NICKLEN=16 USERLEN=10 * HOSTLEN=63 TOPICLEN=450 KICKLEN=450 CHANNELLEN=30 KEYLEN=23 * CHANTYPES=# PREFIX=(ov)@+ CASEMAPPING=ascii CAPAB IRCD=dancer * :are available on this server */ /* search suffix */ suffix[0] = '\0'; pos = strstr (arguments, " :"); if (pos) { snprintf (suffix, sizeof (suffix), "%s", pos); pos[0] = '\0'; } return irc_message_split_string (hashtable, tags, host, command, target, NULL, arguments, suffix, ' ', -1, max_length); } /* * Splits an IRC message about to be sent to IRC server. * * The maximum length of an IRC message is 510 bytes for user data + final * "\r\n", so full size is 512 bytes (the user data does not include the * optional tags before the host). * * The 512 max length is the default (recommended) and can be changed with the * server option called "split_msg_max_length" (0 to disable completely the * split). * * The split takes care about type of message to do a split at best place in * message. * * The hashtable returned contains keys "msg1", "msg2", ..., "msgN" with split * of message (these messages do not include the final "\r\n"). * * Hashtable contains "args1", "args2", ..., "argsN" with split of arguments * only (no host/command here). * * Each message ("msgN") in hashtable has command and arguments, and then is * ready to be sent to IRC server. * * Returns hashtable with split message. * * Note: result must be freed after use. */ struct t_hashtable * irc_message_split (struct t_irc_server *server, const char *message) { struct t_hashtable *hashtable; char **argv, **argv_eol, *tags, *host, *command, *arguments, target[4096]; char *pos, monitor_action[3]; int split_ok, argc, index_args, max_length_nick, max_length_host; int split_msg_max_length; split_ok = 0; tags = NULL; host = NULL; command = NULL; arguments = NULL; argv = NULL; argv_eol = NULL; if (server) { split_msg_max_length = IRC_SERVER_OPTION_INTEGER( server, IRC_SERVER_OPTION_SPLIT_MSG_MAX_LENGTH); /* * split disabled? use a very high max_length so the message should * never be split */ if (split_msg_max_length == 0) split_msg_max_length = INT_MAX - 16; } else { split_msg_max_length = 512; /* max length by default */ } /* debug message */ if (weechat_irc_plugin->debug >= 2) { weechat_printf (NULL, "irc_message_split: message='%s', max length=%d", message, split_msg_max_length); } hashtable = weechat_hashtable_new (32, WEECHAT_HASHTABLE_STRING, WEECHAT_HASHTABLE_STRING, NULL, NULL); if (!hashtable) return NULL; if (!message || !message[0]) goto end; if (message[0] == '@') { pos = strchr (message, ' '); if (pos) { tags = weechat_strndup (message, pos - message + 1); message = pos + 1; } } argv = weechat_string_split (message, " ", 0, 0, &argc); argv_eol = weechat_string_split (message, " ", 2, 0, NULL); if (argc < 2) goto end; if (argv[0][0] == ':') { if (argc < 3) goto end; host = argv[0]; command = argv[1]; arguments = argv_eol[2]; index_args = 2; } else { command = argv[0]; arguments = argv_eol[1]; index_args = 1; } max_length_nick = (server && (server->nick_max_length > 0)) ? server->nick_max_length : 16; max_length_host = 1 + /* ":" */ max_length_nick + /* nick */ 1 + /* "!" */ 63 + /* host */ 1; /* " " */ if ((weechat_strcasecmp (command, "ison") == 0) || (weechat_strcasecmp (command, "wallops") == 0)) { /* * ISON :nick1 nick2 nick3 * WALLOPS :some text here */ split_ok = irc_message_split_string ( hashtable, tags, host, command, NULL, ":", (argv_eol[index_args][0] == ':') ? argv_eol[index_args] + 1 : argv_eol[index_args], NULL, ' ', max_length_host, split_msg_max_length); } else if (weechat_strcasecmp (command, "monitor") == 0) { /* * MONITOR + nick1,nick2,nick3 * MONITOR - nick1,nick2,nick3 */ if (((argv_eol[index_args][0] == '+') || (argv_eol[index_args][0] == '-')) && (argv_eol[index_args][1] == ' ')) { snprintf (monitor_action, sizeof (monitor_action), "%c ", argv_eol[index_args][0]); split_ok = irc_message_split_string ( hashtable, tags, host, command, NULL, monitor_action, argv_eol[index_args] + 2, NULL, ',', max_length_host, split_msg_max_length); } else { split_ok = irc_message_split_string ( hashtable, tags, host, command, NULL, ":", (argv_eol[index_args][0] == ':') ? argv_eol[index_args] + 1 : argv_eol[index_args], NULL, ',', max_length_host, split_msg_max_length); } } else if (weechat_strcasecmp (command, "join") == 0) { /* JOIN #channel1,#channel2,#channel3 key1,key2 */ if ((int)strlen (message) > split_msg_max_length - 2) { /* split join if it's too long */ split_ok = irc_message_split_join (hashtable, tags, host, arguments, split_msg_max_length); } } else if ((weechat_strcasecmp (command, "privmsg") == 0) || (weechat_strcasecmp (command, "notice") == 0)) { /* * PRIVMSG target :some text here * NOTICE target :some text here */ if (index_args + 1 <= argc - 1) { split_ok = irc_message_split_privmsg_notice ( hashtable, tags, host, command, argv[index_args], (argv_eol[index_args + 1][0] == ':') ? argv_eol[index_args + 1] + 1 : argv_eol[index_args + 1], max_length_host, split_msg_max_length); } } else if (weechat_strcasecmp (command, "005") == 0) { /* :server 005 nick MODES=4 CHANLIMIT=#:20 NICKLEN=16 USERLEN=10 ... */ if (index_args + 1 <= argc - 1) { split_ok = irc_message_split_005 ( hashtable, tags, host, command, argv[index_args], (argv_eol[index_args + 1][0] == ':') ? argv_eol[index_args + 1] + 1 : argv_eol[index_args + 1], split_msg_max_length); } } else if (weechat_strcasecmp (command, "353") == 0) { /* * list of users on channel: * :server 353 mynick = #channel :mynick nick1 @nick2 +nick3 */ if (index_args + 2 <= argc - 1) { if (irc_channel_is_channel (server, argv[index_args + 1])) { snprintf (target, sizeof (target), "%s %s", argv[index_args], argv[index_args + 1]); split_ok = irc_message_split_string ( hashtable, tags, host, command, target, ":", (argv_eol[index_args + 2][0] == ':') ? argv_eol[index_args + 2] + 1 : argv_eol[index_args + 2], NULL, ' ', -1, split_msg_max_length); } else { if (index_args + 3 <= argc - 1) { snprintf (target, sizeof (target), "%s %s %s", argv[index_args], argv[index_args + 1], argv[index_args + 2]); split_ok = irc_message_split_string ( hashtable, tags, host, command, target, ":", (argv_eol[index_args + 3][0] == ':') ? argv_eol[index_args + 3] + 1 : argv_eol[index_args + 3], NULL, ' ', -1, split_msg_max_length); } } } } end: if (!split_ok || (weechat_hashtable_get_integer (hashtable, "items_count") == 0)) { irc_message_split_add (hashtable, 1, tags, message, arguments); } if (tags) free (tags); if (argv) weechat_string_free_split (argv); if (argv_eol) weechat_string_free_split (argv_eol); return hashtable; }
maxteufel/weechat
src/plugins/irc/irc-message.c
C
gpl-3.0
36,810
RESOLUTIONS=("100kb" "200kb" "400kb" "800kb" "1000kb") for i in "${RESOLUTIONS[@]}"; do ./script.sh $i; done;
New-College-of-Florida/Jonathan-Niles-Thesis
code/epigenetics/cebpb/run.sh
Shell
gpl-3.0
110
import re import asyncio import threading from collections import defaultdict def connector(bot, dispatcher, NICK, CHANNELS, PASSWORD=None): @bot.on('client_connect') async def connect(**kwargs): bot.send('USER', user=NICK, realname=NICK) if PASSWORD: bot.send('PASS', password=PASSWORD) bot.send('NICK', nick=NICK) # Don't try to join channels until the server has # sent the MOTD, or signaled that there's no MOTD. done, pending = await asyncio.wait( [bot.wait("RPL_ENDOFMOTD"), bot.wait("ERR_NOMOTD")], loop=bot.loop, return_when=asyncio.FIRST_COMPLETED ) # Cancel whichever waiter's event didn't come in. for future in pending: future.cancel() for channel in CHANNELS: bot.send('JOIN', channel=channel) @bot.on('client_disconnect') async def reconnect(**kwargs): # Wait a second so we don't flood await asyncio.sleep(5, loop=bot.loop) # Schedule a connection when the loop's next available bot.loop.create_task(bot.connect()) # Wait until client_connect has triggered await bot.wait("client_connect") @bot.on('ping') def keepalive(message, **kwargs): bot.send('PONG', message=message) @bot.on('privmsg') def message(host, target, message, **kwargs): if host == NICK: # don't process messages from the bot itself return if target == NICK: # private message dispatcher.handle_private_message(host, message) else: # channel message dispatcher.handle_channel_message(host, target, message) class Dispatcher(object): def __init__(self, client): self.client = client self._callbacks = [] self.register_callbacks() def _register_callbacks(self, callbacks): """\ Hook for registering custom callbacks for dispatch patterns """ self._callbacks.extend(callbacks) def register_callbacks(self): """\ Hook for registering callbacks with connection -- handled by __init__() """ self._register_callbacks(( (re.compile(pattern), callback) for pattern, callback in self.command_patterns() )) def _process_command(self, nick, message, channel): results = [] for pattern, callback in self._callbacks: match = pattern.search(message) or pattern.search('/privmsg') if match: results.append( callback(nick, message, channel, **match.groupdict())) return results def handle_private_message(self, nick, message): for result in self._process_command(nick, message, None): if result: self.respond(result, nick=nick) def handle_channel_message(self, nick, channel, message): for result in self._process_command(nick, message, channel): if result: self.respond(result, channel=channel) def command_patterns(self): """\ Hook for defining callbacks, stored as a tuple of 2-tuples: return ( ('/join', self.room_greeter), ('!find (^\s+)', self.handle_find), ) """ raise NotImplementedError def respond(self, message, channel=None, nick=None): """\ Multipurpose method for sending responses to channel or via message to a single user """ if channel: if not channel.startswith('#'): channel = '#%s' % channel self.client.send('PRIVMSG', target=channel, message=message) elif nick: self.client.send('PRIVMSG', target=nick, message=message) class Locker(object): def __init__(self, delay=None, user=""): self.delay = delay if delay or delay == 0 and type(delay) == int else 5 self.locked = False def lock(self): if not self.locked: if self.delay > 0: self.locked = True t = threading.Timer(self.delay, self.unlock, ()) t.daemon = True t.start() return self.locked def unlock(self): self.locked = False return self.locked def cooldown(delay): def decorator(func): if not hasattr(func, "__cooldowns"): func.__cooldowns = defaultdict(lambda: Locker(delay)) def inner(*args, **kwargs): nick = args[1] user_cd = func.__cooldowns[nick] if user_cd.locked: return ret = func(*args, **kwargs) user_cd.lock() return ret return inner return decorator
AiAeGames/DaniBot
dispatcher.py
Python
gpl-3.0
4,840
#define F_CPU 8000000UL #include <avr/io.h> #include <avr/interrupt.h> #include <inttypes.h> #include <util/delay.h> #include <stdlib.h> // 1WIRE CONFIG #define DQ 2 // pin DQ termometru DS1822-PAR #define THERM_DDRx DDRD #define THERM_PINx PIND #define STRONG_PULL_UP_DDR DDRC #define STRONG_PULL_UP_PORT PORTC #define STRONG_PULL_UP_PIN 1 #define SET_DQ THERM_DDRx &= ~(1 << DQ) // linia DQ w stan wysoki #define CLR_DQ THERM_DDRx |= (1 << DQ) // linia DQ w stan niski #define IN_DQ THERM_PINx & (1 << DQ) // sprawdzenie stanu linii DQ (odczyt) #define STRONG_PULL_UP_ON STRONG_PULL_UP_PORT |= (1 << STRONG_PULL_UP_PIN) #define STRONG_PULL_UP_OFF STRONG_PULL_UP_PORT &= ~(1 << STRONG_PULL_UP_PIN) double temperature=0.0; void OneWireReset(void) { CLR_DQ; // stan niski na linii 1wire _delay_us(480); // opoznienie ok 480us SET_DQ;// stan wysoki na linii 1wire _delay_us(480); // opoznienie ok 480 us } void OneWireWriteBit(uint8_t bit) { CLR_DQ; // stan niski na linii 1wire _delay_us(10); // opoznienie 10us if(bit) { SET_DQ; // jezeli parametr jest niezerowy to ustaw stan wysoki na linii } _delay_us(100); // opoznienie 100us SET_DQ; // stan wysoki na linii 1wire } uint8_t OneWireReadBit(void) { CLR_DQ; // stan niski na linii 1Wire _delay_us(3); // opoznienie 3us SET_DQ; // stan wysoki na linii 1Wire _delay_us(15); // opoznienie 15us if(IN_DQ) { return 1; } else { return 0; // testowanie linii, funkcja zwraca stan } } uint8_t OneWireReadByte(void) { uint8_t i; // iterator petli uint8_t value = 0; // odczytany bajt for (i=0;i<8;i++) { // odczyt 8 bitów z magistrali DQ if(OneWireReadBit()) { value|=0x01<<i; } _delay_us(9); // opoznienie 9us } return(value); } void OneWireWriteByte(uint8_t val) { uint8_t i; // iterator petli uint8_t temp; for (i=0; i<8; i++) { // wyslanie 8 bitów na magistrale 1-Wire temp = val >> i; temp &= 0x01; OneWireWriteBit(temp); } _delay_us(9); } void ReadTemperature() { uint8_t i; uint8_t scratchpad[9]; /* stratchpad[]: 0 - lsb 1 - msb 2 - T_{h} register 3 - T_{l} register 4 - configuartion register 5 - reserved 6 - reserved 7 - reserved 8 - crc */ STRONG_PULL_UP_OFF; OneWireReset(); // reset 1-Wire OneWireWriteByte(0xCC); // komenda skip ROM OneWireWriteByte(0x44); // komenda convertT STRONG_PULL_UP_ON; _delay_ms(750); // delay 750ms STRONG_PULL_UP_OFF; OneWireReset(); // reset 1Wire OneWireWriteByte(0xCC); // komenda skip ROM OneWireWriteByte(0xBE); // komenda read Scratchpad for(i=0; i<9; i++) { scratchpad[i] = OneWireReadByte(); } uint16_t buffer = scratchpad[0]; buffer |= (scratchpad[1] << 8); temperature = (double)(buffer / 16.0); } volatile uint8_t command; int main(void) { uint8_t maxFanSpeed = 255; uint8_t minFanSpeed = 80; uint8_t fanSpeed = minFanSpeed; double minTemperature = 23.5; double maxTemperature = 24.6875; // Fast PWM mode TCCR0 |= (1 << WGM01) | (1 << WGM00); // OC0 enabled, clear on match TCCR0 |= (1 << COM01) | (1 << COM00); // timer0 clock source prescaler TCCR0 |= (1 << CS00); // pin OC0 as output DDRB |= (1 << PB0); STRONG_PULL_UP_DDR |= (1 << STRONG_PULL_UP_PIN); // initialize interrupts sei(); while(1) { PORTC &= ~(1 << 1); ReadTemperature(); if (temperature < minTemperature && fanSpeed > minFanSpeed) { fanSpeed -= 1; } else if (temperature > maxTemperature && fanSpeed < maxFanSpeed - 20) { fanSpeed += 1; } OCR0 = 255 - fanSpeed; _delay_ms(500); } return 0; }
slawciu/rzeczybezinternetu
FunWithFan/main.c
C
gpl-3.0
4,071
#ifndef __TRIP__INTRO_SORT__HPP__ #define __TRIP__INTRO_SORT__HPP__ #include <boost/threadpool.hpp> #include <stdlib.h> #include <vector> #include <algorithm> namespace trip { namespace detail { inline int bsr(int _value) { int result; #if defined __i386 && defined __GNUC__ __asm__("bsrl %1, %0 \n\t" : "=r"(result) : "r"(_value)); #else result = 0; for (; _value != 1; _value >>= 1) ++result; #endif return result; } template<typename T> inline T median(const T& begin, const T& center, const T& end) { if (center < begin && center < end) return begin < end ? begin : end; if (begin < center && end < center) return begin < end ? end : begin; return center; } template<typename Iterator> inline void insertion_sort(Iterator begin_, Iterator end_) { typedef typename std::iterator_traits<Iterator>::value_type value_t; // if only two members, just swap if (end_ - begin_ == 2) { if (*(end_ - 1) < *begin_) std::iter_swap(begin_, end_ - 1); return; } for (Iterator i = begin_ + 1; i != end_; ++i) { Iterator j = i; value_t v = *i; while (j != begin_ && v < *(j - 1)) { *j = *(j - 1); --j; } *j = v; } } template<typename Iterator> void do_intro_sort(Iterator begin_, Iterator end_, std::size_t depth_, boost::threadpool::pool& _threadpool) { typedef typename std::iterator_traits<Iterator>::value_type value_t; enum thresholds { // limit for insertion sort INSERTION_THRESHOLD = 16, // minimum members to assign a new thread THREAD_THRESHOLD = 4096 }; while (end_ - begin_ > 1) { // if only few members are left use insertion sort if (end_ - begin_ < INSERTION_THRESHOLD) { insertion_sort(begin_, end_); return; } // if recursion limit reached use heap sort if (depth_-- == 0) { std::make_heap(begin_, end_); std::sort_heap(begin_, end_); return; } // calculate the pivot value_t p = median(*begin_, *(begin_ + (end_ - begin_) / 2), *(end_ - 1)); Iterator i = begin_, j = end_; // quicksort partitioning while (true) { while (*i < p) ++i; --j; while (p < *j) --j; if (!(i < j)) break; std::iter_swap(i, j); ++i; } int r = end_ - i; if (r > 1) { if (r < THREAD_THRESHOLD) { do_intro_sort(i, end_, depth_, _threadpool); } else { _threadpool.schedule(boost::bind(&do_intro_sort<Iterator>, i, end_, depth_, boost::ref(_threadpool))); } } end_ = i; } } } // namespace detail template<class Iterator> void intro_sort(Iterator first, Iterator last) { int number_of_threads = boost::thread::hardware_concurrency(); if (number_of_threads < 1) number_of_threads = 1; boost::threadpool::pool threadpool(number_of_threads); std::size_t depth = 2 * trip::detail::bsr(last - first); if (last - first > 1) { detail::do_intro_sort(first, last, depth, threadpool); threadpool.wait(); } } } // namespace trip #endif
purpleKarrot/JunkLoad
tools/sort/intro_sort.hpp
C++
gpl-3.0
2,925
using System; using System.Collections.Generic; using System.Linq; using Epam.JDI.Commons; using Epam.JDI.Core.Attributes; using Epam.JDI.Core.Interfaces.Base; using Epam.JDI.Core.Interfaces.Common; using Epam.JDI.Core.Interfaces.Complex; using Epam.JDI.Web.Selenium.Attributes; using Epam.JDI.Web.Selenium.Elements.Base; using Epam.JDI.Web.Selenium.Elements.Common; using Epam.JDI.Web.Utils; using static Epam.JDI.Core.Settings.JDISettings; namespace Epam.JDI.Web.Selenium.Elements.Composite { public class Form<T> : WebElement, IForm<T> { protected Action<Form<T>, string, ISetValue> SetFieldValueAction = (f, text, element) => element.Value = text; protected Func<Form<T>, IHasValue, string> GetFieldValueAction = (f, element) => element.Value; public void Fill(T entity) { Fill(entity.ToSetValue()); } public void Fill(Dictionary<string, string> map) { this.GetFields(typeof(ISetValue)).ForEach(element => { var fieldValue = map.FirstOrDefault(pair => GetElementClass.NamesEqual(pair.Key.ToLower().Trim('_'), NameAttribute.GetElementName(element).ToLower().Trim('_'))).Value; if (fieldValue == null) return; var setValueElement = (ISetValue) element.GetValue(this); DoActionRule(fieldValue, val => SetFieldValueAction(this, val, setValueElement)); }); } public IList<string> Verify(T entity) { return Verify(entity.ToSetValue()); } private Button GetSubmitButton() { var fields = this.GetFields(typeof(IButton)); switch (fields.Count) { case 0: throw Exception($"Can't find any buttons on form '{ToString()}."); case 1: return (Button) fields[0].GetValue(this); default: throw Exception($"Form '{ToString()}' have more than 1 button. Use submit(entity, buttonName) for this case instead"); } } public void Submit(Dictionary<string, string> objStrings) { Fill(objStrings); GetElementClass.GetButton("Submit").Click(); } private void SetText(string text) { var field = this.GetFields(typeof(ISetValue))[0]; var setValueElement = (ISetValue) field.GetValue(this); DoActionRule(text, val => SetFieldValueAction(this, val, setValueElement)); } public void Submit(string text) { SetText(text); GetElementClass.GetButton("Submit").Click(); } public void Search(T entity) { Submit(entity, "Search"); } public void Submit(T entity, string buttonName) { Fill(entity.ToSetValue()); GetElementClass.GetButton(buttonName).Click(); } public void Submit(string text, string buttonName) { SetText(text); GetElementClass.GetButton(buttonName).Click(); } public void Login(string text) { Submit(text, "Login"); } public void Add(string text) { Submit(text, "Add"); } public void Publish(string text) { Submit(text, "Publish"); } public void Save(string text) { Submit(text, "Save"); } public void Update(string text) { Submit(text, "Update"); } public void Cancel(string text) { Submit(text, "Cancel"); } public void Close(string text) { Submit(text, "Close"); } public void Back(string text) { Submit(text, "Back"); } public void Select(string text) { Submit(text, "Select"); } public void Next(string text) { Submit(text, "Next"); } public void Search(string text) { Submit(text, "Search"); } public void Submit(T entity) { Submit(entity, "Submit"); } public void Login(T entity) { Submit(entity, "Login"); } public void Add(T entity) { Submit(entity, "Add"); } public void Publish(T entity) { Submit(entity, "Publish"); } public void Save(T entity) { Submit(entity, "Save"); } public void Update(T entity) { Submit(entity, "Update"); } public void Cancel(T entity) { Submit(entity, "Cancel"); } public void Close(T entity) { Submit(entity, "Close"); } public void Back(T entity) { Submit(entity, "Back"); } public void Select(T entity) { Submit(entity, "Select"); } public void Next(T entity) { Submit(entity, "Next"); } public void Submit(T entity, Enum buttonName) { Fill(entity.ToSetValue()); GetElementClass.GetButton(buttonName.ToString().ToLower()).Click(); } public IList<string> Verify(Dictionary<string, string> objStrings) { var compareFalse = new List<string>(); this.GetFields(typeof(IHasValue)).ForEach( field => { var fieldValue = objStrings.FirstOrDefault(pair => GetElementClass.NamesEqual(pair.Key, NameAttribute.GetElementName(field))).Value; if (fieldValue == null) return; var valueField = (IHasValue) field.GetValue(this); DoActionRule(fieldValue, expected => { var actual = GetFieldValueAction(this, valueField).Trim(); if (actual.Equals(expected)) return; compareFalse.Add($"Field '{field.Name}' (Actual: '{actual}' <> Expected: '{expected}')"); }); }); return compareFalse; } public void Check(T entity) { Check(entity.ToSetValue()); } public void Check(Dictionary<string, string> objStrings) { var result = Verify(objStrings); if (result.Count > 0) throw Exception("Check form failed:" +result.Print("".FromNewLine()).FromNewLine()); } protected Func<Form<T>, string> GetValueAction => f => this.GetFields(typeof (IHasValue)).Select(field => ((IHasValue) field.GetValue(this)).Value).Print(); protected Action<Form<T>, string> SetValueAction => (f, value) => Submit(value.ParseAsString()); public string Value { get { return Actions.GetValue(f => GetValueAction(this)); } set { Actions.SetValue(value, (f, val) => SetValueAction(this, value));} } } }
alexeykuptsov/JDI
C#.Net/JDI/Web/Selenium/Elements/Composite/Form.cs
C#
gpl-3.0
7,241
/* * This file is part of Cleanflight. * * Cleanflight 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. * * Cleanflight 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 Cleanflight. If not, see <http://www.gnu.org/licenses/>. */ // // CMS things for blackbox and flashfs. // #include <stdbool.h> #include <stdint.h> #include <string.h> #include <ctype.h> #include "platform.h" #include "build/version.h" #ifdef CMS #include "drivers/system.h" #include "cms/cms.h" #include "cms/cms_types.h" #include "cms/cms_menu_blackbox.h" #include "config/config_profile.h" #include "config/config_master.h" #include "config/feature.h" #include "io/flashfs.h" #ifdef USE_FLASHFS static long cmsx_EraseFlash(displayPort_t *pDisplay, const void *ptr) { UNUSED(ptr); displayClearScreen(pDisplay); displayWrite(pDisplay, 5, 3, "ERASING FLASH..."); displayResync(pDisplay); // Was max7456RefreshAll(); Why at this timing? flashfsEraseCompletely(); while (!flashfsIsReady()) { delay(100); } displayClearScreen(pDisplay); displayResync(pDisplay); // Was max7456RefreshAll(); wedges during heavy SPI? return 0; } #endif // USE_FLASHFS static bool featureRead = false; static uint8_t cmsx_FeatureBlackbox; static long cmsx_Blackbox_FeatureRead(void) { if (!featureRead) { cmsx_FeatureBlackbox = feature(FEATURE_BLACKBOX) ? 1 : 0; featureRead = true; } return 0; } static long cmsx_Blackbox_FeatureWriteback(void) { if (cmsx_FeatureBlackbox) featureSet(FEATURE_BLACKBOX); else featureClear(FEATURE_BLACKBOX); return 0; } static OSD_Entry cmsx_menuBlackboxEntries[] = { { "-- BLACKBOX --", OME_Label, NULL, NULL, 0}, { "ENABLED", OME_Bool, NULL, &cmsx_FeatureBlackbox, 0 }, { "RATE DENOM", OME_UINT8, NULL, &(OSD_UINT8_t){ &blackboxConfig()->rate_denom,1,32,1 }, 0 }, #ifdef USE_FLASHFS { "ERASE FLASH", OME_Funcall, cmsx_EraseFlash, NULL, 0 }, #endif // USE_FLASHFS { "BACK", OME_Back, NULL, NULL, 0 }, { NULL, OME_END, NULL, NULL, 0 } }; CMS_Menu cmsx_menuBlackbox = { .GUARD_text = "MENUBB", .GUARD_type = OME_MENU, .onEnter = cmsx_Blackbox_FeatureRead, .onExit = NULL, .onGlobalExit = cmsx_Blackbox_FeatureWriteback, .entries = cmsx_menuBlackboxEntries }; #endif
midelic/betaflight
src/main/cms/cms_menu_blackbox.c
C
gpl-3.0
2,902
default: go build -o finddupe install: go build -o ${GOPATH}/bin/finddupe github.com/antonyho/go-dupefinder build-deps: dep init update-deps: dep ensure -update test: go test
antonyho/go-dupefinder
Makefile
Makefile
gpl-3.0
185
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'embedbase', 'hr', { pathName: 'objekt medija', title: 'Media Embed', button: 'Umetanje Media Embed', unsupportedUrlGiven: 'Navedeni URL nije podržan', unsupportedUrl: 'URL {url} nije podržan od strane Media Embed-a.', fetchingFailedGiven: 'Nije moguće dohvatiti sadržaj danog URL-a.', fetchingFailed: 'Nije moguće dohvatiti sadržaj za {url}.', fetchingOne: 'Dohvaćanje oEmbed odgovora...', fetchingMany: 'Dohvaćanje oEmbed odgovora, {current} od {max} gotovo...' } );
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/plugins/embedbase/lang/hr.js
JavaScript
gpl-3.0
676
% This is part of Le Frido % Copyright (c) 2006-2022 % Laurent Claessens, Carlotta Donadello % See the file fdl-1.3.txt for copying conditions. %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \section{Règles de calcul} %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ D'abord une dérivée facile, qui sera utile pour démontrer la formule de dérivation d'un quotient. \begin{lemma} Nous avons : \begin{equation} \left( \frac{1}{ x } \right)'=-\frac{1}{ x^2 }. \end{equation} \end{lemma} \begin{proof} En posant \( f(x)=1/x\), nous avons le calcul \begin{equation} \frac{ f(x+\epsilon)-f(x) }{ \epsilon }=\frac{ \frac{1}{ x+\epsilon }-\frac{1}{ x } }{ \epsilon }=\frac{ x-(x+\epsilon) }{ \epsilon x(x+\epsilon) }=\frac{ -1 }{ x(x+\epsilon) }. \end{equation} Nous trouvons le résultat en passant à la limite et en tenant compte de la proposition \ref{PROPooOUPNooTrClHw} sur la limite d'un quotient. \end{proof} \begin{proposition}[\cite{ooRCDWooONrayj,ooVNAOooAuQSse,ooOGGJooCGQgDO}] \label{PROPooOUZOooEcYKxn} Nous avons les règles suivantes. \begin{enumerate} \item \label{ITEMooTFNPooYngHnD} Si \( f,g\colon \eR\to \eR\) sont dérivables en \( a\in \eR\), alors \( f+g\) est dérivable en \( a\) et \begin{equation} (f+g)'(a)=f'(a)+g'(a). \end{equation} \item \label{ITEMooIPLRooOZXqMg} Si \( f\colon \eR\to \eR\) est dérivable en \( a\in \eR\) et si \( \lambda\in \eR\), alors \( (\lambda f)\) est dérivable en \( a\) et \begin{equation} (\lambda f)'(a)=\lambda f'(a). \end{equation} \item \label{ITEMooMQERooBCqnvS} Si \( f,g\colon \eR\to \eR\) sont dérivables en \( a\in \eR\), alors \( fg\) est dérivable en \( a\) et \begin{equation} (fg)'(a)=f'(a)g(a)+f(a)g'(a). \end{equation} Cette formule est appelée \defe{règle de Leibnitz}{Leibnitz}. \item \label{ITEMooLYZCooVUPTyh} Soient deux intervalles \( I,J\) dans \( \eR\). Soient des fonctions \( f\colon I\to J\) et \( g\colon J\to \eR\). Soit encore \( a\in I\). SI \( f\) est dérivable en \( a\) et si \( g\) est dérivable en \( f(a)\), alors \( g\circ f\) est dérivable en \( a\) et \begin{equation} (g\circ f)'(a)= g'\big( f(a) \big)f'(a). \end{equation} \item \label{ITEMooMUNQooLiKffz} Soient \( f,g\colon I\to \eR\) des fonction sur un intervalle ouvert \( I\). Soit \( a\in I\); supposons que \( g(a)\neq 0\). Alors la fonction \( \frac{ f }{ g }\) est dérivable en \( a\) et \begin{equation} \left( \frac{ f }{ g } \right)'(a)=\frac{ f'(a)g(a)-f(a)g'(a) }{ g(a)^2 }. \end{equation} \end{enumerate} En particulier, la dérivation est une opération linéaire sur l'espace des fonctions infiniement dérivables. \end{proposition} \begin{proof} Point par point. \begin{subproof} \item[Pour \ref{ITEMooTFNPooYngHnD}] \item[Pour \ref{ITEMooIPLRooOZXqMg}] Écrivons la définition de la dérivée avec $(\lambda f)$ au lieu de $f$, et calculons un petit peu : \begin{subequations} \begin{align} (\lambda f)'(x) & =\lim_{\epsilon\to 0}\frac{ (\lambda f)(x+\epsilon)-(\lambda f)(x) }{ \epsilon } \\ & =\lim_{\epsilon\to 0}\frac{ \lambda \big( f(x+\epsilon) \big)-\lambda f(x) }{ \epsilon } \\ & =\lim_{\epsilon\to 0}\lambda \frac{ f(x+\epsilon) -f(x) }{ \epsilon } \\ & =\lambda \lim_{\epsilon\to 0}\frac{ f(x+\epsilon) -f(x) }{ \epsilon } \\ & =\lambda f'(x). \end{align} \end{subequations} \item[Pour \ref{ITEMooMQERooBCqnvS}, règle de Leibnitz] La définition de la dérivée dit que \begin{equation} \label{Eqfgrimeepsfgx} (fg)'(x)=\lim_{\epsilon\to 0}\frac{f(x+\epsilon)g(x+\epsilon)-f(x)g(x)}{\epsilon}. \end{equation} La subtilité est d'ajouter au numérateur la quantité $-f(x)g(x+\epsilon)+f(x)g(x+\epsilon)$, ce qui est permis parce que cette quantité est nulle\footnote{Nous avons déjà faut le coup d'ajouter et enlever la même chose durant la démonstration du théorème~\ref{Tholimfgabab}. C'est une technique assez courante en analyse.}. Le numérateur de \eqref{Eqfgrimeepsfgx} devient donc \begin{equation} \begin{aligned}[] f(x+\epsilon)g(x+\epsilon) & -f(x)g(x+\epsilon)+f(x)g(x+\epsilon)-f(x)g(x) \\ & = g(x+\epsilon)\big( f(x+\epsilon)-f(x) \big)+f(x)\big( g(x+\epsilon)-g(x) \big), \end{aligned} \end{equation} où nous avons effectué deux mises en évidence. Étant donné que nous avons deux termes, nous pouvons couper la limite en deux : \begin{equation} \begin{aligned}[] (fg)'(x) & =\lim_{\epsilon\to 0}g(x+\epsilon)\frac{ f(x+\epsilon)-f(x) }{\epsilon} & +\lim_{\epsilon\to 0}f(x)\frac{ g(x+\epsilon)-g(x) }{\epsilon} \\ & =\lim_{\epsilon\to 0}g(x+\epsilon)\lim_{\epsilon\to 0}\frac{ f(x+\epsilon)-f(x) }{\epsilon} & +f(x)\lim_{\epsilon\to 0}\frac{ g(x+\epsilon)-g(x) }{\epsilon}, \end{aligned} \end{equation} où nous avons utilisé le théorème~\ref{Tholimfgabab} pour scinder la première limite en deux, ainsi que la propriété \eqref{Eqbutmultlim} pour sortir le $f(x)$ de la limite dans le second terme. Maintenant, dans le premier terme, nous avons évidemment\footnote{Pas tout à fait évidemment : selon le théorème~\ref{ThoLimCont}, \emph{limite et continuité}, il faut que $g$ soit continue.} $\lim_{\epsilon\to 0}g(x+\epsilon)=g(x)$. Les limites qui restent sont les définitions classiques des dérivées de $f$ et $g$ au point~$x$ : \begin{equation} (fg)'(x)=g(x)f'(x)-f(x)g'(x), \end{equation} ce qu'il fallait démontrer. \item[Pour \ref{ITEMooLYZCooVUPTyh}] Nous posons \( b=f(a)\) et nous considérons la fonction suivante : \begin{equation} \begin{aligned} u\colon J & \to \eR \\ y & \mapsto u(y)=\begin{cases} \frac{ g(y)-g(b) }{ y-b } & \text{si } y\neq b \\ g'(b) & \text{si } y=b. \end{cases} \end{aligned} \end{equation} Vu que \( g\) est dérivable en \( b\), la seconde ligne existe et \( u\) est continue en \( y=b=f(a)\). C'est la définition de la dérivée. Mais \( f\) est continue en \( a\), donc \( u\circ f\) est également continue en \( a\), et nous avons \begin{equation} \lim_{x\to a} (u\circ f)(x)=u\big( f(a) \big)=u(b)=g'(b). \end{equation} En récrivant la définition de \( u\) en \( f(x)\), l'expression suivante est une fonction continue de \( x\) : \begin{equation} u\big( f(x) \big)=\begin{cases} \frac{ g\big( f(x) \big)-g(b) }{ f(x)-b } & \text{si } f(x)\neq b \\ g'(b) & \text{si } y=b. \end{cases} \end{equation} Si \( f(x)\neq b\) nous avons : \begin{equation} \label{EQooKHQZooJdbmlT} g\big( f(x) \big)-g(b)=u\big( f(x) \big)\big( f(x)-b \big). \end{equation} Si par contre \( f(x)=b\), en réalité, l'égalité \eqref{EQooKHQZooJdbmlT} est encore valable parce qu'elle se résume à \( 0=0\). Nous divisons par \( x-a\) et nous avons l'égalité \begin{equation} \frac{ g\big( f(x) \big)-f\big( f(a) \big) }{ x-a }=u\big( f(x) \big)\frac{ f(x)-f(a) }{ x-a } \end{equation} qui est valable sur \( I\setminus\{ a \}\). Il ne s'agit pas maintenant de prendre la limite \( x\to a\) des deux côtés, parce que la limite du membre de gauche est précisément ce que ce théorème s'efforce de prouver exister. Nous montrons que la limite du membre de gauche existe en montrant que celle de droite existe. D'une part, \( u\circ f\) est continue et \begin{equation} \lim_{x\to a} u\big( f(x) \big)=u\big( f(a) \big)=u(b)=g'(b). \end{equation} D'autre par, \( f\) est dérivable en \( a\), donc \begin{equation} \lim_{x\to a} \frac{ f(x)-f(a) }{ x-a }=f'(a). \end{equation} Tout cela pour dire qu'à droite, la limite existe et vaut \( g'(b)f'(a)\). Donc nous avons l'existence de la limite que nous définissant \( (g\circ f)'(a)\), et la valeur \begin{equation} \lim_{x\to a} \frac{ g\big( f(x) \big)-f\big( f(a) \big) }{ x-a }= g'\big( f(a) \big)f'(a). \end{equation} Le résultat est prouvé. \item[Pour \ref{ITEMooMUNQooLiKffz}] Nous considérons la fonction \begin{equation} \begin{aligned} i\colon \eR\setminus\{ 0 \} & \to \eR \\ x & \mapsto \frac{1}{ x }. \end{aligned} \end{equation} La fonction \( g\) est dérivable en \( a\), la fonction \( i\) est dérivable en \( g(a)\). Donc par le théorème de dérivation des fonctions composées\footnote{Proposition \ref{PROPooOUZOooEcYKxn}\ref{ITEMooLYZCooVUPTyh}.}, la fonction \( i\circ f\) est dérivable en \( a\) et \begin{equation} (i\circ g)'(a)=i'\big( g(a) \big)g'(a)=-\frac{ g'(a) }{ g(a)^2 }. \end{equation} Pour le quotient, nous utilisons la formule de la dérivée du produit sur \( \frac{ f }{ g }(x)=f(x)\frac{1}{ g(x) } \) pour dire que \( f/g\) est dérivable en \( a\) et \begin{equation} \left( \frac{ f }{ g } \right)'(a)=f'(a)\frac{1}{ g(a) }+f(a)\left( \frac{1}{ g } \right)'(a) =\frac{ f'(a) }{ g(a) }-\frac{ f(a)g'(a) }{ g(a)^2 } =\frac{ f'(a)g(a)-f(a)g'(a) }{ g(a)^2 }, \end{equation} ce qu'il fallait démontrer. \end{subproof} \end{proof} \begin{remark} Nous ne pouvons pas dire que la dérivée est une opération linéaire sur l'espace des fonctions dérivables. Certes la proposition \ref{PROPooOUZOooEcYKxn} implique entre autres que l'ensemble des fonctions dérivables est un espace vectoriel. Mais la dérivée d'une fonction dérivable n'est pas spécialement dérivable. \end{remark} \begin{remark} La formule \( (1/u)'=-u'/u^2\) ne peut pas être vue comme un cas particulier de \( (u^{\alpha})'=\alpha u^{\alpha-1}\) (proposition \ref{PROPooSGLGooIgzque}) parce que cette formule est utilisée dans la démonstration de la formule générale. \end{remark} Pour les fonctions à valeurs dant \( \eR^n\), nous posons la définition suivante. \begin{definition} Soit une fonction \( f\colon \eR\to \eR^n\) dont les composantes \( f_i\colon \eR\to \eR\) sont dérivables. Nous définissons la fonction \( f'\) par \begin{equation} f'(x)=\sum_if'_i(x)e_i, \end{equation} c'est-à-dire une dérivation composante par composante. \end{definition} Cette définition est celle pour une fonction \( \eR\to \eR^n\), et elles est facile. Très différente est la situation d'une fonction \( \eR^n\to \eR\) dans laquelle il faudra introduire la notion de différentielle\footnote{Ce sera pour la définition \ref{DefDifferentiellePta}.}. \begin{lemma} \label{LEMooXHVBooHYjXdq} Soit une fonction dérivable \( f\colon \eR\to \eR^n\). Nous posons \begin{equation} \begin{aligned} g\colon \eR & \to \eR \\ t & \mapsto f(a+\lambda t) \end{aligned} \end{equation} où \( a\in \eR\). Alors \( g\) est dérivable et \( g'(0)=\lambda f'(0)\). \end{lemma} \begin{proof} Nous devons prouver que la limite \begin{equation} \lim_{\epsilon\to 0}\frac{ g(\epsilon)-g(0) }{ \epsilon } \end{equation} existe et vaut \( \lambda f'(0)\). Nous y allons avec les accroissements finis \ref{PropUTenzfQ} : \begin{equation} g(\epsilon)-g(0)=f(a+\lambda \epsilon)-f(a)=f(a)+\lambda \epsilon f'(a)-f(a)=\lambda\epsilon f'(a). \end{equation} Le quotient différentiel devient donc \begin{equation} \frac{ g(\epsilon)-g(0) }{ \epsilon }=\frac{ \lambda \epsilon f'(a) }{ \epsilon }=\lambda f'(a). \end{equation} Il n'y a donc pas de problème à passer à la limite et nous avons \( g'(0)=f'(a)\). \end{proof} Par rapport à la dérivation, les produits scalaire et vectoriel vérifient une règle de Leibnitz. \begin{proposition} \label{PROPooFKKHooQZGXhE} Soit $I$ un intervalle de $\eR$. Si $u$ et $u$ sont dans $C^1(I,\eR^3)$, alors \begin{equation} \label{EqFormLeibProdscalVect} \begin{aligned}[] \frac{ d }{ dt }\big( u(t)\cdot v(t) \big) & =\big( u'(t)\cdot v(t) \big)+\big( u(t)\cdot v'(t) \big) \\ \frac{ d }{ dt }\big( u(t)\times v(t) \big) & =\big( u'(t)\times v(t) \big)+\big( u(t)\times v'(t) \big). \end{aligned} \end{equation} \end{proposition} Nous faisons la preuve pour le produit scalaire; sans doute que le produit vectoriel sera la même chose. \begin{proof} Nous considérons des fonctions dérivables \( f,g\colon \eR\to \eR^3\), et nous posons \( \varphi(t)=f(t)\cdot g(t)\). En ce qui concerne la dérivée de la fonction \( f\cdot g\colon \eR\to \eR\), nous devons étudier la limite \begin{equation} \label{EQooGRFKooNHceiW} \lim_{\epsilon\to 0}\frac{ \varphi(t+\epsilon)-\varphi(t) }{ \epsilon }=\lim_{\epsilon\to 0}\frac{ f(t+\epsilon)\cdot g(t+\epsilon)-f(t)\cdot g(t) }{ \epsilon }. \end{equation} La fonction \( f\) étant dérivable, la proposition \ref{PropUTenzfQ} nous donne une fonction \( \alpha\colon \eR\to \eR^3\) telle que \begin{equation} f(t+\epsilon)=f(t)+\epsilon f'(t)+\epsilon\alpha(\epsilon) \end{equation} et \( \lim_{\epsilon\to 0}\alpha(\epsilon)=0\). En substituant cela dans le numérateur de \eqref{EQooGRFKooNHceiW} nous calculons un peu : \begin{subequations} \begin{align} f(t+\epsilon)\cdot g(t+\epsilon)-f(t)\cdot g(t) & =\big( f(t)+\epsilon f'(t)+\epsilon \alpha(\epsilon) \big)\cdot\big( g(t)+\epsilon g'(t)+\epsilon\beta(\epsilon) \big) \\ & \quad - f(t)\cdot g(t) \\ & =\epsilon f(t)\cdot g'(t)+\epsilon^2 f'(t)\cdot \beta(\epsilon) \\ & \quad+\epsilon\alpha(\epsilon)\cdot g(t)+\alpha(\epsilon)\epsilon^2\cdot g'(t)+\epsilon^2\alpha(\epsilon)\cdot \beta(\epsilon). \end{align} \end{subequations} En divisant cela par \( \epsilon\) et en prenant la limite \( \epsilon\to 0\), et nous reste \begin{equation} f(t)\cdot g'(t)+f'(t)\cdot g(t). \end{equation} \end{proof} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Dérivée de la réciproque} %--------------------------------------------------------------------------------------------------------------------------- \begin{proposition}[\cite{XGIooNMtKqx}] \label{PropMRBooXnnDLq} Soit \( f\colon I\to J\) une fonction bijective, continue et dérivable\footnote{Définition~\ref{DEFooOYFZooFWmcAB}.}. Soient \( x_0\in I\) et \( y_0=f(x_0)\). Si \( f'(x_0)\neq 0\) alors la fonction réciproque \( f^{-1}\) est dérivable en \( y_0\) et sa dérivée est donnée par \begin{equation} (f^{-1})'(y_0)=\frac{1}{ f'(x_0) }. \end{equation} \end{proposition} \begin{proof} Pour rappel, une fonction dérivable est toujours continue (proposition~\ref{PropSFyxOWF}). Prouvons que \( f^{-1}\) est dérivable au point \( b=f(a)\in J\). Étant donné que \( f\) est dérivable en \( a\), nous avons \begin{equation}\label{EqJEWooSjQrfk} f'(a)=\lim_{x\to a} \frac{ f(x)-f(a) }{ x-a }. \end{equation} Par ailleurs, étant donnée la continuité de \( f^{-1}\) donnée par la proposition~\ref{ThoKBRooQKXThd}\ref{ItemEJZooKuFoeFiv}, nous avons \begin{equation} \lim_{\epsilon\to 0} f^{-1}(b+\epsilon)=f^{-1}(b)=a. \end{equation} Nous pouvons donc remplacer dans \eqref{EqJEWooSjQrfk} tous les \( x\) par \( f^{-1}(b+\epsilon)\) et prendre la limite \( \epsilon\to 0\) au lieu de \( x\to a\) : \begin{equation} \begin{aligned}[] f'(a) & =\lim_{\epsilon\to 0}\frac{ f\big( f^{-1}(b+\epsilon) \big)-f(a) }{ f^{-1}(b+\epsilon)-a } \\ & =\lim_{\epsilon\to 0}\frac{ b+\epsilon-f(a) }{ f^{-1}(b+\epsilon)-f^{-1}(b) } \\ & =\lim_{\epsilon\to 0}\frac{ \epsilon }{ f^{-1}(b+\epsilon)-f^{-1}(b) } \\ & =\frac{1}{ \lim_{\epsilon\to 0}\frac{ f^{-1}(b+\epsilon)-f^{-1}(b) }{ \epsilon } } \\ & =\frac{1}{ (f^{-1})'(b) }. \end{aligned} \end{equation} Nous avons utilisé le fait que \( f(a)=b\) et \( a=f^{-1}(b)\). \end{proof} \begin{proposition}[\cite{BIBooWTHJooTyNuub}] \label{PROPooSGTBooFxUuXK} Soit \(f \) une fonction dérivable et strictement monotone de l'intervalle \( I\) sur l'intervalle \( J\) (f est alors une bijection de $I$ vers $J$). Si \( f'\) ne s'annule par sur \( I\) alors \begin{enumerate} \item la fonction \( f\) est une bijection de \( I\) vers \( J\), \item la fonction \( f^{-1}\) est dérivable sur \( J\), \item et nous avons la formule \begin{equation} \label{EQooELIHooDxUFxH} (f^{-1})'=\frac{1}{ f'\circ f^{-1} }. \end{equation} \end{enumerate} \end{proposition} \index{réciproque!dérivabilité} \begin{normaltext} Très souvent on préfère retenir la formule \begin{equation}\label{EqWWAooBRFNsv} (f^{-1})'(y_0) = \frac{1}{f'\left((f^{-1})(y_0)\right)} \end{equation} Elle est très simple à retrouver : il suffit d'écrire \begin{equation} f^{-1}\big( f(x) \big)=x \end{equation} puis de dériver les deux côtés par rapport à \( x\) en utilisant la règle de dérivation des fonctions composées : \begin{equation} (f^{-1})'\big( f(x) \big)f'(x)=1. \end{equation} \end{normaltext} \begin{example}[difféomorphisme entre \( \eR\) et un ouvert borné] \label{EXooGKPNooZtmJen} Nous cherchons à construire une application dérivable et d'inverse dérivable entre \( \eR\) (en entier) et un ouvert borné de \( \eR\). Il serait tentant de prendre l'application arc tangente \begin{equation} \begin{aligned} \arctan\colon \eR & \to \left] -\frac{ \pi }{2} , \frac{ \pi }{2} \right[ \\ x & \mapsto \arctan(x) \end{aligned}, \end{equation} mais elle ne sera définie que dans le théorème~\ref{THOooUSVGooOAnCvC}. Nous posons \begin{equation} f(x)=\begin{cases} 2+\frac{1}{ x-2 } & \text{si } x\leq 1 \\ \frac{1}{ x } & \text{si } x>1. \end{cases} \end{equation} Cela est continue en \( x=1\) : il suffit de calculer les deux valeurs. En ce qui concerne la dérivabilité en \( x=1\), nous devons faire \begin{equation} \lim_{\epsilon\to 0}\frac{ f(1+\epsilon)-f(1) }{ \epsilon }. \end{equation} La limite à gauche est égale à la dérivée de \( x\mapsto 2+\frac{ 1 }{ x-2 }\) en \( x=1\) et la limite à droite est égale à la dérivée de \( x\mapsto 1/x\) en \( x=1\). Dans les deux cas nous trouvons \( -1\). \begin{center} \input{auto/pictures_tex/Fig_LMHMooCscXNNdU.pstricks} \end{center} Nous voyons vite que cette fonction est strictement décroissante; et un calcul de limite nous dit qu'il s'agit d'une bijection dérivable \begin{equation} f\colon \eR\to \mathopen] 0 , 2 \mathclose[. \end{equation} La proposition~\ref{PropMRBooXnnDLq} s'applique et la bijection réciproque est également dérivable (donc continue aussi). \end{example} \begin{probleme} Si vous connaissez un autre exemple, plus simple, de difféomorphisme \( f\colon \eR\to \mathopen] a , b \mathclose[\), faites-le moi savoir. Ne pas utiliser d'exponentielle (vous pensiez à bricoler quelque chose à partir de la primitive de \( x\mapsto e^{-x^2}\) ?) ni de fonctions trigonométriques. \end{probleme} \begin{example} Nous aimerions donner le logarithme comme exemple, mais l'exponentielle ne sera définie que dans longtemps à partir des séries entières. Allez voir l'exemple~\ref{ExZLMooMzYqfK} pour le logarithme comme inverse de l'exponentielle. \end{example} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Dérivée de fonction composée} %--------------------------------------------------------------------------------------------------------------------------- \begin{proposition}[\cite{BIBooPWHQooSUmtLC}] \label{PROPooDONLooWthqRR} Soient des intervalles \( I\) et \( J\) dans \( \eR\) ainsi que des fonctions \( f\colon I\to \eR\) et \( g\colon J\to \eR\) tels que \( g(J)\subset I\). Soit \( a\in J\). Nous supposons que \( f\) est dérivable en \( g(a)\) et \( g\) est dérivable en \( a\). Alors \( f\circ g\) est dérivable en \( a\) et \begin{equation} (f\circ g)'(a)=f'\big( g(a) \big)g'(a). \end{equation} \end{proposition} \begin{proof} Nous considérons la formule des accroissements finis sous la forme \eqref{EQooPWIZooVuhjmt}. Pour la fonction \( g\), nous écrivons \begin{equation} g(a+\epsilon)=g(a)+\epsilon g'(a)+\alpha\epsilon(\epsilon) \end{equation} avec \( \alpha(\epsilon)\to 0\). Et de même pour \( f\big( g(a) \big)\) : \begin{subequations} \begin{align} f\big( g(a) \big) & =f\big( g(a)+\epsilon g'(a)+\epsilon\alpha(\epsilon) \big) \\ & =f\big( g(a) \big)+\big( \epsilon g'(a)+\epsilon\alpha(\epsilon) \big)f'\big( g(a) \big)+\epsilon\beta\big( \epsilon g'(a)+\epsilon\alpha(\epsilon) \big) \end{align} \end{subequations} avec \( \beta(\epsilon)\to 0\). Nous avons donc, pour \( \epsilon\) assez petit pour que tout reste dans \( I\) et \( J\)\footnote{Et c'est là qu'on utilise la continuité de \( f\) et \( g\) garantie par la proposition \ref{PropSFyxOWF}.}, que \begin{equation} \frac{ (f\circ g)(a+\epsilon)-(f\circ g)(a) }{ \epsilon }=\big( g'(a)+\alpha(\epsilon) \big)f'\big( g(a) \big)+\beta\big( \epsilon g'(a)+\epsilon\alpha(\epsilon) \big). \end{equation} En ce qui concerne la limite \( \epsilon\to 0\), nous avons entre autres, \begin{equation} \lim_{\epsilon\to 0}\beta\big( \epsilon g'(a)+\epsilon\alpha(\epsilon) \big)=0, \end{equation} et donc bien \( (f\circ g)'(a)=g'( a )f'\big( g(a) \big)\). \end{proof} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Dérivée de fonction périodique} %--------------------------------------------------------------------------------------------------------------------------- \begin{definition} \label{DEFooHUZAooYyBmwe} Une fonction \( f\colon \eR\to \eR\) est \defe{périodique}{fonction périodique} si il existe \( T\in \eR\) tel que \begin{equation} f(x+T)=f(x) \end{equation} pour tout \( x\in \eR\). Un tel \( T\) est une \defe{période}{période} de \( f\). Nous disons que \( T\) est \emph{la} période de \( f\) si il est le minimum vérifiant la propriété. \end{definition} \begin{lemma}[\cite{MonCerveau}] \label{LEMooOGFGooCnTDjO} Si \( f\) est une fonction périodique de période \( T\), alors toutes les périodes sont de la forme \( kT\) avec \( k\in \eN^*\). \end{lemma} \begin{proof} Considérons une période \( t\). Nous avons \( t>T\) par hypothèse. Si \( t\) n'est pas un multiple de \( T\), la division euclidienne \ref{ThoDivisEuclide} permet d'écrire \( t=kT+l\) avec \( l<T\). Nous avons alors, pour tout \( x\in \eR\) : \begin{equation} f(x)=f(x+t)=f(x+kT+l)=f(x+l). \end{equation} Donc \( l\) est une période de \( f\). Cela n'est pas possible parce que \( T\) est la plus petite. \end{proof} \begin{lemma} \label{LEMooHWQYooXcNLts} Si \( f\colon \eR\to \eR\) est périodique et si \( T\) est une période de \( f\), alors \( f'\) est périodique et \( T\) en est une période. \end{lemma} \begin{proof} Soit \( a\in \eR\). Par hypothèse \( f\) est dérivable en \( a\) et les limites qui suivent existent : \begin{equation} f'(a+T)=\lim_{\epsilon\to 0}\frac{ f(a+T+\epsilon)-f(a+T) }{ \epsilon }=\lim_{\epsilon\to 0}\frac{ f(a+\epsilon)-f(a) }{ \epsilon }=f'(a). \end{equation} Nous avons utilisé la condition de périodicité en \( a\) et en \( a+\epsilon\). \end{proof} %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \section{Dérivation et croissance} %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Supposons une fonction dont la dérivée est positive. Étant donné que la courbe est « collée » à ses tangentes, tant que les tangentes montent, la fonction monte. Or, une tangente qui monte correspond à une dérivée positive, parce que la dérivée est le coefficient directeur de la tangente. Ce résultat très intuitif peut être prouvé rigoureusement. C'est la tache à laquelle nous allons nous atteler maintenant. \begin{proposition} \label{PropGFkZMwD} Si $f$ et $f'$ sont des fonctions continues sur l'intervalle $[a,b]$ et si $f'$ est strictement positive sur $[a,b]$, alors $f$ est croissante sur $[a,b]$. De la même manière, si $f'$ est strictement négative sur $[a,b]$, alors $f$ est décroissante sur $[a,b]$. \end{proposition} \begin{proof} Nous n'allons prouver que la première partie. La seconde partie se prouve en considérant $-f$ et en invoquant alors la première\footnote{Méditer cela.}. Prenons $x_1$ et $x_2$ dans $[a,b]$ tels que $x_1<x_2$. Par hypothèse, pour tout $x$ dans $[x_1,x_2]$, nous avons \begin{equation} f'(x)=\lim_{\epsilon\to 0}\frac{ f(x+\epsilon)-f(x) }{\epsilon} >0. \end{equation} Maintenant, la proposition~\ref{PropoLimPosFPos} dit que quand une limite est positive, alors la fonction dans la limite est positive sur un voisinage. En appliquant cette proposition à la fonction \begin{equation} r(\epsilon)=\frac{ f(x+\epsilon)-f(x) }{ \epsilon }, \end{equation} dont la limite en zéro est positive, nous trouvons que $r(\epsilon)>0$ pour tout $\epsilon$ pas trop éloigné de zéro. En particulier, il existe un $\delta>0$ tel que $\epsilon<\delta$ implique $r(\epsilon)>0$; pour un tel $\epsilon$, nous avons donc \begin{equation} r(\epsilon)=\frac{ f(x+\epsilon)-f(x) }{ \epsilon }>0. \end{equation} Étant donné que $\epsilon>0$, nous avons que $f(x+\epsilon)-f(x)>0$, c'est-à-dire que $f$ est strictement croissante entre $x$ et $x+\epsilon$. Jusqu'ici, nous avons prouvé que la fonction $f$ était strictement croissante dans un voisinage autour de chaque point de $[a,b]$. Cela n'est cependant pas encore tout à fait suffisant pour conclure. Ce que nous voudrions faire, c'est de dire, c'est prendre un voisinage $]a,m_1[$ autour de $a$ sur lequel $f$ est croissante. Donc, $f(m_1)>f(a)$. Ensuite, on prend un voisinage $]m_1,m_2[$ de $m_1$ sur lequel $f$ est croissante. De ce fait, $f(m_2)>f(m_1)>f(a)$. Et ainsi de suite, nous voulons construire des $m_3$, $m_4$,\ldots jusqu'à arriver en $b$. Hélas, rien ne dit que ce processus va fonctionner. Il faut trouver une subtilité. Le problème est que les voisinages sur lesquels la fonction est croissante sont peut-être de plus en plus petits, de telle sorte à ce qu'il faille une infinité d'étapes avant d'arriver à bon port (en $b$). Heureusement, nous pouvons drastiquement réduire le nombre d'étapes en nous souvenant du théorème de Borel-Lebesgue~\ref{ThoBOrelLebesgue}. Nous notons par $\mO_x$, un ouvert autour de $x$ tel que $f$ soit strictement croissante sur $\mO_x$. Un tel voisinage existe. Cela fait une infinité d'ouverts tels que \begin{equation} [a,b]\subseteq\bigcup_{x\in[a,b]}\mO_x. \end{equation} Ce que le théorème dit, c'est qu'on peut en choisir un nombre fini qui recouvre encore $[a,b]$. Soient $\{ \mO_{x_1},\ldots,\mO_{x_n} \}$, les heureux élus, que nous supposons pris dans l'ordre : $x_1<x_2<\ldots<x_n$. Nous avons \begin{equation} [a,b]\subseteq\bigcup_{i=1}^n\mO_i. \end{equation} Quitte à les rajouter à la collection, nous supposons que $x_1=a$ et que $x_n=b$. Maintenant nous allons choisir encore un sous-ensemble de cette collection d'ouverts. On pose $\mA_1=\mO_{x_1}$. Nous savons que $\mA_1$ intersecte au moins un des autres $\mO_{x_i}$. Cette affirmation vient du fait que $[a,b]$ est connexe (proposition~\ref{PropInterssiConn}), et que si $\mO_{x_1}$ n'intersectait personne, alors \begin{equation} \begin{aligned}[] \mO_{x_1} & & \text{et} & & \bigcup_{i=2}^n\mO_{x_i} \end{aligned} \end{equation} forment une partition de $[a,b]$ en deux ouverts disjoints, ce qui n'est pas possible parce que $[a,b]$ est connexe. Nous nommons $\mA_2$, un des ouverts $\mO_{x_i}$ qui intersecte $\mA_1$. Disons que c'est $\mO_k$. Notons que $\mA_1\cup\mA_2$ est un intervalle sur lequel $f$ est strictement croissante. En effet, si $y_{12}$ est dans l'intersection, $f(a)<f(y_{12})$ parce que $f$ est strictement croissante sur $\mA_1$, et pour tout $x>y_{12}$ dans $\mA_2$, $f(x)>f(y_{12})$ parce que $f$ est strictement croissante dans $\mA_2$. Maintenant, nous éliminons de la liste des $\mO_{x_i}$ tous ceux qui sont inclus dans $\mA_1\cup\mA_2$. Dans ce qu'il reste, il y en a automatiquement un qui intersecte $\mA_1\cup\mA_2$, pour la même raison de connexité que celle invoquée plus haut. Nous appelons cet ouvert $\mA_3$, et pour la même raison qu'avant, $f$ est strictement croissante sur $\mA_1\cup\mA_2\cup\mA_3$. En recommençant suffisamment de fois, nous finissons par devoir prendre un des $\mO_{x_i}$ qui contient $b$, parce qu'au moins un des $\mO_{x_i}$ contient $b$. À ce moment, nous avons fini la démonstration. \end{proof} Il est intéressant de noter que ce théorème concerne la croissance d'une fonction sous l'hypothèse que la dérivée est positive. Il nous a fallu très peu de temps, en utilisant la positivité de la dérivée, pour conclure qu'autour de tout point, la fonction était strictement croissante. À partir de là, c'était pour ainsi dire gagné. Mais il a fallu un réel travail de topologie très fine\footnote{et je te rappelle que nous avons utilisé la proposition~\ref{PropInterssiConn}, qui elle même était déjà un très gros boulot !} pour conclure. Étonnant qu'une telle quantité de topologie soit nécessaire pour démontrer un résultat essentiellement analytique dont l'hypothèse est qu'une limite est positive, n'est-ce pas ? Une petite facile, maintenant. \begin{proposition} Si $f$ est croissante sur un intervalle, alors $f'\geq 0$ à l'intérieur de cet intervalle, et si $f$ est décroissante sur l'intervalle, alors $f'\leq 0$ à l'intérieur de l'intervalle. \end{proposition} Note qu'ici, nous demandons juste la croissance de $f$, et non sa \emph{stricte} croissance. \begin{proof} Soit $f$, une fonction croissante sur l'intervalle $I$, et $x$ un point intérieur de $I$. La dérivée de $f$ en $x$ vaut \begin{equation} f'(x)=\lim_{\epsilon\to 0}\frac{ f(x+\epsilon)-f(x) }{\epsilon}, \end{equation} mais, comme $f$ est croissante sur $I$, nous avons toujours que $f(x+\epsilon)-f(x)\geq0$ quand $\epsilon>0$, et $f(x+\epsilon)-f(x)\leq0$ quand $\epsilon<0$, donc cette limite est une limite de nombres positifs ou nuls, qui est donc positive ou nulle. Cela prouve que $f'(x)\geq 0$. \end{proof} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Théorèmes de Rolle et des accroissements finis} %--------------------------------------------------------------------------------------------------------------------------- \begin{theorem}[Théorème de Rolle\cite{ooNRTLooCpjVdc,ooFQESooWuxtpx}] \label{ThoRolle} Soit $f$, une fonction continue sur $[a,b]$ et dérivable sur $]a,b[$. Si $f(a)=f(b)$, alors il existe un point $c\in]a,b[$ tel que $f'(c)=0$. \end{theorem} \index{théorème!Rolle} \begin{proof} Étant donné que $[a,b]$ est un intervalle compact, l'image de $[a,b]$ par $f$ est un intervalle compact, soit $[m,M]$ (théorème~\ref{ThoImCompCotComp}). Si $m=M$, alors le théorème est évident : c'est que la fonction est constante, et la dérivée est par conséquent nulle. Supposons que $M> f(a)$ (il se peut que $M=f(a)$, mais alors si $f$ n'est pas constante, il faut avoir $m<f(a)$ et le reste de la preuve peut être adaptée). Comme $M$ est dans l'image de $[a,b]$ par $f$, il existe $c\in ]a,b[$ tel que $f(c)=M$. Considérons maintenant la fonction \begin{equation} \tau(x) =\frac{ f(c+x)-f(c) }{ x }. \end{equation} Par définition, $\lim_{x\to 0}\tau(x)=f'(c)$. Par hypothèse, si $u<c$, \begin{equation} \tau(u-c) = \frac{ f(u)-f(c) }{ u-c }>0 \end{equation} parce que $u-c<0$ et $f(u)-f(c)<0$. Par conséquent, $\lim_{x\to 0}\tau(x)\geq 0$. Nous avons aussi, pour $v>c$, \begin{equation} \tau(v-c) = \frac{ f(v)-f(c) }{ v-c }<0 \end{equation} parce que $v-c>0$ et $f(v)-f(c)<0$. Par conséquent, $\lim_{x\to 0}\tau(x)\leq 0$. Mettant les deux ensemble, nous avons $f'(c)=\lim_{x\to 0}\tau(x)=0$, et $c$ est le point que nous cherchions. \end{proof} Voici une généralisation du théorème de Rolle, dans le cas où nous n'aurions pas deux points sur lesquels la fonction est identique, mais deux points en lesquels la limite de la fonction est identique. Typiquement, lorsque les points en question sont \( \pm\infty\). \begin{theorem}[Généralisation de Rolle\cite{ooNRTLooCpjVdc}] \label{THOooXDTBooFeSZoK} Soient \( -\infty\leq a<b\leq +\infty\). Soit une fonction dérivable \( f\colon \mathopen] a , b \mathclose[\to \eR\) telle que \begin{equation} \lim_{x\to a} f(x)=\lim_{x\to b} f(x)=\ell \end{equation} avec \( \ell\in \bar \eR\). Alors il existe \( x\in \mathopen] a , b \mathclose[\) tel que \( f'(x)=0\). \end{theorem} \begin{proof} Soit un difféomorphisme\footnote{Définition~\ref{DefAQIQooYqZdya}.} strictement croissant \( \varphi\colon \eR\to \mathopen] \alpha , \beta \mathclose[\). Pour cela vous pouvez bricoler à partir de l'exemple~\ref{EXooGKPNooZtmJen}. Mais n'utilisez pas la fonction arc tangente, parce qu'elle n'est définie qu'au théorème~\ref{THOooUSVGooOAnCvC}. Nous posons \( a'=\varphi(a)\), \( b'=\varphi(b)\) et \begin{equation} g= \varphi\circ f\circ \varphi^{-1}\colon \mathopen] a' , b' \mathclose[\to \mathopen] \alpha , \beta \mathclose[. \end{equation} Cela est une fonction dérivable et continue sur \( \mathopen[ a' , b' \mathclose]\) en posant \( g(a')=g(b')=\varphi(\ell)\). Donc il existe \( c'\in\mathopen] a' , b' \mathclose[\) tel que \( g'(c')=0\). En posant \( c=\varphi^{-1}(c')\) nous avons \( c\in \mathopen] a , b \mathclose[\) et, en utilisant de nombreuses fois la règle de dérivation des fonctions composées~\ref{PROPooOUZOooEcYKxn}\ref{ITEMooLYZCooVUPTyh}, \begin{subequations} \begin{align} f'(c) & =f'\big( \varphi^{-1}(c') \big) \\ & =(\varphi^{-1})'\Big( (g\circ \varphi)\big( \varphi^{-1}(c') \big) \Big)(g\circ\varphi)'\big( \varphi^{-1}(c') \big) \\ & =(\varphi^{-1})'\big( g(c') \big)\underbrace{g'(c')}_{=0}\varphi'\big( \varphi^{-1}(c') \big) \\ & =0. \end{align} \end{subequations} \end{proof} Une autre généralisation de Rolle, avec des dérivées d'ordre supérieur. \begin{proposition}[\cite{ooWCFFooRMBEJl}] \label{PROPooCPCAooJjOZNy} Soit un intervalle ouvert \( I\subset \eR\) contenant \( a,b\) (\( a\neq b\)). Soit une fonction \( f\in C^{k+1}(I,\eR)\). Si \( f(a)=f(b)\) et si \( f^{(j)}(a)=0\) pour \( j=1,\ldots, n\), alors il existe \( x\in \mathopen] a , b \mathclose[\) tel que \( f^{(n+1)}(c)=0\). \end{proposition} \begin{proof} Le théorème de Rolle \ref{ThoRolle} nous dit qu'il existe \( c_1\in \mathopen] a , b \mathclose[\) tel que \( f'(c_1)=0\). Mais alors \( f'(a)=f'(x_1)=0\), et le théorème de Rolls appliqué à \( f'\) donne \( c_2\in \mathopen] a , c_1 \mathclose[\) tel que \( f''(c_2)=0\). Continuant ainsi \( n\) fois, il existe \( c\in \mathopen] a ,b\mathclose[\) tel que \( f^{(n+1)}(c)=0\). \end{proof} Le théorème suivant est le théorème des \defe{accroissements finis}{théorème!accroissements finis!dans $\eR$}. Une version avec des dérivées partielles sera la proposition \ref{PROPooCAWBooINcNxj}. \begin{theorem}[Accroissements finis] \label{ThoAccFinis} Soit $f$, une fonction continue sur $[a,b]$ et dérivable sur $]a,b[$. \begin{enumerate} \item \label{ITEMooFZONooXJqLyX} Il existe au moins un réel $c\in]a,b[$ tel que \begin{equation} f'(c)=\frac{ f(b)-f(a) }{ b-a } \end{equation} Autrement dit, la tangente en \( c\) est parallèle à la corde entre \( a\) et \( b\). \item \label{ITEMooXRQKooDBFpdQ} Nous avons la majoration \begin{equation} \big| \frac{ f(b)-f(a) }{ b-a } \big| \leq \sup_{x\in\mathopen[ a , b \mathclose]}| f'(x) | | b-a |. \end{equation} \end{enumerate} \end{theorem} \begin{proof} Considérons la fonction \begin{equation} \tau(x)=f(x)-\big( \frac{ f(b)-f(a) }{ b-a }x + f(a) - a\frac{ f(b)-f(a) }{ b-a } \big), \end{equation} c'est-à-dire la fonction qui donne la distance entre $f$ et le segment de droite qui lie $(a,f(a))$ à $(b,f(b))$. Par construction, $\tau(a)-\tau(b)=0$, donc le théorème de Rolle s'applique à $\tau$ pour laquelle il existe donc un $c\in]a,b[$ tel que $\tau'(c)=0$. En utilisant les règles de dérivation, nous trouvons que la dérivée de $\tau$ vaut \begin{equation} \tau'(x)= f'(x)-\frac{ f(b)-f(a) }{ b-a }, \end{equation} donc dire que $\tau'(c)=0$ revient à dire que $f(b)-f(a)=(b-a)f'(c)$, ce qu'il fallait démontrer. La majoration est une conséquence immédiate, parce que le supremum de \( | f'(x) |\) est forcément plus grand que \( | f'(c) |\). \end{proof} Une généralisation pour une fonction sur un intervalle \( \mathopen] a , b \mathclose[\) où \( a\) et \( b\) peuvent être infinis. \begin{theorem}[Généralisation des accroissements finis] \label{THOooRIIBooOjkzMa} Soient \( -\infty\leq a<b\leq +\infty\) et \( f,g\) des fonctions continues sur \( \mathopen[ a , b \mathclose]\) et dérivables sur \( \mathopen] a , b \mathclose[\). Si \( a=-\infty\) : \begin{itemize} \item Nous demandons la continuité sur \( \mathopen] -\infty , b \mathclose]\) et la dérivabilité sur \( \mathopen] -\infty , b \mathclose[\). \item Nous notons \( f(a)\) la limite \( \lim_{x\to -\infty} f(x)\), et nous supposons qu'elle est finie. \end{itemize} Mêmes conventions si \( b=+\infty\). Alors il existe \( c\in \mathopen] a , b \mathclose[\) tel que \begin{equation} \big( f(b)-f(a) \big)g'(c)=\big( g(b)-g(a) \big)f'(c). \end{equation} \end{theorem} \begin{proof} Nous posons \begin{equation} h(t)=\big( g(b)-g(a) \big)f(t)-\big( f(b)-f(a) \big)g(t). \end{equation} Nous avons \( \lim_{t\to a} h(t)=\lim_{t\to b} h(t)\), de telle sorte que le théorème de Rolle généralisé~\ref{THOooXDTBooFeSZoK} s'applique et il existe \( c\in \mathopen] a , b \mathclose[\) tel que \( h'(c)=0\). Pour ce \( c\) nous avons \begin{equation} 0=h'(c)=\big( f(b)-f(a) \big)g'(c)-\big( g(b)-g(a) \big)f'(c), \end{equation} et donc \begin{equation} \big( f(b)-f(a) \big)g'(c)=\big( g(b)-g(a) \big)f'(c). \end{equation} \end{proof} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Règle de l'Hospital} %--------------------------------------------------------------------------------------------------------------------------- \begin{proposition}[Règle de l'Hospital pour \( \frac{ 0 }{ 0 }\)\cite{ooHQARooDfptJC}] \label{PROPooBZHTooHmyGsy} Soient des fonctions \( f,g\) dérivables sur \( \mathopen] a , b \mathclose[\) et dont la limite en \( a\) est nulle. Si \( g'\) ne s'annule pas sur \( \mathopen] a , b \mathclose[\) et si \begin{equation} \lim_{x\to a^+} \frac{ f'(x) }{ g'(x) }=\ell \end{equation} alors \begin{equation} \label{EQooJHWYooLGdbPH} \lim_{x\to a^+} \frac{ f(x) }{ g(x) }=\ell. \end{equation} Ici \( \ell\in \bar \eR\), et les hypothèses garantissent l'existence de la limite \eqref{EQooJHWYooLGdbPH}. \end{proposition} \begin{proof} Soit \( x\in\mathopen] a , b \mathclose[\). Les fonctions \( f\) et \( g\) sont dérivables sur \( \mathopen] a , x \mathclose[\) et continues sur \( \mathopen[ a , x \mathclose]\), de telle sorte que le théorème~\ref{THOooRIIBooOjkzMa} s'applique et nous avons \( c_x\in \mathopen] a , x \mathclose[\) tel que \begin{equation} \label{EQooMALUooNagavh} \big( f(x)-f(a) \big)g'(c_x)=\big( g(x)-g(a) \big)f'(c_x). \end{equation} Nous nous souvenons de ce que signifient les notations dans le théorème : les notations \( f(a)\), \( f(x)\), \( g(a)\) et \( g(x)\) désignent en réalité les limites. Donc dans \eqref{EQooMALUooNagavh}, nous avons \( f(a)=g(a)=0\). D'autre part nous avons \( g(x)\neq g(a)\), sinon le théorème de Rolle~\ref{THOooXDTBooFeSZoK} annulerait \( g'\) quelque part dans \( \mathopen] a , x \mathclose[\). Nous pouvons donc récrire \eqref{EQooMALUooNagavh} sous la forme \begin{equation} \label{EQooUCLVooFgAfwC} \frac{ f(x) }{ g(x) }=\frac{ f'(c_x) }{ g'(c_x) }. \end{equation} Mais \( \lim_{x\to a^+} c_x=a\) parce que \( c_x\in\mathopen] a , x \mathclose[\). Donc la limite du membre de droite de \eqref{EQooUCLVooFgAfwC} lorsque \( x\to a^+\) existe et vaut \( \ell\). La même limite à gauche doit alors exister et valoir la même valeur. \end{proof} \begin{proposition}[L'Hospital pur \( \frac{ \infty }{ \infty }\)] \label{PROPooTJVCooMeUhIy} Soit \( f\) et \( g\) deux fonctions \begin{enumerate} \item dérivables sur \( \mathopen] a , b \mathclose[\), \item dont les limites en \( a\) sont toutes deux \( \infty\), \item \( g'\neq 0\) sur \( \mathopen] a , b \mathclose[\). \item \begin{equation} \label{EQooVFYCooMjOGtI} \lim_{x\to a^+} \frac{ f'(x) }{ g'(x) }=\ell\in \bar \eR. \end{equation} \end{enumerate} Alors \begin{equation} \lim_{x\to a^+} \frac{ f(x) }{ g(x) }=\ell. \end{equation} Cette dernière égalité signifie «la limite existe et vaut \( \ell\)». \end{proposition} \begin{proof} Soit un intervalle \( \mathopen] x , y \mathclose[\) strictement inclus dans \( \mathopen] a , b \mathclose[\) avec \( x,y\in\eR\). Par le théorème des accroissements finis généralisés~\ref{THOooRIIBooOjkzMa} il existe \( c\in \mathopen] x , y \mathclose[\) tel que \begin{equation} \frac{ f(x)-f(y) }{ g(x)-g(y) }=\frac{ f'(c) }{ g'(c) }. \end{equation} Notons que le dénominateur à gauche n'est pas nul à cause de Rolle et de l'hypothèse que \( g'\) ne s'annule pas sur \( \mathopen[ x , y \mathclose]\). Nous isolons \( f(x)\) : \begin{equation} \label{EQooDFXNooJhdUca} f(x)=\frac{ f'(c) }{ g'(c) }\Big( g(x)-g(y) \Big)+f(y). \end{equation} Avant de diviser par \( g(x)\) nous devons prendre quelques précautions. Soit \( V\), un voisinage de \( \ell\)\footnote{Vous savez ce que signifie un «voisinage de \( \infty\)» ? Allez voir la définition \ref{DEFooRUyiBSUooALDDOa}.}. Vu la limite \eqref{EQooVFYCooMjOGtI}, il existe \( y\in \mathopen] a , b \mathclose[\) tel que \begin{equation} \frac{ f'(t) }{ g'(t) }\in V \end{equation} pour tout \( t\in \mathopen] a , y \mathclose[\). Nous utilisons ici avec subtilité le fait que ces intervalles sont une base de la topologie autour de \( \infty\). Maintenant \( f(y)\) et \( g(y)\) sont fixés et sont des nombres réels. Vu que \( \lim_{x\to a} g(x)=0\) nous pouvons choisir \( r<y\) tel que nous ayons simultanément \begin{enumerate} \item \( g(x)\neq 0\) sur \( \mathopen] a , r \mathclose[\), \item \begin{equation} | \frac{ g(y) }{ g(x) } |\leq \epsilon \end{equation} et \begin{equation} | \frac{ f(y) }{ g(x) } |\leq \epsilon \end{equation} pour tout \( x\in \mathopen] a , r \mathclose[\). \end{enumerate} Nous sommes maintenant armés de \( y\) et \( r\) satisfaisant tout cela et nous pouvons traiter avec la formule \eqref{EQooDFXNooJhdUca} en ne la considérant que pour \( x\in \mathopen] a , r \mathclose[\). Soit \( x\in \mathopen] a , r \mathclose[\); il existe \( c_x\in \mathopen] a , x \mathclose[\) tel que \begin{equation} \label{EQooNEZQooYGJmFW} \frac{ f(x) }{ g(x) }=\frac{ f'(c_x) }{ g'(c_x) }\left( 1-\frac{ g(y) }{ g(x) } \right)+\frac{ f(y) }{ g(x) }. \end{equation} Nous avons : \begin{enumerate} \item \( \lim_{x\to a^+} c_x=a\), \item \begin{equation} \lim_{x\to a^+}\frac{ f'(c_x) }{ g'(c_x) }=\lim_{x\to a^+} \frac{ f'(x) }{ g'(x) }=\ell, \end{equation} \item \begin{equation} \lim_{x\to a^+} \left( 1-\frac{ g(y) }{ g(x) } \right)=1, \end{equation} \item \( \lim_{x\to a^+} \frac{ f(y) }{ g(x) }=0\). \end{enumerate} Donc chaque partie du membre de droite de \eqref{EQooNEZQooYGJmFW} a une limite bien déterminée pour \( x\to a^+\). Les règles de calcul s'appliquent et nous avons \begin{equation} \lim_{x\to a^+} \frac{ f(x) }{ g(x) }=\ell\times 1+0=\ell. \end{equation} \end{proof} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Dérivée et primitive} %--------------------------------------------------------------------------------------------------------------------------- \begin{corollary} \label{CORooEOERooYprteX} Soit $f$ une fonction dérivable sur $[a,b]$ telle que $f'(x) = 0$ pour tout $x \in [a,b]$. Alors $f$ est constante sur $[a,b]$. \end{corollary} \begin{proof} Si $f$ n'était pas constante sur $[a,b]$, il existerait un $x_1\in ]a,b[$ tel que $f(a)\neq f(x_1)$, et dans ce cas, il existerait, par le théorème des accroissements finis~\ref{ThoAccFinis}, un $c\in]a,x_1[$ tel que \begin{equation} f'(c)=\frac{ f(x_1)-f(a) }{ x_1-a }\neq 0, \end{equation} ce qui contredirait les hypothèses. \end{proof} \begin{corollary} \label{CorNErEgcQ} Soient $f$ et $g$, deux fonctions dérivables sur $[a,b]$ telles que \begin{equation} f'(x) = g'(x) \end{equation} pour tout $x \in [a,b]$. Alors existe un réel $C$ tel que $f (x) = g (x) + C$ pour tout $x\in [a,b]$. \end{corollary} \begin{proof} Considérons la fonction $h(x)=f(x)-g(x)$, dont la dérivée est, par hypothèse, nulle. L'annulation de la dérivée entraine par le corolaire~\ref{CorNErEgcQ} que $h$ est constante. Si $h(x)=C$, alors $f(x)=g(x)+C$, ce qu'il fallait prouver. \end{proof} \begin{definition} \label{DefXVMVooWhsfuI} Soit \( I\) un intervalle ouvert de \( \eR\) et une fonction \( f\colon I\to \eR\). La fonction \( F\colon I\to \eR\) est une \defe{primitive}{primitive!fonction} de \( f\) si \( F\) est dérivable sur \( I\) et si \( F'(x)=f(x)\) pour tout \( x\) dans \( I\). \end{definition} Exprimé en termes des primitives, le corolaire~\ref{CorNErEgcQ} signifie que \begin{corollary} \label{CorZeroCst} Si $F$ et $G$ sont deux primitives de la même fonction $f$ sur un intervalle, alors il existe une constante $C$ pour laquelle $F(x)=G(x)+C$. \end{corollary} Cela signifie qu'il n'y a, en réalité, pas des milliards de primitives différentes à une fonction. Il y en a essentiellement une seule, et puis les autres, ce sont juste les mêmes, mais décalées d'une constante. \begin{remark} L'hypothèse de se limiter à un intervalle est importante parce que si on considère la fonction sur deux intervalles disjoints, nous pouvons choisir la constante indépendamment dans l'un et dans l'autre. Par exemple la fonction \begin{equation} F(x)=\begin{cases} \ln(x)+1 & \text{si } x>0 \\ \ln(x)-7 & \text{si } x<0 \end{cases} \end{equation} est une primitive de \( \frac{1}{ x }\) sur l'ensemble \( \eR\setminus\{ 0 \}\). Certains ne s'en privent pas. Le logiciel \href{https://www.sagemath.org}{ Sage } par exemple fait ceci : \begin{verbatim} sage: f(x)=1/x sage: F=f.integrate(x) sage: A=F(x)-F(-x) sage: A.full_simplify() I*pi \end{verbatim} En réalité lorsque \( x>0\), Sage définit \( \ln(-x)=\ln(x)+i\pi\). Cela a une certaine logique parce que \( \ln(-1)=i\pi\) (du fait que \( e^{i\pi}=-1\)), mais si on ne le sait pas, ça peut étonner. \end{remark} \begin{normaltext} Il existe plusieurs primitives à une fonction donnée. En physique, la constante arbitraire est souvent fixée par une condition initiale, comme nous le verrons dans la section~\ref{SecMRUAsecondeGGdQoT}. \end{normaltext} %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \section{Fonctions de plusieurs variables} %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ La physique, et les sciences en général, regorgent de fonctions à plusieurs variables. \begin{description} \item[Accélération centripète]\footnote{Appelez la «centrifuge» si vous voulez; ça ne me fait ni chaud ni froid.} Si une masse $m$ tourne sur un cercle, elle subira une accélération dirigée vers l'intérieur égale à \begin{equation} F(v,r)=\frac{ mv^2 }{ r } \end{equation} où $r$ est le rayon du cercle et $v$ est la vitesse. \item[Pression dans un gaz] Si on a $n$ moles de gaz dans un volume $V$ a une température $T$, alors la pression sera donnée par la fonction de trois variables \begin{equation} p=\frac{ nRT }{ V } \end{equation} où $R$ est la constante des gaz parfaits. \end{description} En mathématique, on peut inventer de nombreuses fonctions de plusieurs variables. La fonction \begin{equation} f(x,y)=x^2+xy\cos(x^2+y^3) \end{equation} est définie sur $\eR^2$. La fonction \begin{equation} f(x,y,z)=\frac{ x+y-2z }{ 1-x^2-y^2-z^2 } \end{equation} est définie sur $\eR^3$ moins la sphère unité $\{ x^2+y^2+z^2=1 \}$. La plus grande partie de ce cours est consacrée à l'étude des fonctions de plusieurs variables. Nous allons maintenant donner quelques indications sur comment <<dessiner>> une telle fonction. Vous connaissez déjà la définition de graphe pour une fonction $f$ d'une seule variable à valeurs dans $\eR$ : c'est l'ensemble des points du plan de la forme $(x, f(x))$. Vous voyez que cet ensemble n'est pas vraiment un gros morceau de $\eR^2$ parce que son intérieur est vide : il y a une seule valeur de $f$ qui correspond au point $x$, donc une boule de $\eR^2$ centrée en $(x, f(x))$ de n'importe quel rayon contient toujours des points qui ne font pas partie du graphe de $f$. %La première chose qu'on a envie de dire est que un tel graphe est une courbe dans $\eR^2$ mais cela n'est pas toujours vrai. Le graphe de la fonction cosinus est bien une courbe dans dans le plan, mais le graphe de la fonction tangente est une réunion infinie de courbes. Ce qui est vrai est que le graphe d'une fonction d'une variable est \emph{localement} une courbe si la fonction n'est pas trop mal choisie. % exemple? Nous voulons donner une définition assez générale pour le graphe d'une fonction \begin{definition} Soit $f$ une fonction de $\eR^m$ dans $\eR^n$. Le \defe{graphe}{graphe!fonction} de $f$ est la partie de $\eR^m\times \eR^n$ de la forme \begin{equation} \Graph f= \{ (x,y)\in \eR^m\times \eR^n \,|\, y=f(x)\}. \end{equation} \end{definition} Cette définition se spécialise de la façon suivante dans les cas communs. Soit $f$ une fonction de $\eR^m$ dans $\eR$. Le graphe de $f$ est la partie de $\eR^m\times \eR$ donné par \begin{equation} \Graph f= \{ (x,y)\in \eR^m\times \eR \,|\, y=f(x)\}. \end{equation} Et pour les fonctions \( \eR^2\to \eR\) : \begin{equation} \Graph f= \{ (x,y,z)\in\eR^2\tq z=f(x,y) \}. \end{equation} C'est cette définition qu'il faut garder à l'esprit lorsqu'on travaille sur des dessins en trois dimensions. Si $f$ est une fonction de deux variables indépendantes $x$ et $y$ à valeurs dans $\eR$, alors un point dans le graphe de $f$ est un point $(x,y,z)\in\eR^3$ tel que \begin{equation} z=f(x,y), \end{equation} ou encore, un point de la forme \begin{equation} \big( x,y,f(x,y) \big). \end{equation} %Si $g$ est une fonction d'une variable $x$ à valeurs dans $\eR^2$, alors un point dans le graphe de $g$ prend la forme $(x,g_1(x), g_2(x))$, où $g_1$ et $g_2$ sont les composantes de $g$. Dans les deux cas le graphe est un sous-ensemble de $\eR^3$. %Nous considérons d'abord le cas d'une fonction $f$ de deux variables $x$ et $y$ à valeurs dans $\eR$. L'espace $\eR^3$ a trois dimensions, cela veut dire que il faut fixer trois paramètres indépendants pour désigner un point de manière unique (voir, au cours d'une deuxième lecture de ces notes, la section sur les coordonnées cylindriques et sphériques,~\ref{sec_coord}). Le graphe d'une fonction comme $f$ est un sous-ensemble de $\eR^3$ où l'un des trois paramètres est d'office la valeur de $f$, donc il est décrit par seulement deux paramètres $x$ et $y$. Son intérieur est alors vide et, si $f$ est une fonction <<suffisamment gentille>>, $\Graph f$ est localement une surface dans $\eR^3$. Nous avons parfois besoin de donner des représentations graphiques d'une fonction. Nous pouvons, par exemple, penser à la fonction que associe à un point de la Terre son altitude. Lorsqu'on part pour une promenade en montagne on a envie de connaitre le graphe de cette fonction qui correspond en fait à la surface de la montagne. Bien sur nous ne voulons pas amener avec nous un modèle en 3D de la montagne donc il nous faut une méthode efficace pour projeter le graphe de $f$ sur le plan $x$-$y$ tout en gardant les informations fondamentales. Pour cela nous avons besoin de deux définitions (à ne pas confondre !) \begin{definition} Soit $f$ une fonction de $\eR^2$ dans $\eR$ et soit $c$ dans $\eR$. La \defe{$z$-section}{section!de graphe} de $\Graph f$ à la hauteur $c$ est donné par \[ S^z_c=\{ (x,y,c)\in \eR^3\,|\, f(x,y)=c\}. \] \end{definition} \begin{definition}\label{def_niveau} Soit $f$ une fonction de $\eR^n$ dans $\eR$ et soit $c$ dans $\eR$. La \defe{courbe de niveau}{courbe de niveau} de $f$ à la hauteur $c$ est l'ensemble \begin{equation} N_c=\{ (x1,\ldots, x_n)\in \eR^n\,|\, f(x1,\ldots, x_n)=c\}. \end{equation} \end{definition} On peut représenter la fonction $f$ d'une façon très précise en traçant quelques-unes de ses courbes de niveau. Dans la suite on pourra considérer aussi les $x$-sections et les $y$-sections du graphe d'une fonction de deux variables. La $x$-section de $\Graph f$ à la hauteur $a$ est \[ S^x_a=\{(a,y,z)\in\eR^3\,|\, f(a,y)=z\}. \] Comme vous avez peut être déjà compris, $S^x_a$ est le graphe de la fonction de $y$ qu'on obtient de $f$ en fixant $x=a$. Cette fonction est appelée $x$-section de $f$ pour $x=a$. Certaines surfaces dans $\eR^3$ sont le graphe d'une fonction. \begin{example} Quelques graphes importants. \begin{description} \item[Un plan non vertical] Tout plan dans $\eR^3$ peut être décrit par une équation de la forme \[ a(x-x_0)+ b(y-y_0) + c(z-z_0) = r, \] où, $(x_0, y_0, z_0)$ est vecteur dans $\eR^3$, et $a$, $b$, $c$ et $r$ sont des nombres réels. Si $c\neq 0$ alors le plan n'est pas vertical et on peut dire que il est le graphe de la fonction \[ P(x,y)= \frac{r+cz_0 -a(x-x_0)-b(y-y_0)}{c}, \] quitte à choisir des nouvelles constantes $s$, $t$, $q$, \[ P(x,y)=sx +ty +q. \] \item[Un paraboloïde elliptique] Pour tous $\alpha$ et $\beta$ dans $\eR$ les graphes des fonctions \[ PE_1(x,y)=\frac{x^2}{\alpha^2}+\frac{y^2}{\beta^2} \] ou de la fonction \[ PE_2(x,y)=-\frac{x^2}{\alpha^2}-\frac{y^2}{\beta^2} \] sont des paraboloïdes elliptiques. Le premier est contenu dans le demi-espace $z\geq 0$, l'autre dans $z\leq 0$. Le nom de cette surface vient de la forme de ses sections. En fait toutes sections $S^z_c$ sont des ellipses, alors que les sections $S^x_a$ et $S^y_b$ sont des paraboles. \item[Un paraboloïde hyperbolique (selle)] Pour tous $\alpha$ et $\beta$ dans $\eR$ les graphes des fonctions \[ PH_1(x,y)=\frac{x^2}{\alpha^2}-\frac{y^2}{\beta^2} \] ou de la fonction \[ PH_2(x,y)=-\frac{x^2}{\alpha^2}+\frac{y^2}{\beta^2} \] sont des paraboloïdes hyperboliques. Remarquez que les sections $S^z_c$ de ce graphe sont des hyperboles, alors que les sections $S^x_a$ et $S^y_b$ sont des paraboles. \item[Une demi-sphère] La fonction $S^+=\sqrt{R^2-x^2-y^2}$ a pour graphe la demi-sphère supérieure centrée en l'origine et de rayon $R$. Le dernier de ces exemples nous signale une chose très importante : une sphère entière n'est pas le graphe d'une fonction de $x$ et $y$. Par contre, une demi-sphère est bien le graphe de la fonction $f(x,y)=\sqrt{1-x^2-y^2}$. L'équation que nous utilisons pour d'écrire une sphère de rayon $R$ centrée en l'origine est \[ x^2+y^2+z^2=R^2 \] Donc, à chaque point $(x,y)$ dans le disque $x^2+y^2\leq R^2$ (notez que ce disque est contenu dans la section $S^z_0$), on peut associer deux valeurs de $z$ : $z_1=\sqrt{R^2-x^2-y^2}$ et $z_2=-\sqrt{R^2-x^2-y^2}$. Par définition, une fonction n'associe qu'un seul valeur à chaque point de son domaine, d'où l'impossibilité de décrire cette sphère comme le graphe d'une fonction de $x$ et $y$. \end{description} \end{example} Considérons la fonction $Sp: \eR^3\to \eR$ qui associe à $(x,y,z)$ la valeur $x^2+y^2+z^2$. La sphère de rayon $R$ centrée en l'origine est l'ensemble de niveau $N_{R^2}$ de $Sp$. L'ensemble de niveau $N_{0}$ de $Sp$ est l'origine, et tous les ensembles de niveau de hauteur négative sont vides. La même chose est vraie pour les ellipsoïdes centrées en l'origine avec les axes $x$, $y$ et $z$ comme axes principaux et comme longueurs de demi-axes $a$, $b$ et $c$. Voici la fonction dont il sont les ensembles de niveau \[ El(x,y,z)= \frac{x^2}{a^2}+\frac{y^2}{b^2}+\frac{z^2}{c^2}. \] \begin{example} Des ensembles de niveau importants. \begin{description} \item[Tout graphe] Le graphe de toute fonction $f$ de $\eR^2$ dans $\eR$ peut être considéré comme l'ensemble de niveau zéro de la fonction $F(x,y,z)=z-f(x,y)$. \item[Hyperboloïdes] Les hyperboloïdes, comme les ellipsoïdes, sont une famille d'ensemble de niveau. En particulier, nous considérons des hyperboloïdes dont l'axe de symétrie est l'axe des $z$ et qui sont symétriques par rapport un plan $x$-$y$. Une fois que les paramètres $a$, $b$ et $c$ sont fixés la fonction que nous intéresse est \[ Hyp(x,y,z)= \frac{x^2}{a^2}+\frac{y^2}{b^2}-\frac{z^2}{c^2}. \] Les ensembles de niveau $N_d$ pour $d>0$ sont connexes, on les appelle \emph{hyperboloïdes à une feuille}. L'ensemble de niveau $N_0$ est \emph{cône (elliptique)}, les deux moitiés du cône se touchent en l'origine. Enfin, les ensembles de niveau $N_d$ pour $d<0$ ne sont pas connexes et pour cette raison on les appelle \emph{hyperboloïdes à deux feuilles}. \end{description} \end{example} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Graphes de fonctions à plusieurs variables} %--------------------------------------------------------------------------------------------------------------------------- Le \defe{graphe}{graphe!fonction de deux variables} d'une fonction de deux variables $f\colon D\subset\eR^2\to \eR$ est l'ensemble \begin{equation} \Big\{ \big( x,y,f(x,y) \big) \tq (x,y)\in D \Big\}\subset\eR^3. \end{equation} Ce graphe est une surface dans $\eR^3$. \begin{example} \label{ExempleTroisDxxyy} Tracer le graphe de la fonction \begin{equation} (x,y)\mapsto x^2+y^2. \end{equation} Le plus simple est de demander à Sage de nous fournir une représentation 3D \begin{verbatim} ---------------------------------------------------------------------- | Sage Version 4.6.1, Release Date: 2011-01-11 | | Type notebook() for the GUI, and license() for information. | ---------------------------------------------------------------------- sage: f(x,y)=x**2+y**2 sage: plot3d(f,(x,-3,3),(y,-3,3)) \end{verbatim} Voici ce que cela donne\footnote{En vrai, ce que Sage donne est un objet qu'on peut même faire bouger.} : (à regarder avec des lunettes bleues et rouges) : \begin{center} \includegraphics[width=15cm]{pictures_bitmap/coupe.png} \end{center} À part que l'ordinateur l'a dit, est-ce qu'on peut comprendre pourquoi le graphe de la fonction $x^2+y^2$ ressemble à un bol ? En coordonnées cylindriques, le graphe s'écrit \begin{equation} z=r^2. \end{equation} Donc il se fait que plus on s'éloigne du point $(0,0)$ dans le plan $XY$, plus le graphe va monter. Et il monte à quelle vitesse ? Il monte à la vitesse $r^2$. Il s'agit donc de dessiner la fonction $z=r^2$ dans le plan et de la «faire tourner». \end{example} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Courbes de niveau} %--------------------------------------------------------------------------------------------------------------------------- Une technique utile pour se faire une idée de la forme d'une fonction en trois dimensions est de tracer les \defe{courbes de niveau}{courbe de niveau}. La courbe de niveau de hauteur $h$ est la courbe dans le plan donnée par l'équation \begin{equation} f(x,y)=h. \end{equation} \begin{example} Dessinons par exemple les courbes de niveau de la fonction \begin{equation} f(x,y)=x+y+2. \end{equation} La courbe de niveau $h$ est donnée par l'équation $x+y+2=h$, c'est-à-dire \begin{equation} y(x)=-x+h-2. \end{equation} Par conséquent la courbe de niveau de hauteur $0$ est $y=-x-2$, celle de hauteur $5$ est $y=-x+3$, etc. Nous pouvons également nous aider de Sage pour ce faire : \begin{verbatim} ---------------------------------------------------------------------- | Sage Version 4.6.1, Release Date: 2011-01-11 | | Type notebook() for the GUI, and license() for information. | ---------------------------------------------------------------------- sage: f(x,y)=x+y+2 sage: var('h') h sage: niveau(h,x)=solve(f(x,y)==h,y)[0].rhs() sage: g1(x)=niveau(1,x) sage: g1 x |--> -x - 1 \end{verbatim} Ici la fonction \verb+g1+ est la courbe de niveau $1$. Si on veut faire tracer une courbe de niveau, Sage peut le faire : \begin{verbatim} sage: implicit_plot(f(x,y)==1,(x,-3,3),(y,-4,4)) \end{verbatim} Cela tracera la courbe de niveau $h=1$ dans la partie du plan $x\in\mathopen[ -3 , 3 \mathclose]$ et $y\in\mathopen[ -4,4 , \mathclose]$. \end{example} Il est bien entendu possible de créer automatiquement $50$ courbes de niveau et de demander de les tracer toutes sur le même graphe. \lstinputlisting{tex/frido/courbeNiveau.py} Le résultat est : \begin{center} \includegraphics[width=8cm]{pictures_bitmap/niveauCercles.png} \end{center} Notez que les courbes sont censées être des cercles : les axes $X$ et $Y$ n'ont pas la même échelle. \begin{example} Un exemple plus riche en enseignements est celui de la fonction \begin{equation} f(x,y)=x^2-y^2. \end{equation} La courbe de niveau $h$ est donnée par l'équation $x^2-y^2=h$. Commençons par $h=0$. Dans ce cas nous avons $(x+y)(x-y)=0$ et par conséquent les courbes de niveau de hauteur zéro sont les deux droites $x+y=0$ et $x-y=0$. Voyons ensuite la courbe de niveau $h=1$. Cela est l'équation $x^2-y^2=1$, c'est-à-dire \begin{equation} y(x)=\pm\sqrt{x^2-1}. \end{equation} C'est une fonction qui n'est définie que pour $| x |\geq 1$. Avec $x=1$ nous avons $y=1$. Ensuite, lorsque $x$ grandit, $y$ grandit également, mais la courbe ne peut pas croiser la courbe de niveau $h=0$. Donc, suivant les notations de la figure~\ref{LabelFigCQIXooBEDnfK}, la courbe de niveau «part» de $P$ et doit monter sans croiser les diagonales. % les figures CQIXooBEDnfK et KGQXooZFNVnW sont générées par le script MBFDooRFPyNW %The result is on figure~\ref{LabelFigCQIXooBEDnfK}. % From file CQIXooBEDnfK \newcommand{\CaptionFigCQIXooBEDnfK}{La courbe de niveau $h=1$ de $x^2-y^2$. Notez qu'elle est en deux morceaux.} \input{auto/pictures_tex/Fig_CQIXooBEDnfK.pstricks} %The result is on figure~\ref{LabelFigKGQXooZFNVnW}. % From file KGQXooZFNVnW \newcommand{\CaptionFigKGQXooZFNVnW}{La courbe de niveau $x^2-y^2=-1$.} \input{auto/pictures_tex/Fig_KGQXooZFNVnW.pstricks} En ce qui concerne la courbe de niveau $h=-1$, elle correspond à la courbe $y=\pm\sqrt{1+x^2}$ qui est définie pour tous les $x\in\eR$. Le même raisonnement que précédemment nous amène à la figure~\ref{LabelFigKGQXooZFNVnW}. \end{example} Une autre façon de voir les courbes de niveau est de dire que la courbe de niveau de hauteur $h$ est la projection dans le plan $XY$ de la section du graphe de $f$ par le plan $z=h$. On peut également définir le graphe de fonctions de trois (ou plus) variables. Le graphe de la fonction $f\colon D\subset\eR^3\to \eR$ est l'ensemble \begin{equation} \big\{ \big( x,y,z,f(x,y,z) \big)\tq (x,y,z)\in D \big\}\subset \eR^4. \end{equation} De tels graphes ne peuvent pas être représentés sur une feuille de papier. Il est toutefois possible de définir les ensembles de niveaux : \begin{equation} E_h=\big\{ (x,y,z)\in D\tq f(x,y,z)=h\big\}. \end{equation} Ce sont des surfaces dans $\eR^3$ que l'on peut dessiner. \begin{example} Les surfaces de niveau de la fonction $f(x,y,z)=x^2+y^2+z^2$ sont des sphères. Il n'y a pas de surfaces de niveau pour les «hauteurs» négatives. \end{example} \begin{example} Considérons la fonction $f(x,y,z)=x^2+y^2-z^2$. En coordonnées cylindriques, cette fonction s'écrit \begin{equation} f(r,\theta,z)=r^2-z^2. \end{equation} La surface de niveau $0$ est donnée par l'équation $r=| z |$. Cela fait un cercle à chaque hauteur, dont le rayon grandit linéairement avec la hauteur; le tout est donc un cône. C'est d'ailleurs le cône obtenu par rotation de la courbe de niveau $h=0$ que nous avions obtenu pour la fonction $x^2-y^2$. En ce qui concerne les ensembles de niveau positifs, ils sont donnés par \begin{equation} z=\pm\sqrt{x^2+y^2-h}. \end{equation} Notez qu'ils ne sont pas définis pour $r\geq h$. Cela pose un petit problème quand on veut le tracer à l'ordinateur : \begin{verbatim} ---------------------------------------------------------------------- | Sage Version 4.6.1, Release Date: 2011-01-11 | | Type notebook() for the GUI, and license() for information. | ---------------------------------------------------------------------- sage: var('x,y') (x, y) sage: f(x,y)=sqrt(x**2+y**2-3) sage: F=plot3d(f(x,y),(x,-5,5),(y,-5,5)) sage: G=plot3d(-f(x,y),(x,-5,5),(y,-5,5)) sage: F+G \end{verbatim} Le résultat est\footnote{Encore une fois : ça donne mieux à l'écran, et vous pouvez le faire bouger; je vous encourage à le faire !} : \begin{center} \includegraphics[width=15cm]{pictures_bitmap/AdSmauvais.png} \end{center} On voit qu'il y a un grand trou au centre correspondant aux $z$ proches de zéro. Or d'après l'équation, il n'en est rien : en $z=0$ il y a bel et bien tout un cercle. Afin d'obtenir une meilleur image, il faut demander de tracer avec un maillage plus fin : \begin{verbatim} ---------------------------------------------------------------------- | Sage Version 4.6.1, Release Date: 2011-01-11 | | Type notebook() for the GUI, and license() for information. | ---------------------------------------------------------------------- sage: var('x,y') (x, y) sage: f(x,y)=sqrt(x**2+y**2-3) sage: F=plot3d(f(x,y),(x,-5,5),(y,-5,5),plot_points=300) sage: G=plot3d(-f(x,y),(x,-5,5),(y,-5,5),plot_points=300) sage: F+G \end{verbatim} Le temps de calcul est un peu plus long, mais le résultat est meilleur : \begin{center} \includegraphics[width=15cm]{pictures_bitmap/AdSbon.png} \end{center} \end{example} %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ %\section{Calcul de limites} %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ %Incidemment, le lemme~\ref{Def_diff2} nous donne une nouvelle technique pour calculer des limites à plusieurs variables, similaire à celle du développement asymptotique expliquée dans la section~\ref{SecTaylorR}. %En effet, la formule \eqref{def_diff2} nous permet d'écrire $f(x)$ sous la forme %\begin{equation} % f(x)=f(a)+df(a).(x-a)+\sigma_f(a,x)\| x-a \| %\end{equation} %où la fonction $\sigma_f$ satisfait $\lim_{x\to a}\sigma_f(a,x)=0$. Ici, $x$ et $a$ sont des éléments de $\eR^m$. %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \section{Limites à plusieurs variables} %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \label{SecLimVarsPlus} Prenons une fonction $f\colon \eR^n\to \eR$. Nous disons que \begin{equation} \lim_{x\to x_0}f(x)=l\in\eR \end{equation} lorsque $\forall \epsilon>0$, $\exists\delta$ tel que $\| x-x_0 \|\leq\delta$ implique $| f(x)-l |\leq \epsilon$. Remarquez qu'ici, $x\in\eR^n$, et sachez distinguer $\| . \|$, la norme dans $\eR^n$ de $| . |$ qui est la valeur absolue dans $\eR$. Une autre façon d'exprimer cette définition est que l'ensemble des valeurs atteintes par $f$ dans une boule de rayon $\delta$ autour de $x_0$ n'est pas très loin de $l$. Nous définissons donc \begin{equation} E_{\delta}=\{ f(x)\tq x\in B(x_0,\delta) \}. \end{equation} Notez que si $f$ n'est pas définie en $x_0$, il n'y a pas de valeurs correspondantes au centre de la boule dans $E_{\delta}$. Ceci est évidemment la situation générique lorsqu'il y a une indétermination à lever dans le calcul de la limite. Nous avons alors que \begin{equation} \lim_{x\to x_0}f(x)=l \end{equation} lorsque $\forall\epsilon>0$, $\exists\delta$ tel que \begin{equation} \label{Eqvmoinsrapplimdeux} \sup\{ | v-l |\tq v\in E_{\delta} \}\leq\epsilon. \end{equation} Une façon classique de montrer qu'une limite n'existe pas, est de prouver que, pour tout $\delta$, l'ensemble $E_{\delta}$ contient deux valeurs constantes. Si par exemple $0\in E_{\delta}$ et $1\in E_{\delta}$ pour tout $\delta$, alors aucune valeur de $l$ (même pas $l=\pm\infty$) ne peut satisfaire à la condition \eqref{Eqvmoinsrapplimdeux} pour toute valeur de $\epsilon$. Nous laissons à la sagacité de l'étudiant le soin d'adapter tout ceci pour le cas $\lim_{x\to x_0}f(x)=\pm\infty$. La proposition suivante semble évidente, mais nous sera tellement utile qu'il est préférable de l'expliciter~: \begin{proposition} \label{PROPooPOAQooPmxEtb} Soient $f : D \to \eR$ une fonction de domaine \( D\), \( a\in\Adh(D)\) et un voisinage \( V\) de \( a\). Nous supposons que \( V\cap D\) s'écrive comme une intersection finie : \begin{equation*} V\cap D = \bigcup_{i=1}^k A_i \end{equation*} telle que $a \in \Adh A_i$ pour tout $i \leq k$. Alors, la limite \begin{equation} \label{EQooEXELooHccCGw} \limite x a f(x) \end{equation} existe et vaut $b\in \eR$ si et seulement si chacune des limites \begin{equation} \limite[x \in A_i] x a f(x) \end{equation} existe et vaut $b$. \end{proposition} \begin{proof}On sait déjà que si la limite de $f : D \to \eR$ existe, alors toute restriction à $A_i$ admet la même limite\footnote{C'est une conséquence de la caractérisation séquentielle de la continuité \ref{fContEstSeqCont}.}. Il suffit donc de prouver la réciproque. Fixons provisoirement un entier \( i\) entre \( 1\) et \( k\) ainsi que \( \epsilon>0\). Vu que \( \lim_{\substack{x\to a\\x\in A_i}} f(x)=b\), il existe \( \delta_i>0\) tel que si \( x\in A_i\) et si \( 0<| x-a |<\delta_i\), alors \begin{equation} \label{EQooUCAIooRpUgnE} | f(x)-f(a) |<\epsilon. \end{equation} Quitte à prendre \( \delta_i\) un peu plus petit, nous supposons que \( V\subset B(a,\delta_i)\). Nous posons $\delta = \min\{\delta_i\}_{i=1,\ldots, k}$, et nous considérons \( x\in D\) tel que \( 0<| x-a |<\delta\). Nous avons alors \begin{enumerate} \item \( x\in V\cap D\), \item il existe \( i\) tel que \( x\in A_i\). \end{enumerate} Ce \( x\) est donc un élément de \( A_i\) vérifiant \( 0<| x-a |<\delta\leq \delta_i\). Il vérifie donc \eqref{EQooUCAIooRpUgnE} : \( | f(x)-f(a) |<\epsilon\). Cela prouve la limite \eqref{EQooEXELooHccCGw}. \end{proof} \begin{example} \begin{enumerate} \item Pour qu'une fonction $f : \eR \to \eR$ admette une limite en $a \in \eR$, il faut et il suffit qu'elle y admette une limite à droite et une limite à gauche qui soient égales. Cela est une application de la proposition \ref{PROPooPOAQooPmxEtb} avec \( \eR=\mathopen] -\infty , a \mathclose[\cup\mathopen] a , \infty \mathclose[\). \item Une suite $(x_k)$ admet une limite si et seulement si les sous-suites $(x_{2k})$ et $(x_{2k+1})$ convergent vers la même limite. Ceci n'est pas une application directe de la proposition, mais la teneur est la même. \end{enumerate} \end{example} \begin{lemma}[\cite{MonCerveau}] Soient deux espaces vectoriels \( E\) et \( F\). Soit une fonction \( f\colon \eR\to F\) telle que \( \lim_{t\to 0} f(t)=y\in F\). Nous posons \begin{equation} \begin{aligned} \varphi\colon E & \to F \\ h & \mapsto f(\| h \|). \end{aligned} \end{equation} Alors \( \varphi\) admet une limite pour \( h\to 0\) et elle est donnée par \begin{equation} \lim_{h\to 0} \varphi(h)=\lim_{t\to 0} f(t). \end{equation} \end{lemma} \begin{proof} Soit \( \epsilon>0\). Il existe \( \delta\) tel que si \( t<\delta\) alors \( \| f(t)-y \|_F<\epsilon\). Si \( \| h \|<\delta\) nous avons \begin{equation} \| \varphi(h)-y \|=\| f(\| h \|)-y \|<\epsilon. \end{equation} Donc c'est bon. \end{proof} Voici, dans le même ordre d'idée, un autre résultat qui permet de réduire le nombre de variables dans une limite lorsque la fonction ne dépend pas de certaines variables. \begin{lemma}[\cite{MonCerveau}] \label{LEMooYLIHooFBQyzC} Soit une fonction \( g\colon \eR\to \eR\) vérifiant \begin{equation} \lim_{t\to a} g(t)=\ell. \end{equation} Alors la fonction \begin{equation} \begin{aligned} f\colon \eR^2 & \to \eR \\ (x,y) & \mapsto g(x) \end{aligned} \end{equation} vérifie \begin{equation} \lim_{\substack{(x,y)\to(a,b)\\x\neq a}} f(x,y)=\ell. \end{equation} \end{lemma} \begin{proof} Soit \( \epsilon>0\). Par hypothèse sur la limite de \( g\) en \( a\), il existe \( \delta>0\) tel que \( 0<| t-a |<\delta\) implique \( | g(t)-\ell |<\epsilon\). Attention : passage subtil\footnote{Je rejette déjà en bloc et d'un revers de main toute tentative de dire «la limite épointée, c'est mieux». Voir aussi l'exemple \ref{EXooHSYNooBZhDbE}.}. Si \( 0<\| (x,y)-(a,b) \|<\delta\), alors nous avons évidemment aussi \( | x-a |<\delta\), mais pas spécialement \( 0<| x-a |<\delta\) comme le requis pour utiliser la limite de \( g\). Dans le calcul de la limite restreinte à \( x\neq a\), les points qui interviennent sont les valeurs de \( (x,y)\) dans \( B\big( (a,b),\delta \big)\setminus\{ x=a \}\). Or pour celles-là nous avons bien \( 0<| x-a |<\delta\). Le calcul suivant fonctionne donc : \begin{equation} | f(x,y)-\ell |=| g(x)-\ell |<\epsilon. \end{equation} \end{proof} \begin{example} \label{EXooHSYNooBZhDbE} Pourquoi prendre la limite \( (x,y)\to (a,b)\) avec \( x\neq a\) dans l'énoncé du lemme \ref{LEMooYLIHooFBQyzC} ? Imaginons la fonction \begin{equation} g(x)=\begin{cases} 0 & \text{si } x\neq 0 \\ 1 & \text{si } x=0. \end{cases} \end{equation} Dans ce cas, le graphe de la fonction \( f(x,y)=g(x)\) est tout plat sauf la ligne \( x=0\) qui est en hauteur. Nous avons donc \( f(0,t)=1\) pour tout \( t\) et donc nous n'avons pas \( \lim_{(x,y)\to (0,0)} f(x,y)=0\) : tout voisinage de \( (0,0)\) contient des points \( (x,y)\) tels que \( f(x,y)=1\) et des points \( (x,y)\) tels que \( f(x,y)=0\). \end{example} Il existe de nombreuses façons de calculer des limites à plusieurs variables. Plus nous connaîtrons de mathématiques, plus nous aurons de techniques à notre disposition. Nous allons tout de suite voir quelques méthodes. Voir le thème~\ref{THEMEooLTCIooGDIPnF} pour plus de techniques et d'exemples. %--------------------------------------------------------------------------------------------------------------------------- \subsection{Caractérisation de la limite par les suites} %--------------------------------------------------------------------------------------------------------------------------- \begin{example} \label{ExFNExempleMethodeTrigigi} Considérons la fonction \begin{equation} f(x,y)=\frac{ xy }{ x^2+y^2 }, \end{equation} et remarquons que, quelle que soit la valeur de $y$, cette fonction est nulle lorsque $x=0$. De la même manière, nous voyons que si $x=y$, alors la fonction vaut\footnote{En fait ce que nous sommes en train de faire est de poser $\theta=\pi/2$ et $\theta=\pi/4$ dans \eqref{Eq2807fpolairerhodeuxcossin}.} $\frac{ 1 }{2}$. Il est impossible que la fonction ait une limite en $(0,0)$ parce qu'on ne peut pas trouver un $\ell$ dont on s'approche à la fois en suivant la ligne $x=0$ et la ligne $x=y$. Deux autres chemins avec encore deux autres valeurs sont dessinés sur la figure~\ref{LabelFigMethodeChemin}. Cet exemple pourra être formalisé en utilisant le théorème~\ref{ThoLimSuite}. Voir l'exemple~\ref{EXooNBTYooFyKRTB}. \end{example} \begin{theorem}[Caractérisation de la limite par les suites] \label{ThoLimSuite} Une fonction $f\colon D\subset\eR^m\to \eR^n$ admet une limite $\ell$ en un point d'accumulation $a$ de $D$ si et seulement si pour toute suite $(x_n)$ dans $D\setminus\{ a \}$ convergente vers $a$, la suite $\big( f(x_n) \big)$ dans $\eR^n$ converge vers $\ell$. \end{theorem} \begin{proof} Supposons d'abord que la fonction ait une limite $\ell$ lorsque $x\to a$, et considérons une suite $(x_n)$ dans $D\setminus\{ a \}$ convergente vers $a$. Nous devons montrer que la suite $y_n=f(x_n)$ converge vers $\ell$, c'est-à-dire que si nous choisissons $\varepsilon>0$ nous devons montrer qu'il existe un $N$ tel que $n>N$ implique $\| y_n-\ell \|=\| f(x_n)-\ell \|<\varepsilon$. Nous avons deux hypothèses. La première est la convergence de la fonction et la seconde est la convergence de la suite $(x_n)$. L'hypothèse de convergence de la fonction nous dit que (le $\varepsilon$ a déjà été choisi dans le paragraphe précédent) \begin{equation} \exists\delta\tq\,0<\| x-a \|<\delta\Rightarrow\| f(x)-\ell \|<\varepsilon. \end{equation} Une fois choisi ce $\delta$ qui «va avec» le $\varepsilon$ qui a été choisi précédemment, la définition de la convergence de la suite nous enseigne que \begin{equation} \exists N\tq n>N\Rightarrow\| x_n-a \|<\delta. \end{equation} Récapitulons ce que nous avons fait. Nous avons choisi un $\varepsilon$, et puis nous avons construit un $N$. Lorsque $n>N$, nous avons $\| x_n-a \|<\delta$. Mais alors, par construction de ce $\delta$, nous avons $\| f(x_n)-\ell \|<\varepsilon$. Au final, $n>N$ implique bien $\| y_n-\ell \|<\varepsilon$, ce qu'il nous fallait. Nous supposons maintenant que la fonction $f$ \emph{ne} converge \emph{pas} vers $\ell$, et nous allons construire une suite d'éléments $x_n$ qui converge vers $a$ sans que $(y_n)=f(x_n)$ ne converge vers $\ell$. La fonction $f$ vérifie la condition \eqref{EqCaractNonLim}. Nous prenons donc un $\varepsilon$ tel que $\forall \delta$, il existe un $x$ qui vérifie \emph{en même temps} les deux conditions \begin{subequations} \begin{numcases}{} 0<\| x-a \|<\delta\\ \| f(x)-\ell \|>\varepsilon. \end{numcases} \end{subequations} Un tel $x$ existe pour tout choix de $\delta$. Choisissons un $n$ arbitraire et $\delta=\frac{1}{ n }$. Nous nommons $x_n$ le $x$ correspondant à ce choix de $n$. La suite $(x_n)$ ainsi construite converge vers $a$ parce que \begin{equation} \| x_n-a \|<\delta_n=\frac{1}{ n }, \end{equation} donc dès que $n$ est grand, $\| x_n-a \|$ est petit. Mais la suite $y_n=f(x_n)$ ne converge pas vers $\ell$ parce que \begin{equation} \| f(x_n)-\ell \|>\varepsilon \end{equation} pour tout $n$. La suite $y_n$ ne s'approche donc jamais à moins d'une distance $\varepsilon$ de $\ell$. \end{proof} \begin{example} \label{EXooNBTYooFyKRTB} Reprenons l'exemple \ref{ExFNExempleMethodeTrigigi}. Considérons les deux suites $x_n=(0,\frac{1}{ n })$ et $y_n=(\frac{1}{ n },\frac{1}{ n })$. Ce sont deux suites dans $\eR^2$ qui tendent vers $(0,0)$. Si la fonction $f$ convergeait vers $\ell$, alors nous aurions au moins \begin{subequations}\label{Eq3007Lixxyyell} \begin{align} \lim f(x_n) & =\ell \\ \lim f(y_n) & =\ell, \end{align} \end{subequations} mais nous savons que pour tout $n$, $f(x_n)=f(0,\frac{1}{ n })=0$ et $f(y_n)=f(\frac{1}{ n },\frac{1}{ n })=\frac{1}{ 2 }$. Il n'y a donc aucun nombre $\ell$ qui vérifie les deux équations \eqref{Eq3007Lixxyyell} parce que $\lim f(x_n)=0$ et $\lim f(y_n)=\frac{ 1 }{2}$. \end{example} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Règle de l'étau} %--------------------------------------------------------------------------------------------------------------------------- Une première façon de calculer la limite d'une fonction est de la «coincer» entre deux fonctions dont nous connaissons la limite. \begin{theorem}[Règle de l'étau\cite{BIBooNKECooNNYQvB}] \label{ThoRegleEtau} Soit $\mO$, un ouvert de $\eR^m$ contenant le point $a$. Soient $f$, $g$ et $h$, trois fonctions définies sur $\mO$ (éventuellement pas en $a$ lui-même). Supposons que pour tout $x\in\mO$ (à part éventuellement $a$), nous ayons les inégalités \begin{equation} g(x)\leq f(x)\leq h(x). \end{equation} Supposons de plus que \begin{equation} \lim_{x\to a} g(x)=\lim_{x\to a} h(x)=\ell. \end{equation} Alors la limite $\lim_{x\to a} f(x)$ existe et vaut $\ell$. \end{theorem} Nous insistons sur le fait que les deux fonctions entre lesquelles nous coinçons $f$ doivent tendre vers \emph{la même} valeur. Cette méthode est très pratique lorsqu'on a des fonctions trigonométriques qui se factorisent parce qu'elles sont toujours majorables par $1$; voir l'exemple~\ref{EXooSPFDooSluUGV}. \begin{example} Prouver la continuité en $(0,0)$ de la fonction \begin{equation} f(x,y)=\begin{cases} \frac{ x | y | }{ \sqrt{x^2+y^2} } & \text{si }(x,y)\neq (0,0) \\ 0 & \text{sinon.} \end{cases} \end{equation} Considérons une suite $(x_n,y_n)\in\eR^2$ qui tend vers $(0,0)$. Étant donné que $\frac{ | y | }{ \sqrt{x^2+y^2} }<1$ pour tout $x$ et $y$, nous avons \begin{equation} 0\leq | f(x_n,y_n) |=\left| \frac{ x_n | y_n | }{ \sqrt{x_n^2+y_n^2} } \right| \leq | x_n |\to 0. \end{equation} Donc nous avons \begin{equation} \lim_{(x,y)\to(0,0)}f(x,y)=0=f(0,0), \end{equation} ce qui prouve que la fonction est continue en $(0,0)$ par la proposition~\ref{PropFnContParSuite}. Nous avons utilisé la règle de l'étau (théorème~\ref{ThoRegleEtau}). \end{example} \begin{normaltext} Nous notons \( f\sim g\)\nomenclature[Y]{\( f\sim g\)}{fonctions ayant des limites équivalentes} pour \( x\to a\) lorsque \( \lim_{x\to a} \frac{ f(x) }{ g(x) }=1\). Cela signifie que \( f\) et \( g\) tendent vers la même limite, à la même vitesse. \end{normaltext} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Méthode des chemins} %--------------------------------------------------------------------------------------------------------------------------- Lorsque la limite n'existe pas, il y a une façon en général assez simple de le savoir, c'est la \defe{méthode des chemins}{méthode!des chemins}. \newcommand{\CaptionFigMethodeChemin}{Sur toute la droite $y=-x$, la fonction vaut $-1/2$, tandis que sur toute la droite $y=x/2$, elle vaut $\frac{2}{ 5 }$. Il est donc impossible que la fonction ait une limite en $(0,0)$, parce que dans toute boule autour de zéro, il y aura toujours un point de chacune de ces deux droites.} \input{auto/pictures_tex/Fig_MethodeChemin.pstricks} C'est la proposition suivante qui va faire une grosse partie du travail. \begin{proposition}[\cite{MonCerveau}] \label{PROPooSAFIooWvmSiT} Soit $f\colon D\subset\eR^m\to \eR^n$ et $a$ un point d'adhérence de $D$. Alors nous avons \begin{equation} \lim_{x\to a} f(x)=\ell \end{equation} si et seulement si pour toute fonction $\gamma\colon \eR\to \eR^m$ telle que $\lim_{t\to 0} \gamma(t)=a$, nous avons \begin{equation} \lim_{t\to 0} (f\circ\gamma)(t)=\ell. \end{equation} \end{proposition} \begin{proof} En deux parties. \begin{subproof} \item[Sens direct] Soit une fonction \( \gamma\colon \eR\to \eR^m\) telles que \( \lim_{t\to 0} \gamma(t)=a\). Par le théorème \ref{ThoLimSuite}, il suffit de montrer que \( (f\circ\gamma)(t_n)\to\ell\) pour toute suite \( t_n\to 0\) dans \( \eR\). Nous savons que la suite \( n\mapsto \gamma(t_n)\) est une suite qui converge vers \( a\). Mais l'hypothèse \( \lim_{x\to a} f(x)=\ell\) implique que pour toute suite \( x_n\to a\) nous avons \( f(x_n)\to \ell\). Cela est en particulier vrai pour la suite \( n\mapsto \gamma(t_n)\). Donc : \begin{equation} \lim_{n\to \infty} f\big( \gamma(t_n) \big)=\ell, \end{equation} ce qu'il fallait prouver. \item[Réciproque] Pour les mêmes raisons de caractérisation séquentielle que précédemment, il faut prouver que \( \lim_{n\to \infty} f(x_n)=\ell\) pour tout suite \( x_n\to a\). \begin{subproof} \item[Un chemin] Soit la fonction \( \gamma\colon \eR\to \eR^m\) affine par morceaux et telle que \begin{equation} \gamma\left( \frac{1}{ n } \right)=x_n. \end{equation} Nous prolongeons \( \gamma\) par \( \gamma(t)=a\) pour \( t\leq 0\). \item[\( \gamma(t)\to a\)] Nous montrons que \( \lim_{t\to 0} \gamma(t)=a\). Soient \( \epsilon>0\) et \( N\) tel que \( x_n\in B(a,\epsilon)\) pour tout \( n\geq N\). Si \( t<\frac{1}{ N }\) alors \( t\in\mathopen[ \frac{1}{ k+1 } , \frac{1}{ k } \mathclose]\) pour un certain \( k>N\). Donc \begin{equation} \gamma(t)\in\mathopen[ \gamma(\frac{1}{ k+1 }) , \gamma(\frac{1}{ k }) \mathclose] \end{equation} et donc \( \gamma(t)\in\mathopen[ x_{k+1} , x_k \mathclose]\) parce que \( \gamma\) est formé de ces segments de droites. Mais comme \( B(a,\epsilon)\) est convexe\footnote{C'est la proposition \ref{PROPooUQLUooDQfYLT}.}, nous avons \begin{equation} \gamma(t)\in\mathopen[ x_{k+1} , x_k \mathclose]\subset B(a,\epsilon). \end{equation} Nous avons donc bien \( \lim_{t\to 0} \gamma(t)=a\). \item[Conclusion] L'hypothèse nous donne alors \( \lim_{t\to 0} (f\circ \gamma)(t)=\ell\). En particulier le critère de la caractérisation séquentielle de la limite dit que \begin{equation} \lim_{n\to \infty} f\big( \gamma(\frac{1}{ n }) \big)=\ell, \end{equation} ce qui signifie \( \lim_{n\to \infty} f(x_n)=\ell\). \end{subproof} \end{subproof} \end{proof} \begin{corollary} \label{CorMethodeChemin} Soient $f\colon D\subset\eR^m\to \eR^n$ et $a$ un point d'accumulation de $D$. Si nous avons deux fonctions $\gamma_1,\gamma_2\colon \eR\to \eR^m$ telles que \begin{equation} \lim_{t\to 0} \gamma_1(t)=\lim_{t\to 0} \gamma_2(t)=a \end{equation} tandis que \begin{equation} \lim_{t\to 0} (f\circ \gamma_1)(t)\neq\lim_{t\to 0} (f\circ \gamma_2)(t), \end{equation} ou bien que l'une des deux limites n'existe pas, alors la limite de $f(x)$ lorsque $x\to a$ n'existe pas. \end{corollary} \begin{corollary} \label{CorMethodeChemoinNegatif} Soient $f\colon D\subset\eR^m\to \eR^n$ et $a$ un point d'accumulation de $D$. Si il existe une fonction $\gamma\colon \eR\to \eR^m$ avec $\gamma(0)=a$ telle que la limite $\lim_{t\to 0} (f\circ\gamma)(t)$ n'existe pas, alors la limite $\lim_{x\to a} f(x)$ n'existe pas. \end{corollary} En ce qui concerne le calcul de limites, la méthode des chemins peut être utilisé de trois façons : \begin{enumerate} \item Dès que l'on trouve une fonction $\gamma\colon \eR\to \eR^m$ telle que $\lim_{t\to 0} (f\circ \gamma)(t)=\ell$, alors nous savons que \emph{si la limite $\lim_{x\to a} f(x)$ existe}, alors cette limite vaut $\ell$. \item Dès que l'on a trouvé deux fonctions $\gamma_i$ qui tendent vers $a$, mais dont les limites de $\lim_{t\to 0} (f\circ\gamma_i)(t)$ sont différentes, alors la limite $\lim_{x\to a} f(x)$ n'existe pas. \item Dès qu'on trouve une chemin le long duquel il n'y a pas de limite, alors la limite n'existe pas (corolaire~\ref{CorMethodeChemoinNegatif}). \end{enumerate} La méthode des chemins ne permet donc pas de de calculer une limite quand elle existe. Elle permet uniquement de la «deviner», ou bien de prouver que la limite n'existe pas. \begin{example} Soit à calculer \begin{equation} \label{Eq3007ExempleLimiche} \lim_{(x,y)\to(0,0)}\frac{ x-y }{ x+y }. \end{equation} Si nous prenons le chemin $\gamma_1(t)=(t,t)$, nous avons bien $\lim_{t\to 0} \gamma_1(t)=(0,0)$, et nous avons \begin{equation} \lim_{t\to 0} (f\circ\gamma_1)(t)=\lim_{t\to 0} \frac{ t-t }{ t+t }=0. \end{equation} Donc si la limite \eqref{Eq3007ExempleLimiche} existait, elle vaudrait obligatoirement $0$. Mais si nous considérons $\gamma_2(t)=(0,t)$, nous avons \begin{equation} (f\circ\gamma_2)(t)=\frac{ -t }{ t }=-1, \end{equation} donc si la limite existe, elle doit obligatoirement valoir $-1$. Ne pouvant être égale à $0$ et à $-1$ en même temps, la limite \eqref{Eq3007ExempleLimiche} n'existe pas. \end{example} %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \section{Dérivée directionnelle} %+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Nous sommes capables de dériver une fonction de deux variables $f(x,y)$ par rapport à $x$ et par rapport à $y$. C'est-à-dire que nous sommes capables de donner la variation de la fonction lorsqu'on bouge le long des axes horizontal et vertical. Il est évidemment souhaitable de parler de la variation de la fonction lorsqu'on se déplace le long d'autre droites. Soit donc $u=\begin{pmatrix} u_1 \\ u_2 \end{pmatrix}$ un vecteur unitaire (c'est-à-dire $u_1^2+u_2^2=1$), et considérons la fonction de une variable \begin{equation} \begin{aligned} \varphi\colon \eR & \to \eR \\ t & \mapsto f(a+tu_1,b+tu_2). \end{aligned} \end{equation} La fonction $\varphi$ n'est rien d'autre que la fonction $f$ vue le long de la droite de direction donnée par le vecteur $u$. Nous pouvons aussi l'écrire $\varphi(t)=f(p+tu)$. Soit $f\colon \eR^2\to \eR$ une fonction de deux variables et soit $(a,b)\in\eR^2$. La façon la plus naturelle de définir une dérivée à deux variables est de considérer les \defe{dérivées partielles}{dérivée!partielle} définies par \begin{equation} \begin{aligned}[] \frac{ \partial f }{ \partial x }(a,b) & =\lim_{x\to a} \frac{ f(x,b)-f(a,b) }{ x-a } \\ \frac{ \partial f }{ \partial y }(a,b) & =\lim_{y\to b} \frac{ f(a,y)-f(a,b) }{y-b}. \end{aligned} \end{equation} Ces nombres représentent la façon dont le nombre $f(x,y)$ varie lorsque soit seul $x$ varie soit seul $y$ varie. Les dérivées partielles se calculent de la même façon que les dérivées normales. Pour calculer $\partial_xf$, on fait «comme si» $y$ était une constante, et pour calculer $\partial_yf$, on fait comme si $x$ était une constante. %--------------------------------------------------------------------------------------------------------------------------- \subsection{Dérivée partielle et directionnelles} %--------------------------------------------------------------------------------------------------------------------------- Soit une fonction $f:A\subset \mathbb{R}^n \rightarrow \mathbb{R}^m$. Si $n\neq 1$, la notion de \emph{dérivée} de la fonction $f$ n'a plus de sens puisqu'on ne peut plus parler de pente de \emph{la} tangente au graphe de $f$ en un point. On introduit alors quelques notions qui feront, en dimension quelconque, le même travail que la dérivée en dimension un : les dérivées directionnelles et la différentielle. Nous allons voir qu'en dimension un, la différentielle coïncide avec la dérivée. \begin{definition} \label{DEFooCATTooTPLtpR} Soit une fonction \( f\colon V\to W\) où \( V\) et \( W\) sont des espaces vectoriels normés. Soient \( a\in V\) et \( v\in V\). Nous posons \( \varphi\colon \eR\to W\) donnée par \begin{equation} \varphi(t)=f(a+tv). \end{equation} Nous disons que $f$ admet une \defe{dérivée suivant le vecteur $v$ au point $a$}{dérivée!directionnelle} si la fonction \( \varphi\) est dérivable en \( a\). Nous notons alors \begin{equation} \frac{ \partial f }{ \partial v }(a)=\varphi'(a), \end{equation} ou alors \begin{equation} \partial_v f(a)=\lim_{ \begin{subarray}{l} t\to 0\\ t\neq 0 \end{subarray} }\frac{f(a+tv)-f(a)}{t}. \end{equation} Si une base \( \{ e_i \}\) de \( V\) est donnée, nous notons \( \partial_if\) la dérivée de \( f\) dans la direction de \( e_i\). La fonction \( \partial_if\) est la \defe{dérivée partielle}{dérivée partielle} de \( f\). Dans le cas de \( V=\eR^n\), cela est souvent noté \begin{equation} \frac{ \partial f }{ \partial x_i }(a)=\Dsdd{ f(a+ te_i) }{t}{0}. \end{equation} \end{definition} Si $m=2,3$ on peut utiliser la notation $f_x$, $\partial_x$ ou $\partial_1$ pour la dérivée partielle suivant $e_1$, $f_y$, $\partial_y$ ou $\partial_2$ pour la dérivée partielle suivant $e_2$ et $f_z$, $\partial_z$ ou $\partial_3$ pour la dérivée partielle suivant $e_3$. En général, nous écrivons $\partial_i$ pour noter la la dérivée partielle suivant $e_i$. Des exemples faisons intervenir les fonctions trigonométriques, exponentielles et logarithme sont les exemples~\ref{EXooETZYooYsKPDJ},~\ref{EXooGMRIooUucRez}. La fonction d'une seule variable qu'on obtient à partir de $f$ en fixant les $p-1$ variables $x_1,\ldots, x_{i-1}, x_{i+1}, \ldots, x_p$ et qui associe à $x_i$ la valeur $f(x_1,\ldots, x_{i-1}, x_i, x_{i+1}, \ldots, x_p)$, est appelée $x_i$-ème \defe{section}{section} de $f$ en $x_1,\ldots, x_{i-1}, x_{i+1}, \ldots, x_p$. L'$i$-ème dérivée partielle de $f$ au point $a=(x_1,\ldots,x_m)$ est la dérivée de l'$i$-ème section de $f$ au point $x_i$. En pratique, pour calculer les dérivées partielles d'une fonction on fait une dérivation par rapport à la variable choisie en considérant les autres variables comme des constantes. Géométriquement, il s'agit du taux de variation instantané de $f$ en $a$ dans la direction du vecteur $u$, c'est-à-dire de la pente de la tangente dans la direction du vecteur $u$ au graphe de $f$ au point $(a, f(a))$. \begin{remark} De nombreuses sources parlent de de dérivée \defe{dans la direction} du vecteur $v$ en définissant (avec une certaine raison) une \defe{direction}{direction} dans $\eR^m$ comme étant un vecteur de norme $1$. Ces personnes ne définissent alors \( \partial_uf\) que pour \( \| u \|=1\). Pourquoi ? Le but de la dérivée directionnelle dans la direction $u$ est de savoir à quelle vitesse la fonction monte lorsque l'on se déplace en suivant la direction $u$. Cette information n'aura un caractère « objectif » que si l'on avance à une vitesse donnée. En effet, si on se déplace deux fois plus vite, la fonction montera deux fois plus vite. Par convention, on demande alors d'avancer à vitesse \( 1\). Ici, pour être plus souple en termes de notations et de manipulations, nous définissons \( \partial_uf\) pour tout \( u\) (non nul). Nous devons cependant garder en tête que le nombre \( (\partial_vf)(a)\) ne peut pas être interprété comme étant une «vitesse de croissance de \( f\) en \( a\)» de façon trop sérieuse. \end{remark} \subsubsection*{Cas particulier où $n=2$:} $a = (a_1, a_2)$, $u = (u_1,u_2)$ et $$\frac{\partial f}{\partial u}(a_1, a_2) = \lim_{t\rightarrow 0}\frac{f(a_1+tu_1,a_2+tu_2) - f(a_1, a_2)}{t}$$ Un cas particulier des dérivées directionnelles est la dérivée partielle. Si nous considérons la base canonique $e_i$ de $\eR^n$, nous notons \begin{equation} \frac{ \partial f }{ \partial x_i }=\frac{ \partial f }{ \partial e_i }. \end{equation} Dans le cas d'une fonction à deux variables, nous avons donc les deux dérivées partielles \begin{equation} \begin{aligned}[] \frac{ \partial f }{ \partial x }(a) & & \text{et} & & \frac{ \partial f }{ \partial y }(a) \end{aligned} \end{equation} qui correspondent aux dérivées directionnelles dans les directions des axes. Ces deux nombres représentent de combien la fonction $f$ monte lorsqu'on part de $a$ en se déplaçant dans le sens des axes $X$ et $Y$. %/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// \subsubsection{Quelques propriétés et notations} %/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// \begin{enumerate} \item Si on prend $u=e_j$ le $j$ème vecteur de la base canonique de $\mathbb{R}^n$, alors $$\frac{\partial f}{\partial e_j}(a) = \frac{\partial f}{\partial x_j}(a)$$ c'est-à-dire que la dérivée de $f$ au point $a$ dans la direction $e_j$ est la dérivée partielle de $f$ par rapport à sa $j$ème variable. \item Une fonction peut être dérivable dans certaines directions mais pas dans d'autres (rappelez vous que si la limite à droite est différente de la limite à gauche, la limite n'existe pas). \item Même si une fonction est dérivable en un point dans toutes les directions, on n'est pas sûr qu'elle soit continue en ce point. La dérivabilité directionnelle n'est donc pas une notion suffisante pour assurer la continuité. C'est pourquoi on introduit le concept de \emph{différentiabilité}. \end{enumerate} \begin{lemma} \label{LEMooVOTHooPJcrWH} Nous notons \( \eK\) le corps \( \eR\) ou \( \eC\). Soient deux espaces vectoriels \( V\) et \( W\) sur \( K\). Soient une application \( f\colon V\to W\) ainsi que \( a,u\in V\) tels que \( \frac{ \partial f }{ \partial u }(a)\) existe. Alors pour tout \( \lambda\in \eK\), \( (\partial_{\lambda u}f)(a)\) existe et \begin{equation} \frac{ \partial f }{ \partial (\lambda u) }(a)=\lambda\frac{ \partial f }{ \partial u }(a). \end{equation} \end{lemma} \begin{proof} Nous allons utiliser le lemme \ref{LEMooYJGLooVBaglB}. D'abord nous avons, pour tout \( t\), \( \lambda\) et \( a\) : \begin{equation} \label{EQooRDUEooScpIZa} \frac{ f(a+t\lambda u)-f(a) }{ t }=\lambda\frac{ f(a+t\lambda u)-f(a) }{ \lambda t }. \end{equation} En posant \( g(t)=\frac{ f(a+tu)-f(a) }{ t }\) (\( t\) est une variable dans \( \eR\)), l'hypothèse est que \( \lim_{t\to 0} g(t)\) existe et vaut \( \frac{ \partial f }{ \partial u }(a)\). Le lemme \ref{LEMooYJGLooVBaglB} indique que \( \lim_{t\to 0} g(\lambda t)\) existe aussi et vaut la même chose. Donc \begin{equation} \lim_{t\to 0} \frac{ f(a+\lambda tu)-f(a) }{ \lambda t }=\frac{ \partial f }{ \partial u }(a). \end{equation} En prenant la limite dans \eqref{EQooRDUEooScpIZa}, nous avons le résultat. \end{proof} \begin{example} Considérons la fonction $f(x,y)=2xy^2$. Lorsque nous calculons $\partial_xf(x,y)$, nous faisons comme si $y$ était constant. Nous avons donc $\partial_xf(x,y)=2y^2$. Par contre lors du calcul de $\partial_yf(x,y)$, nous prenons $x$ comme une constante. La dérivée de $y^2$ par rapport à $y$ est évidemment $2y$, et par conséquent, $\partial_yf(x,y)=4xy$. \end{example} \begin{definition} Soit $f$ une application de $U\subset\eR^m$ dans $\eR$ et $u$ un vecteur de $\eR^m$. La fonction $f$ est \defe{dérivable sur $U$ suivant le vecteur $u$}{}, si $f$ est dérivable suivant le vecteur $u$ en tout point de $U$. \end{definition} Pour les fonctions d'une seule variable la dérivabilité en un point $a$ implique la continuité en $a$. Cela n'est pas vrai pour les fonctions de plusieurs variables : il existe des fonctions $f$ qui sont dérivables suivant tout vecteur au point $a$ sans pour autant être continue en $a$. \begin{example} Considérons la fonction $f:\eR^2\to \eR$ \begin{equation} f(x,y)=\left\{ \begin{array}{ll} \frac{x^2y}{x^4+y^2} \qquad & \textrm{si } (x,y)\neq (0,0), \\ 0 & \textrm{sinon}. \end{array} \right. \end{equation} Pour voir que $f$ n'est pas continue en $(0,0)$ il suffit de calculer la limite de $f$ restreinte à la parabole $y=x^2$ \[ \lim_{x\to 0} f(x,x^2)=\frac{1}{2} \neq 0. \] Pourtant la fonction $f$ est dérivable en $(0,0)$ dans toutes les directions. En effet, soit $v=(v_1,v_2)$. Si $v_2\neq 0$, alors \[ \partial_v f(a)=\lim_{\begin{subarray}{l} t\to 0\\ t\neq 0 \end{subarray}} \frac{t^3v_1^2v^2}{t^5 v_1^4+ t^3v_2^2}=\frac{v_1^2}{v_2}, \] tandis que si $v_2=0$, alors la valeur de $f(tv_1, 0)$ est $0$ pour tout $t$ et $v_1$, donc la dérivée partielle de $f$ par rapport à $x$ en l'origine existe et est nulle. \end{example} \begin{example} Pour une fonction réelle à variable réelle, la dérivabilité entraine la continuité. Il n'en va pas de même pour les fonctions à plusieurs variables, comme le montre l'exemple suivant : \begin{equation} f(x,y)=\begin{cases} 0 & \text{si } x=0 \\ \frac{ y }{ x }\sqrt{x^2+y^2} & \text{sinon.} \end{cases} \end{equation} Nous avons tout de suite \begin{equation} \frac{ \partial f }{ \partial y }(0,0)=0. \end{equation} De plus si \( u_x\neq 0\) nous avons \begin{equation} \frac{ \partial f }{ \partial u }(0,0)=\frac{ u_y }{ u_x }\| u \|. \end{equation} Donc toutes les dérivées directionnelles de \( f\) en \( (0,0)\) existent alors que la fonction n'y est manifestement pas continue. En effet sous forme polaire, \begin{equation} f(r,\theta)=\frac{ r\sin(\theta) }{ \cos(\theta) }, \end{equation} et quelle que soit la valeur de \( r\), en prenant \( \theta\) suffisamment proche de \( \pi/2\), la fraction peut être arbitrairement grande. Nous verrons par la proposition~\ref{diff1} que la différentiabilité d'une fonction implique sa continuité. \end{example} \begin{theorem}[Accroissement finis pour les dérivées suivant un vecteur]\label{val_medio_1} Soit $U$ un ouvert dans $\eR^m$ et soit $f:U\to\eR^n$ une fonction. Soient $a$ et $b$ deux points distincts dans $U$, tels que le segment\footnote{Définition~\ref{DefLISOooDHLQrl}.} $[a,b]$ soit contenu dans $U$. Soit $u$ le vecteur \[ u=\frac{b-a}{\|b-a\|_m}. \] Si $\partial_u f(x)$ existe pour tout $x$ dans $[a,b]$ on a \[ \|f(b)-f(a)\|_n\leq \sup_{x\in[a,b]}\|\partial_uf(x)\|_n\|b-a\|_m. \] \end{theorem} \index{accroissements finie!dérivée partielle} \begin{proof} Nous considérons la fonction $g(t)=f\big( (1-t)a-tb \big)$. Elle décrit la droite entre $a$ et $b$ parce que $g(0)=a$ et $g(1)=b$. En ce qui concerne la dérivée, \begin{equation} \begin{aligned}[] g'(t) & =\lim_{h\to 0} \frac{ g(t+h)-g(t) }{ h } \\ & =\lim_{h\to 0} \frac{ f\big( (1-t-h)a-(t+h)b \big) }{ h } \\ & =\lim_{h\to 0} \frac{ f\big( a+(t+h)(b-a) \big)-f\big( a+t(b-a) \big) }{ h } \\ & =\frac{ \partial f }{ \partial u }\big( a+t(b-a) \big)\| b-a \|. \end{aligned} \end{equation} Le dernier facteur $\| b-a \|$ apparaît pour la normalisation du vecteur $u$. En effet dans la limite, il apparaît $h(b-a)$, ce qui donnerait la dérivée le long de $b-a$, tandis que $u$ vaut $(b-a)/\| b-a \|$. Par le théorème des accroissements finis pour $g$, il existe $t_0\in\mathopen] 0 , 1 \mathclose[$ tel que \begin{equation} g(1)=g(0)+g'(t_0)(1-0). \end{equation} Donc \begin{equation} \| g(1)-g(0) \|\leq\sup_{t_0}\| g'(t_0) \|=\sum_{t_0\in\mathopen] 0 , 1 \mathclose[}\left\| \frac{ \partial f }{ \partial u }(a+t_0(b-a)) \right\|\| b-a \|. \end{equation} Mais lorsque $t_0$ parcours $\mathopen] 0 , 1 \mathclose[$, le point $a+t_0(b-a)$ parcours le segment $\mathopen] a , b \mathclose[$, d'où le résultat. \end{proof} \begin{corollary} Dans les mêmes hypothèses, si $n=1$, alors il existe $\bar x $ dans $]a,b[$ tel que \[ f(b)-f(a)=\partial_uf(\bar x)\|b-a\|_m. \] \end{corollary} \begin{definition} Le nombre \begin{equation} \lim_{t\to 0} \frac{ f\big( a+tu_1,b+tu_2 \big)-f(a,b) }{ t } \end{equation} est la \defe{dérivée directionnelle}{dérivée!directionnelle} de $f$ dans la direction de $u$ au point $(a,b)$. Il sera noté \begin{equation} \frac{ \partial f }{ \partial u }(a,b), \end{equation} ou plus simplement $\partial_uf(a,b)$. \end{definition} Lorsque $f$ est différentiable, la dérivée directionnelle est donnée par \begin{equation} \label{EqDerDirnablau} \frac{ \partial f }{ \partial u }(p)=\nabla f(p)\cdot u. \end{equation} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Gradient : direction de plus grande pente} %--------------------------------------------------------------------------------------------------------------------------- Étant donné que $u$ est de norme $1$, l'inégalité de Cauchy-Schwarz donne \begin{equation} \big| \nabla f(a,b)\cdot \begin{pmatrix} u_1 \\ u_2 \end{pmatrix}\big|\leq \| \nabla f(a,b) \|. \end{equation} Donc \begin{equation} -\| \nabla f(p) \|\leq \nabla f(p)\cdot u\leq\| \nabla f(p) \|. \end{equation} La norme de la dérivée directionnelle (qui est la valeur absolue du nombre au centre) est donc «coincée» entre $-\| \nabla f(p) \|$ et $\| \nabla f(p) \|$. Prenons par exemple \begin{equation} u=\frac{ \nabla f(p) }{ \| \nabla f(p) \| }. \end{equation} Dans ce cas, nous avons exactement \begin{equation} \nabla f(p)\cdot u=\| \nabla f(p) \|, \end{equation} qui est la valeur maximale que la dérivée directionnelle peut prendre. La direction du gradient est donc la direction suivant laquelle la dérivée directionnelle est la plus grande. Pour la même raison, la dérivée directionnelle est la plus petite dans le sens opposé au gradient. En termes bien clairs : lorsqu'on veut aller le plus vite possible au ski, on prend la direction du gradient de la piste de ski. C'est dans cette direction que ça descend le plus vite. Dans quelle direction vont les débutants ? Ils vont perpendiculairement à la pente (ce qui ennuie tout le monde, mais c'est un autre problème). Les débutants vont donc dans la direction perpendiculaire au gradient. Prenons donc $u\perp \nabla f(p)$ et calculons la dérivée directionnelle de $f$ dans la direction $u$ en utilisant la formule~\ref{EqDerDirnablau} : \begin{equation} \frac{ \partial f }{ \partial u }(p)=\nabla f(p)\cdot u=0 \end{equation} parce que nous avons choisi $u\perp \nabla f(p)$. Nous voyons donc que les débutants en ski ont eu la bonne intuition que la direction dans laquelle la piste ne descend pas, c'est la direction perpendiculaire au gradient. C'est aussi pour cela que l'on a tendance à faire du zig-zag à vélo lorsqu'on monte une pente très forte et qu'on est fatigué. C'est toujours pour cela que les routes de montagne font de longs lacets. La montée est moins rude en suivant une direction proche d'être perpendiculaire au gradient ! \begin{theorem} Le gradient des fonctions suit à peu près les mêmes règles que les dérivées. Soient $f$ et $g$ deux fonctions différentiables. Nous avons entre autres \begin{enumerate} \item $\nabla(f+g)=\nabla f+\nabla g$; \item $\nabla(fg)(a,b)=g(a,b)\nabla f(a,b)+f(a,b)\nabla g(a,b)$; \item Dès que $g(a,b)\neq 0$, nous avons \begin{equation} \nabla\frac{ f }{ g }=\frac{ g(a,b)\nabla f(a,b)-f(a,b)\nabla g(a,b) }{ g(a,b)^2 }. \end{equation} \end{enumerate} \end{theorem} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Gradient : orthogonal au plan tangent} %--------------------------------------------------------------------------------------------------------------------------- Vu que le gradient d'une fonction est la direction de plus grande pente et que le plan tangent est le plan de plus petite pente, quoi de plus naturel que de penser que le gradient est orthogonal au plan tangent ? \begin{lemma} Soit \( \phi\colon \eR^n\to \eR\) une fonction de classe \( C^1\) et la partie \begin{equation} \Gamma=\{ x\in \eR^n\tq \phi(x)=C \} \end{equation} pour une certaine constante \( C\). Soit \( x_0\in \Gamma\). Le gradient de \( \phi\) en \( x_0\) est orthogonal au plan tangent à \( \Gamma\) en \( x_0\). \end{lemma} \begin{proof} Un vecteur tangent à \( \Gamma\) en \( x_0\) est de la forme \( \gamma'(0)\) où \( \gamma\colon \eR \to \Gamma\) vérifie \( \gamma(0)=x_0\). Vu que \( \phi\) est constante sur \( \Gamma\) nous avons \begin{equation} \Dsdd{ \phi\big( \gamma(s) \big) }{s}{0}=0, \end{equation} ce qui donne \begin{equation} \sum_i\frac{ \partial \phi }{ \partial x_i }\big( \gamma(0) \big)\gamma_i'(0)=0, \end{equation} ce qui signifie exactement \( \langle (\nabla\phi)(x_0), \gamma'(0)\rangle=0\). Le vecteur \( (\nabla\phi)(x_0)\) est donc perpendiculaire à tout vecteur tangent de \( \Gamma\) en \( x_0\). \end{proof} %--------------------------------------------------------------------------------------------------------------------------- \subsection{Mise en bouche en dimension 2} %--------------------------------------------------------------------------------------------------------------------------- Nous savons déjà comment dériver les fonctions composées de $\eR$ dans $\eR$. C'est la proposition \ref{PROPooDONLooWthqRR}. Si nous avons deux fonctions $f\colon \eR\to \eR$ et $u\colon \eR\to \eR$, nous formons la composée $\varphi=f\circ u\colon \eR\to \eR$ dont la dérivée vaut \begin{equation} \varphi'(a)=f'\big( u(a) \big)u'(a). \end{equation} Considérons maintenant le cas un peu plus compliqué des fonctions $f\colon \eR\to \eR$ et $u\colon \eR^2\to \eR$, et de la composée \begin{equation} \begin{aligned} \varphi\colon \eR^2 & \to \eR \\ \varphi(x,y) & = f\big( u(x,y) \big). \end{aligned} \end{equation} Afin de calculer la dérivée partielle de $\varphi$ par rapport à $x$, nous admettons que pour tout $a$, $b$ et $t$, il existe $c\in\mathopen[ a , a+t \mathclose]$ tel que \begin{equation} u(a+t,b)=u(a,b)+t\frac{ \partial u }{ \partial x }(c,b). \end{equation} Cela est une généralisation immédiate du théorème~\ref{ThoAccFinis}. Nous devons calculer \begin{equation} \label{EqPremPasDiffxvp} \frac{ \partial \varphi }{ \partial x }(a,b)=\lim_{t\to 0} \frac{ \varphi(a+t,b)-\varphi(a,b) }{ t }=\lim_{t\to 0} \frac{ f\big( u(a+t,b) \big)-g\big( u(a,b) \big) }{ t }. \end{equation} Étant donné l'hypothèse que nous avons faite sur $u$, nous avons \begin{equation} f\big( u(a+t,b) \big)=f\big( u(a,b)+t\frac{ \partial u }{ \partial x }(c,b) \big). \end{equation} En utilisant le théorème des accroissements finis pour $f$, nous avons un point $d$ entre $u(a,b)$ et $u(a,b)+t\frac{ \partial u }{ \partial x }(c,b)$ tel que \begin{equation} f\big( u(a,b)+t\frac{ \partial u }{ \partial x }(c,b) \big)=f\big( u(a,b) \big)+t\frac{ \partial u }{ \partial x }(c,b)f'(d). \end{equation} Le numérateur de \eqref{EqPremPasDiffxvp} devient donc \begin{equation} t\frac{ \partial u }{ \partial x }(c,b)f'(d). \end{equation} Certes les points $c$ et $d$ sont inconnus, mais nous savons que $c$ est entre $a$ et $a+t$ ainsi que $d$ se situe entre $u(a,b)$ et $u(a,b)+t\frac{ \partial u }{ \partial x }(c,b)$. Lorsque nous prenons la limite $t\to 0$, nous avons donc $\lim_{t\to 0} c=a$ et $\lim_{t\to 0} d=u(a,b)$. Nous avons alors \begin{equation} \lim_{t\to 0} \frac{ t\frac{ \partial u }{ \partial x }(c,b)f'(d) }{ t }=\frac{ \partial u }{ \partial x }(a,b)f'\big( u(a,b) \big). \end{equation} La formule que nous avons obtenue (de façon pas très rigoureuse) est \begin{equation} \frac{ \partial }{ \partial x }f\big( u(x,y) \big)=\frac{ \partial u }{ \partial x }(x,y)f'\big( u(x,y) \big). \end{equation} Prenons maintenant un cas un peu plus compliqué où nous voudrions savoir les dérivées partielles de la fonction $\varphi$ donnée par \begin{equation} \varphi(x,y,z)=f\big( u(x,y),v(x,y,z) \big) \end{equation} où $f\colon \eR^2\to \eR$, $u\colon \eR^2\to \eR$ et $v\colon \eR^3\to \eR$. Commençons par la dérivée partielle par rapport à $z$. Étant donné que $\varphi$ ne dépend de $z$ que via la seconde entrée de $f$, il est normal que seule la dérivée partielle de $f$ par rapport à sa seconde entrée arrive dans la formule : \begin{equation} \frac{ \partial \varphi }{ \partial z }(x,y,z)=\frac{ \partial f }{ \partial v }\big( u(x,y),v(x,y,z) \big)\frac{ \partial v }{ \partial z }(x,y,z). \end{equation} La dérivée partielle par rapport à $y$ demande de tenir compte en même temps de la façon dont $f$ varie avec sa première entrée et la façon dont elle varie avec sa seconde entrée; cela nous fait deux termes : \begin{equation} \frac{ \partial \varphi }{ \partial y }(x,y,z)=\frac{ \partial f }{ \partial u }\big( u(x,y),v(x,y,z) \big)\frac{ \partial u }{ \partial y }(x,y)+\frac{ \partial f }{ \partial v }\big( u(x,y),v(x,y,z) \big)\frac{ \partial v }{ \partial y }(x,y,z). \end{equation} Cette formule a une interprétation simple. Lançons un caillou du sommet d'une falaise. Son mouvement est une chute libre avec une vitesse initiale horizontale : \begin{subequations} \begin{numcases}{} x(t)=v_0t\\ y(t)=h_0-\frac{ gt^2 }{ 2 } \end{numcases} \end{subequations} où $v_0$ est la vitesse initiale horizontale et $h_0$ est la hauteur de la falaise. Si nous sommes intéressés à la distance entre le caillou et le bas de la falaise (point $(0,0)$), le théorème de Pythagore nous dit que \begin{equation} d(t)=\sqrt{x^2(t),y^2(t)}. \end{equation} Pour trouver la variation de la distance par rapport au temps il faut savoir de combien la distance varie lorsque $x$ varie et multiplier par la variation de $x$ par rapport à $t$, et puis faire la même chose avec $y$. %--------------------------------------------------------------------------------------------------------------------------- \subsection{Accroissements finis et dérivées partielles} %--------------------------------------------------------------------------------------------------------------------------- \begin{proposition}[Accroissements finis] \label{PROPooCAWBooINcNxj} Soient des espaces vectoriels normés \( V\) et \( W\). Soit une application \( f\colon V\to W\). Soient des points \( a,b\in V\) tels que \( f\) est continue sur le segment \( \mathopen[ a , b \mathclose]\) et partiellement dérivable dans la direction \( b-a\) sur \( \mathopen] a , b \mathclose]\). Alors il existe \( c\in\mathopen] a , b \mathclose[\) tel que \begin{equation} f(b)=f(a)+(\partial_{\beta}f)(c) \end{equation} où \( c\in \mathopen[ a , b \mathclose]\) et \( \beta=b-a\). \end{proposition} \begin{proof} Nous considérons la fonction \begin{equation} \begin{aligned} \varphi\colon \mathopen[ 0 , 1 \mathclose] & \to W \\ t & \mapsto f\big( a+t(b-a) \big). \end{aligned} \end{equation} Par le théorème des accroissements finis \ref{ThoAccFinis}, il existe \( s\in \mathopen[ 0 , 1 \mathclose]\) tel que\footnote{Les \( a\) et \( b\) dans l'énoncé de \ref{ThoAccFinis} sont les valeurs \( s=0\) et \( s=1\) ici. Rien à voir avec les \( a\) et \( b\) d'ici qui sont des éléments de \( V\).} \begin{equation} \varphi(1)=\varphi(0)+\varphi'(s)(1-0). \end{equation} Autrement dit, \begin{equation} f(b)=f(a)+(\partial_{\beta}f)\big( a+s(b-a) \big). \end{equation} Nous avons le résultat en posant \( c=a+s(b-a)\). \end{proof} \begin{lemma}[Accroissements finis\cite{MonCerveau}] \label{LEMooNMTAooLgMkgH} Soient des espaces vectoriels normés \( V\) et \( W\). Soit une fonction \( f\colon V\to W\) qui est différentiable sur un voisinage \( \mO\) de \( a\in V\). Soient \( v\in V\) et \( \epsilon>0\) tels que \(a+\epsilon v\) reste dans \( \mO\). Nous considérons une base de \( V\) pour donner un sens aux dérivées partielles \( \partial_kf\). Alors il existe une fonction \( \alpha\colon V\to W\) telle que \begin{equation} f(a+\epsilon v)=f(a)+\sum_{k=1}^n\epsilon v_k (\partial_kf)\big( a+\sum_{i=k+1}^n\epsilon v_ie_i \big)+\epsilon\alpha(\epsilon) \end{equation} où la somme sur \( i\) est nulle dans le cas \( k=n\). \end{lemma} \begin{proof} Nous commençons par nous attaquer à la dérivation par rapport à la première variable. La définition \ref{DEFooCATTooTPLtpR} de la dérivation partielle nous invite à poser \begin{equation} \varphi(t)=f\big( a+\sum_{k=2}^n\epsilon v_ke_k+tv_1e_1 \big). \end{equation} Nous avons : \begin{equation} \varphi'(0)=v_1(\partial_1f)\big( a+\sum_{k=2}^n\epsilon v_ke_k \big). \end{equation} Nous appliquons les accroissements finis \ref{PropUTenzfQ} à la fonction \( \varphi\) en \( t=0\). Nous avons une fonction \( \alpha\colon \eR\to W\) telle que \( \lim_{t\to 0} \alpha_1(t)=0\) et \begin{equation} \varphi(t)=\varphi(0)+t\varphi'(0)+t\alpha_1(t). \end{equation} Nous écrivons cette égalité pour \( t=\epsilon\), tout en rappelant que \( \varphi(\epsilon)=f(a+\epsilon v)\) : \begin{equation} f(a+\epsilon v) = \varphi(\epsilon)=f\big( a+\sum_{k=2}^n\epsilon v_ke_k \big)+\epsilon v_1(\partial_1f)\big( a+\sum_{k=2}^n \epsilon v_ke_k \big)+\epsilon \alpha_1(\epsilon). \end{equation} Pour la suite, il suffit de recommencer en écrivant \( \sum_{k=2}^n \epsilon v_ke_k=\epsilon v_2 e_2+\sum_{k=3}^n\epsilon v_k e_k\) dans le second terme. \end{proof} Voici une version un peu moins technologique. \begin{proposition} \label{PROPooYYSMooUDxtlB} Soit une fonction \( f\colon V\to \eR\) où \( V\) est un espace vectoriel métrique. Soit \( a\in V\) tel que \( (\partial_if)(a)\) existe. Alors il existe une fonction \( \alpha\colon \eR\to \eR\) tel que \begin{equation} f(a+\epsilon e_i)=f(a)+\epsilon(\partial_if)(a)+\epsilon\alpha(\epsilon) \end{equation} et \( \lim_{\epsilon\to 0}\alpha(\epsilon)=0\). \end{proposition} \begin{proof} Nous posons \begin{equation} \begin{aligned} \varphi\colon \eR & \to \eR \\ t & \mapsto f(a+ te_i). \end{aligned} \end{equation} Par hypothèse (et définition \ref{DEFooCATTooTPLtpR} de la dérivée partielle), la fonction \( \varphi\) est dérivable et \begin{equation} \varphi'(0)=(\partial_if)(a). \end{equation} Nous appliquons le théorème des accroissements finis \ref{PropUTenzfQ} sur la fonction \( \varphi\) : \begin{equation} \label{EQooGSLNooJcrLIb} \varphi(t)=\varphi(0)+\varphi'(0)+t\alpha(t) \end{equation} pour une certaine fonction \( \alpha\colon \eR\to \eR\) qui vérifie \( \lim_{t\to 0} \alpha(t)=0\). En remplaçant \( \varphi\) par sa valeur en termes de \( f\) dans \eqref{EQooGSLNooJcrLIb}, \begin{equation} f(a+te_i)=f(a)+(\partial_if)(a)+t\alpha(t). \end{equation} \end{proof}
LaurentClaessens/mazhe
tex/frido/219_analyseR.tex
TeX
gpl-3.0
120,884
# clipmenu-im `clipmenu-im(proved)` is a simple clipboard history managment script in `bash`. This version allows you to manage (add, remove, purge) entries in your clipboard history. ## Features: - **copy** an entry from history to clipboard - **remove** entries from history on demand (dude, I missed this one) - **autoremove empty** or blank entries (new!) - **limit duplicates** creation (in progress) - **purge** history on demand (new!) - option to use **cli-based menu** or **gtk-based menu** instead of `dmenu` (new!) - accept any `dmenu` options on commandline ## Usage: clipmenu-im [-c] [-d|-D] [any dmenu options] First start `clipmenud` daemon: clipmenud & Then use `clipmenu-im` to **copy** any entry from history to clipboard: clipmenu-im now you can paste it the usual way. To **delete** any entry from the history: clipmenu-im -d It will let you choose lines to be deleted multiple times, when you are done press `C-c`. If you want to **purge** the history, use: clipmenu-im -D If you would like to use `clipmenu-im` with **cli-based menu** instead of `dmenu` add `-c` switch (`-z` for `zenity` dialog) to any of the above commands, eg: clipmenu-im -c -d will let you delete entries using text menu in terminal. ### Dependencies: [dmenu](http://tools.suckless.org/dmenu) (optional, recommended), `xclip`, `xsel`, zenity (optional, only if you want gtk gui) under Debian you can get them with: sudo apt-get install suckless-tools xclip xsel zenity ### TODO: - use pure `bash`, remove all unnecessary calls to external tools (in progress, not urgent) - some dmenu "skinning" depending on what we are doing (copy/delete) (in progress, not urgent) - purging history by sending SIGHUP to `clipmenud` seems more 'standard' (in progress, not urgent) ## Credits: The `clipmenu-im` is the extended and rewritten version of [clipmenu](https://github.com/cdown/clipmenu) by cdown. The `clipmenud` is the original code by cdown. ## Copyright: Licensed under GNU General Public License v3 (see License file). Copyright (C) 2016 Tomasz Winiarski
ogeno/clipmenu-im
README.md
Markdown
gpl-3.0
2,107
#include "cc430x513x.h" #include "config.h" #include "radio.h" #include "radio/RF1A.h" #include "radio/hal_pmm.h" #include "I2Croutines.h" #include <stdio.h> void accurate_clk(void); void init(void); void send_debug(char*); void send_packet(void); uint16_t crc_xmodem_update (uint16_t crc, uint8_t data); #define BITHIGH WriteSingleReg(FREQ0, 0x3E) #define BITLOW WriteSingleReg(FREQ0, 0x3C) #define ODR_HIGH cntrl_reg1_val = 0xA1; EEPROM_ByteWrite(0x26,cntrl_reg1_val) #define ODR_MED cntrl_reg1_val = 0xB1; EEPROM_ByteWrite(0x26,cntrl_reg1_val) #define ODR_LOW cntrl_reg1_val = 0xB9; EEPROM_ByteWrite(0x26,cntrl_reg1_val) #define AVERAGE_BUF_POWER (4) #define LAUNCH_DET_LEN (4) #define AVERAGE_BUF_LEN (1<<AVERAGE_BUF_POWER) //16 is sample rate at max speed #define THRES_NO_LAUNCH (5 *16) #define THRES_POST_LAUNCH (20) #define THRES_MED (2 *16) //#define THRES_LARGE (6 *16) #define THRES_LARGE (20) volatile int prev_bit = 0; uint8_t sendBuff[100] = "\0"; char debugBuff[100] = "\0"; volatile uint8_t bitpos = 0; volatile uint8_t* sendPtr = &sendBuff[0]; char outvar; volatile uint8_t state = 0; //0-idle, 1-inflight, 2-postflight uint8_t cntrl_reg1_val = 0xB8 | 1; int32_t tx_max = 0; int32_t tx_min = 0; uint16_t tx_id = 0; uint16_t batt_voltage = 0; uint16_t ticks_since_last = 0; uint8_t button_held = 3; uint8_t button_held_off = 2; uint16_t packet_count = 0; const uint16_t device_id = 0x5E06; /* * main.c */ void main(void) { WDTCTL = WDTPW + WDTHOLD; // WDTCTL = WDTPW + (0x2 << 5) + 3; init(); __bis_SR_register(GIE); //__delay_cycles(400000); while(ADC12CTL1 & ADC12BUSY); batt_voltage = ADC12MEM0; ADC12CTL0 |= ADC12SC; __delay_cycles(400000); while(ADC12CTL1 & ADC12BUSY); batt_voltage = ADC12MEM0; ADC12CTL0 |= ADC12SC; while(ADC12CTL1 & ADC12BUSY); batt_voltage = ADC12MEM0; if (batt_voltage > 2662) // 3.9V P2OUT |= BIT3; else P2OUT |= BIT4; radio_high_power(); //radio_carrier_on(); send_debug("rst\n"); //unsigned char txbuffp[] = {1,2,3,4,5,6,7,8,9,10}; // while(1) // { // transmit_packet(txbuffp,10); // __delay_cycles(4000000); // } int32_t launch_det_buff[LAUNCH_DET_LEN]; int32_t averaging_buff[AVERAGE_BUF_LEN] = {0}; state = 2; //allows a base average to be got uint8_t ldb_ptr = 0; uint8_t av_ptr = 0; uint8_t buff[10]; int32_t average_sum = 0; uint8_t launch = 0; //0 - no launch; >0 - launch //1 - medium increase since last value (needs another medium increase) //2 - large increase since last value (needs another value close) uint8_t sample_rate = 0; //0 - slow //1 - med //2 - max uint16_t launch_sample_count = 0; //how many samples has a launch been detected for uint16_t no_launch_sample_count = 0; //how many samples has a no launch been detected for (used when in launch state) uint16_t post_launch_sample_count = 0; int32_t level_point = 0; int32_t max_point = 0x80000000; int32_t min_point = 0x7FFFFFFF; uint8_t set_level = 0; //reset when returning to idle uint16_t since_last_tx = 0; //all altitudes in meters x16 EEPROM_SequentialRead(1,&buff[0],3); //set high to get initial ground average sample_rate = 2; ODR_HIGH; uint8_t test; while(1) { //slow down /* while(P3IN & BIT4); EEPROM_SequentialRead(1,&buff[0],3); EEPROM_ByteWrite(0x26,cntrl_reg1_val); EEPROM_ByteWrite(0x26,cntrl_reg1_val | 2); while(P3IN & BIT4); EEPROM_SequentialRead(1,&buff[0],3); EEPROM_ByteWrite(0x26,cntrl_reg1_val); EEPROM_ByteWrite(0x26,cntrl_reg1_val | 2); */ //wait for new sample while(P3IN & BIT4); //get new value EEPROM_SequentialRead(1,&buff[0],3); if(sample_rate) { EEPROM_ByteWrite(0x26,cntrl_reg1_val); //get a new value ASAP EEPROM_ByteWrite(0x26,cntrl_reg1_val | 2); } int32_t alt = 0; if (buff[0] & 0x80) alt = 0xFFF00000; //sign extend alt |= ((int32_t)buff[0] << 12); alt |= ((int32_t)buff[1] << 4); alt |= ((int32_t)buff[2] >> 4); /////// #ifdef DEBUG if (state == 0) { test++; if (test == 60) { test = 0; alt = alt + 300; } } #endif ////// /////////////////////////////// /// launch detect /// /////////////////////////////// // current = alt // last = launch_det_buff[ldb_ptr] // prev = launch_det_buff[ptr_last] uint8_t ptr_last; if (ldb_ptr == 0) ptr_last = LAUNCH_DET_LEN-1; else ptr_last = ldb_ptr-1; int32_t diff1,diff2; diff1 = (alt-launch_det_buff[ldb_ptr]); diff2 = (launch_det_buff[ldb_ptr] - launch_det_buff[ptr_last]); uint8_t sign = 0; if ((diff1 & 0x80000000)^(diff2 & 0x80000000)) //see if same sign on diffs sign = 1; diff1 = abs(diff1); diff2 = abs(diff2); if (state < 2) { if (diff1 > THRES_LARGE) //high rate launch happening { launch = 2; launch_sample_count++; sample_rate = 2; ODR_HIGH; // send_debug("HR "); } else if (sign) //otheriwse, if different signs, no launch { launch = 0; // send_debug("DS "); if (sample_rate == 1) //go back to idle, no launch { sample_rate = 0; ODR_LOW; } } else { if (diff1 > THRES_MED) { if (diff2 > THRES_MED) //launch happening { launch = 1; launch_sample_count++; sample_rate = 2; ODR_HIGH; // send_debug("MR "); } else //launch might be happening, but wait until next sample { sample_rate = 1; ODR_MED; // send_debug("QR "); } } else { if (sample_rate == 1) //go back to idle, no launch { sample_rate = 0; ODR_LOW; } // send_debug(" "); } } } //TODO: compare current against average baselevel //if just launched, save average as base level if (launch > 0 && set_level == 0) { set_level = 1; level_point = average_sum; } /////////////////////////////// /// calculate base level /// /////////////////////////////// //place onto launch buffer int32_t removed; ldb_ptr++; if (ldb_ptr == LAUNCH_DET_LEN) ldb_ptr = 0; removed = launch_det_buff[ldb_ptr]; launch_det_buff[ldb_ptr] = alt; //place onto averaging buffer int32_t removed2 = averaging_buff[av_ptr]; averaging_buff[av_ptr] = removed; av_ptr++; if (av_ptr == AVERAGE_BUF_LEN) av_ptr = 0; //update average (not divided by number of elements of the array yet) average_sum -= removed2; average_sum += removed; int32_t diff = alt-level_point; snprintf(debugBuff,100,"%d %d \n\r",(int16_t)alt,(int16_t)diff); send_debug(debugBuff); // WDTCTL = (WDTCTL & 0x00FF) | WDTPW | (0x1 << 3); switch (state) { case 0: //idle state //test battery voltage //read previous batt_voltage = ADC12MEM0; if (batt_voltage > 2662) // 3.9V P2OUT |= BIT3; else P2OUT |= BIT4; //monitor power button if ((P1IN & (1<<1))) { if (button_held == 0){ if(button_held_off == 0){ P1OUT &= ~BIT2; //turn off P2OUT &= ~(BIT3 | BIT4); } else button_held_off--; } } else if (button_held) button_held--; else button_held_off = 2; if (launch > 0) { tx_id++; state = 1; send_debug("launch det\n\r"); level_point = average_sum >> AVERAGE_BUF_POWER; since_last_tx = 0; } //sync pulse tx / showalive since_last_tx++; if (since_last_tx > 10) { since_last_tx = 0; send_packet(); } ticks_since_last++; #ifdef DEBUG if (ticks_since_last > 60)//1800) //change P1OUT &= ~BIT2; //turn off #else if (ticks_since_last > TTL_MAX) //change P1OUT &= ~BIT2; //turn off #endif //test battery voltage //start next ADC12CTL0 |= ADC12SC; _delay_cycles(30000); P2OUT &= ~(BIT3 | BIT4); break; case 1: //launch state if (launch == 0 ) no_launch_sample_count++; if (no_launch_sample_count > THRES_NO_LAUNCH) //if launch has been 0 for a while move to post launch state { state = 2; no_launch_sample_count = 0; launch_sample_count = 0; send_debug("launch ended\r\n"); } // send_packet(); break; default: //post launch state post_launch_sample_count++; if (post_launch_sample_count > THRES_POST_LAUNCH) //stay in post launch for a while to get a new base average { state = 0; post_launch_sample_count = 0; set_level = 0; max_point = 0x80000000; min_point = 0x7FFFFFFF; send_debug("entering idle\r\n"); sample_rate = 0; ODR_LOW; if (tx_max > 1600 || tx_min < -1600) ///change ticks_since_last = 0; } send_packet(); break; } //turn off? if (batt_voltage < 2388){ //3.5V P1OUT &= ~BIT2; //turn off } //if state==launch do min/max if (state == 1) { if (alt > max_point) max_point = alt; if (alt < min_point) min_point = alt; tx_max = max_point - level_point; tx_min = min_point - level_point; } } } void form_packet(uint8_t *buff) { buff[0] = (uint8_t)(packet_count>>8); buff[1] = (uint8_t)(packet_count & 0xFF); buff[2] = (uint8_t)(device_id >> 8); buff[3] = (uint8_t)(device_id & 0xFF); int32_t t = tx_max; buff[7] = (uint8_t)(t & 0xFF); t = t >> 8; buff[6] = (uint8_t)(t & 0xFF); t = t >> 8; buff[5] = (uint8_t)(t & 0xFF); t = t >> 8; buff[4] = (uint8_t)(t & 0xFF); t = tx_min; buff[11] = (uint8_t)(t & 0xFF); t = t >> 8; buff[10] = (uint8_t)(t & 0xFF); t = t >> 8; buff[9] = (uint8_t)(t & 0xFF); t = t >> 8; buff[8] = (uint8_t)(t & 0xFF); buff[16] = state; buff[17] = (uint8_t)((batt_voltage >> 4)&0xFF); buff[18] = (uint8_t)(tx_id>>8); buff[19] = (uint8_t)(tx_id & 0xFF); buff[20] = (uint8_t)(((TTL_MAX-ticks_since_last)>>8)&0xFF); buff[21] = (uint8_t)((TTL_MAX-ticks_since_last)&0xFF); uint16_t crc = 0xFFFF; uint8_t i; for (i = 0; i < 26; i++) crc = crc_xmodem_update(crc,buff[i]); buff[26] = (uint8_t)((crc>>8) & 0xFF); buff[27] = (uint8_t)(crc & 0xFF); } uint16_t crc_xmodem_update (uint16_t crc, uint8_t data) { int i; crc = crc ^ ((uint16_t)data << 8); for (i=0; i<8; i++) { if (crc & 0x8000) crc = (crc << 1) ^ 0x1021; else crc <<= 1; } return crc; } void send_packet(void) { // if (!(*sendPtr)) // { // snprintf(sendBuff,30,"XXX$$%u,%ld,%ld\n",(int16_t)tx_id,tx_max,tx_min); // TA1CCTL0 = CCIE; // sendPtr = sendBuff; // } unsigned char status = Strobe( RF_SNOP ); if ((status & 0x30) == 0) { form_packet(sendBuff); transmit_packet(sendBuff,28); packet_count++; } } void send_debug(char* string) { while (*string) { while(!(UCA0IFG & UCTXIFG)); UCA0TXBUF = *string; string++; } } #pragma vector=TIMER1_A1_VECTOR __interrupt void Timer1_A1_CCRx_Isr(void) { switch(__even_in_range(TA1IV,6)) { case 0: break; // No interrupts case 2: break; // TA0CCR1 case 4: // TA0CCR2 { // the simulated GPIO interrupt occur - do something break; } case 6: break; // TA0CCR3 default: break; } } // Timer A0 interrupt service routine #pragma vector=TIMER1_A0_VECTOR __interrupt void Timer1_A0 (void) { if(*sendPtr) { if (bitpos == 0) { //start bit BITLOW; outvar = *sendPtr; } else if (bitpos > 7) { //stop bits BITHIGH; } else { if (outvar & 1) BITHIGH; else BITLOW; outvar = outvar >> 1; } bitpos++; if (bitpos > 9) { bitpos = 0; sendPtr++; } } else TA1CCTL0 &= ~CCIE; /* if (prev_bit){ prev_bit = 0; WriteSingleReg(FREQ0, 0x3C); } else { prev_bit = 1; WriteSingleReg(FREQ0, 0x3E); }*/ } void init(void) { //radio_init(); radio_init_packet(); accurate_clk(); //setup counting timer TA1CCR0 = 636;//636; //106; //14 //temporary top TA1CTL = (0x1 << 8) | (0x3 << 6); //ACLK, upto CCR0 mode, /8 prescaler, // TA1CCTL0 = CCIE; TA1R = 0; TA1CTL |= (0x1 << 4); //remap pins PMAPPWD = 0x02D52; P3MAP7 = PM_UCB0SDA; P1MAP0 = PM_UCB0SCL; P3MAP4 = PM_TA1CCR2A; //bodge p3.4 to timer0 for interrupts P2MAP0 = PM_UCA0TXD; PMAPPWD = 0; P3SEL |= (1<<7) | (1<<4); //i2c and pin bodge P1SEL |= (1<<0);// | (1<<7); //temp pullups P3REN |= BIT7; P3OUT |= BIT7; InitI2C(0x60); EEPROM_ByteWrite(0x26,0xB8); //set OSR to 128 EEPROM_ByteWrite(0x13,0x07); //enable data flags (pressure only) EEPROM_ByteWrite(0x28,0x11); //set int active low open drain EEPROM_ByteWrite(0x29,0x80); //enable DRDY interrupt EEPROM_ByteWrite(0x2A,0x80); //DRDY interrupt to INT1 EEPROM_ByteWrite(0x26,cntrl_reg1_val); //set active //setup pin to get drdy P3REN |= BIT4; P3OUT |= BIT4; //ADC ADC12CTL0 = ADC12SHT11 + ADC12ON; // Sampling time, ADC12 on ADC12CTL1 = ADC12SHP; // Use sampling timer ADC12MCTL0 = ADC12INCH_2+ADC12EOS; ADC12CTL0 |= ADC12ENC; ADC12CTL0 |= ADC12SC; //bodge p3.4 to timer0 for interrupts TA1CCTL2 = CM_2 + CCIS_0 + SCS + CAP + CCIE; //keepon P1DIR |= BIT2; P1OUT |= BIT2; //button sense pull down P1REN |= (1<<1); //status LEDs P2DIR |= BIT3 | BIT4; P2OUT &= ~(BIT3 | BIT4); //setup debug uart P2SEL |= BIT0; P2DIR |= BIT0; UCA0CTL1 |= UCSSEL_1; UCA0BR0 = 27; UCA0BR1 = 0; UCA0MCTL = UCBRS1; UCA0CTL1 &= ~UCSWRST; } void accurate_clk(void) //SMCLK: 8.125MHz //ALCK: 253kHz { UCSCTL6 = (0<<8) | (1<<0); //RF XL on, //UCSCTL0 = ; DCO and MOD modified automatically during FLL operation UCSCTL1 = (5<<4); //DCO to range 5 UCSCTL2 = 4 | (0 << 12); //prescaler: 1, divider: 4 UCSCTL3 = (0x5 << 4) | 0x5; //xt2 reference for FLL, input prescale: 16 UCSCTL4 = SELA__DCOCLKDIV | SELS__DCOCLK | SELM__DCOCLKDIV; //SMCLK: DCO, ACLK/MCLK: DCODIV UCSCTL5 = (0x0 << 12) | (0x5 << 8) | (0x0 << 4) | 0x4; //ACLK: /32, SMCLK: /1, MCLK: /16 } //int32_t abs(int32_t in1) //{ // if (in1 & 0x80000000) // return -in1; // else // return in1; //}
suspaceflight/rocket-logger
firmware/main.c
C
gpl-3.0
14,056
import unittest from aiourlstatus import app class TestEmpty(unittest.TestCase): def test_no_urls(self): data = '' urls, len_urls = app.find_sort_urls(data) self.assertEqual(urls, []) self.assertEqual(len_urls, 0) class TestTXT(unittest.TestCase): def test_parse_text(self): with open('tests/retest.txt') as f: data = f.read() urls, len_urls = app.find_sort_urls(data) url_list = [['http://en.wikipedia.org/wiki/Body_image', 'http://en.wikipedia.org/wiki/Identity_formation', 'http://en.wikipedia.org/wiki/Self-confidence', 'http://en.wikipedia.org/wiki/Self-esteem'], ['http://www.bbc.com/sport/0/'], ['http://www.haskell.org/'], ['http://lxer.com/'], ['http://www.find-happiness.com/definition-of-happiness.html'], ['http://www.wikihow.com/Elevate-Your-Self-Esteem']] self.assertCountEqual(urls, url_list) if __name__ == '__main__': unittest.main()
riverrun/aiourlstatus
tests/parse_test.py
Python
gpl-3.0
990
$.components.register("ajax", { defaults: { }, init: function(context) { }, api: function() { $(document).on('click.site.ajax', '[data-plugin="ajax"]', function(e) { e.preventDefault(); var $this = $(this); var href, url = $(this).attr('data-target') || (href = $(this).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, ''); var successEvent = $.Event('success.site.ajax', { relatedTarget: $this[0] }); var failureEvent = $.Event('failure.site.ajax', { relatedTarget: $this[0] }); $.get(url).then(function() { $this.trigger(successEvent); }, function() { $this.trigger(failureEvent); }); }); } });
meloncocoo/spring-based
web-ui/html/global/src/js/components/ajax.js
JavaScript
gpl-3.0
759
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class STransformAnimationPlayEventData : CVariable { [Ordinal(0)] [RED("timeScale")] public CFloat TimeScale { get; set; } [Ordinal(1)] [RED("looping")] public CBool Looping { get; set; } [Ordinal(2)] [RED("timesPlayed")] public CUInt32 TimesPlayed { get; set; } public STransformAnimationPlayEventData(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/STransformAnimationPlayEventData.cs
C#
gpl-3.0
525
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # Copyright (C) Zing contributors. # # This file is a part of the Zing project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import json import operator from django.core.exceptions import PermissionDenied from django.db.models import ProtectedError, Q from django.forms.models import modelform_factory from django.http import Http404 from django.shortcuts import get_object_or_404 from django.utils.functional import cached_property from django.views.generic import View from pootle.core.http import ( JsonResponse, JsonResponseBadRequest, JsonResponseForbidden, JsonResponseNotFound ) class JSONDecodeError(ValueError): pass class APIView(View): """View to implement internal RESTful APIs. Based on djangbone https://github.com/af/djangbone """ # Model on which this view operates. Setting this is required model = None # Base queryset for accessing data. If `None`, model's default manager will # be used base_queryset = None # Set this to restrict the view to a subset of the available methods restrict_to_methods = None # Field names to be included fields = () # Individual forms to use for each method. By default it'll auto-populate # model forms built using `self.model` and `self.fields` add_form_class = None edit_form_class = None # Permission classes implement logic to determine whether the request # should be permitted. Empty list means no permission-checking. permission_classes = [] # Tuple of sensitive field names that will be excluded from any serialized # responses sensitive_field_names = ('password', 'pw') # Set to an integer to enable GET pagination page_size = None # HTTP GET parameter to use for accessing pages page_param_name = 'p' # HTTP GET parameter to use for search queries search_param_name = 'q' # Field names in which searching will be allowed search_fields = None @property def allowed_methods(self): methods = [m for m in self.http_method_names if hasattr(self, m)] if self.restrict_to_methods is not None: restricted_to = map(lambda x: x.lower(), self.restrict_to_methods) methods = filter(lambda x: x in restricted_to, methods) return methods def __init__(self, *args, **kwargs): if self.model is None: raise ValueError('No model class specified.') self.pk_field_name = self.model._meta.pk.name if self.base_queryset is None: self.base_queryset = self.model._default_manager self._init_fields() self._init_forms() return super(APIView, self).__init__(*args, **kwargs) def _init_fields(self): if len(self.fields) < 1: form = self.add_form_class or self.edit_form_class if form is not None: self.fields = form._meta.fields else: # Assume all fields by default self.fields = (f.name for f in self.model._meta.fields) self.serialize_fields = (f for f in self.fields if f not in self.sensitive_field_names) def _init_forms(self): if 'post' in self.allowed_methods and self.add_form_class is None: self.add_form_class = modelform_factory(self.model, fields=self.fields) if 'put' in self.allowed_methods and self.edit_form_class is None: self.edit_form_class = modelform_factory(self.model, fields=self.fields) @cached_property def request_data(self): try: return json.loads(self.request.body) except ValueError: raise JSONDecodeError def get_permissions(self): """Returns permission handler instances required for a particular view.""" return [permission() for permission in self.permission_classes] def check_permissions(self, request): """Checks whether the view is allowed to process the request or not. """ for permission in self.get_permissions(): if not permission.has_permission(request, self): raise PermissionDenied def check_object_permissions(self, request, obj): for permission in self.get_permissions(): if not permission.has_object_permission(request, self, obj): raise PermissionDenied def handle_exception(self, exc): """Handles response exceptions.""" if isinstance(exc, Http404): return JsonResponseNotFound({ 'msg': 'Not found', }) if isinstance(exc, PermissionDenied): return JsonResponseForbidden({ 'msg': 'Permission denied.', }) if isinstance(exc, JSONDecodeError): return JsonResponseBadRequest({ 'msg': 'Invalid JSON data', }) raise def dispatch(self, request, *args, **kwargs): try: self.check_permissions(request) if request.method.lower() in self.allowed_methods: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs) except Exception as exc: return self.handle_exception(exc) def get(self, request, *args, **kwargs): """GET handler.""" if self.kwargs.get(self.pk_field_name, None) is not None: object = self.get_object() return JsonResponse(self.object_to_values(object)) return self.get_collection(request, *args, **kwargs) def get_object(self): """Returns a single model instance.""" obj = get_object_or_404( self.base_queryset, pk=self.kwargs[self.pk_field_name], ) self.check_object_permissions(self.request, obj) return obj def get_collection(self, request, *args, **kwargs): """Retrieve a full collection.""" return JsonResponse(self.qs_to_values(self.base_queryset)) def get_form_kwargs(self): kwargs = { 'data': self.request_data, } if (self.pk_field_name in self.kwargs and self.kwargs[self.pk_field_name] is not None): kwargs.update({ 'instance': self.get_object(), }) return kwargs def post(self, request, *args, **kwargs): """Creates a new model instance. The form to be used can be customized by setting `self.add_form_class`. By default a model form will be used with the fields from `self.fields`. """ form = self.add_form_class(**self.get_form_kwargs()) if form.is_valid(): new_object = form.save() return JsonResponse(self.object_to_values(new_object)) return self.form_invalid(form) def put(self, request, *args, **kwargs): """Update the current model.""" if self.pk_field_name not in self.kwargs: return self.status_msg('PUT is not supported for collections', status=405) form = self.edit_form_class(**self.get_form_kwargs()) if form.is_valid(): updated_object = form.save() return JsonResponse(self.object_to_values(updated_object)) return self.form_invalid(form) def delete(self, request, *args, **kwargs): """Delete the model and return its JSON representation.""" if self.pk_field_name not in kwargs: return self.status_msg('DELETE is not supported for collections', status=405) obj = self.get_object() try: obj.delete() return JsonResponse({}) except ProtectedError as e: return self.status_msg(e[0], status=405) def object_to_values(self, object): """Convert an object to values for serialization.""" return { field: getattr(object, field) for field in self.serialize_fields } def qs_to_values(self, queryset): """Convert a queryset to values for further serialization. An array of objects in `models` and the total object count in `count` is returned. """ search_keyword = self.request.GET.get(self.search_param_name, None) if search_keyword is not None: filter_by = self.get_search_filter(search_keyword) queryset = queryset.filter(filter_by) values = queryset.values(*self.serialize_fields) # Process pagination options if they are enabled if isinstance(self.page_size, int): try: page_param = self.request.GET.get(self.page_param_name, 1) page_number = int(page_param) offset = (page_number - 1) * self.page_size except ValueError: offset = 0 values = values[offset:offset+self.page_size] return_values = { 'models': list(values), 'count': queryset.count(), } return return_values def get_search_filter(self, keyword): search_fields = getattr(self, 'search_fields', None) if search_fields is None: search_fields = self.fields # Assume all fields field_queries = list( zip(map(lambda x: '%s__icontains' % x, search_fields), (keyword,)*len(search_fields)) ) lookups = [Q(x) for x in field_queries] return reduce(operator.or_, lookups) def status_msg(self, msg, status=400): return JsonResponse({'msg': msg}, status=status) def form_invalid(self, form): return JsonResponse({'errors': form.errors}, status=400)
iafan/zing
pootle/core/views/api.py
Python
gpl-3.0
10,141
<?php /** * Sidebar for single post. * * @subpackage GuleTheme * */ ?> <?php if ( is_active_sidebar( 'sidebar-post' ) ) : ?> <div id="sidebar" class="widget-area col-md-4 col-sm-4"> <?php dynamic_sidebar( 'sidebar-post' ); ?> </div><!-- #sidebar --> <?php else : ?> <div id="sidebar" class="widget-area col-md-4 col-sm-4"> <aside class="well widget"> <h3 class="widget-title">Single Post Sidebar</h3> <p> This is post sidebar. Go to widgets and add any widget to "Post Sidebar" to show on this post. </p> </aside> </div> <?php endif; ?>
talentedaamer/Gule
sidebar-post.php
PHP
gpl-3.0
637
// Mantid Repository : https://github.com/mantidproject/mantid // // Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, // NScD Oak Ridge National Laboratory, European Spallation Source // & Institut Laue - Langevin // SPDX - License - Identifier: GPL - 3.0 + #include "MantidQtWidgets/SpectrumViewer/EModeHandler.h" #include "MantidKernel/Logger.h" #include "MantidQtWidgets/SpectrumViewer/QtUtils.h" #include <QLineEdit> namespace { Mantid::Kernel::Logger g_log("SpectrumView"); } namespace MantidQt { namespace SpectrumView { /** * Construct an EModeHandler object to manage the E Mode and E Fixed controls * in the specified UI */ EModeHandler::EModeHandler(Ui_SpectrumViewer *svUI) : m_svUI(svUI) {} /** * Get the EMode value (0,1,2) from the GUI. */ int EModeHandler::getEMode() { return m_svUI->emode_combo_box->currentIndex(); } /** * Set the EMode to display in the GUI. * * @param mode Integer code for the emode type, * 0 = Diffractometer * 1 = Direct Geometry Spectrometer * 2 = Indirect Geometry Spectrometer * NOTE: Any other value will be interpreted as 0 * and the gui will not be changed. */ void EModeHandler::setEMode(const int mode) { if (mode >= 0 && mode <= 2) m_svUI->emode_combo_box->setCurrentIndex(mode); else g_log.error("Mode number invalid: " + QString::number(mode).toStdString() + '\n'); } /** * Return the user specified EFixed value, OR 0, if no valid * EFixed value was set. */ double EModeHandler::getEFixed() { QString text = m_svUI->efixed_control->text(); bool isNumber = false; double eFixed = text.toDouble(&isNumber); if (!isNumber) { g_log.information("E Fixed is not a NUMBER! Value reset to default."); eFixed = 0; } else if (eFixed < 0) { g_log.information("E Fixed is negative, Value reset to default."); eFixed = 0; } setEFixed(eFixed); return eFixed; } /** * Set the EFixed value that is displayed in the UI. * * @param eFixed The new efixed value to display in the * UI. This must be positive, or the * displayed value will be set to zero. */ void EModeHandler::setEFixed(const double eFixed) { double newValue = eFixed; if (eFixed < 0) { g_log.information("E Fixed is negative, reset to default."); newValue = 0; } QtUtils::SetText(10, 4, newValue, m_svUI->efixed_control); } } // namespace SpectrumView } // namespace MantidQt
mganeva/mantid
qt/widgets/spectrumviewer/src/EModeHandler.cpp
C++
gpl-3.0
2,521
<?php // Website: WWW.OpenCartArab.com // E-Mail : info@OpenCartArab.com // Text $_['text_refine'] = 'الأقسام الفرعية'; $_['text_product'] = 'المنتجات'; $_['text_error'] = 'لم يتم العثور على القسم !'; $_['text_empty'] = 'لا توجد منتجات في هذا القسم .'; $_['text_quantity'] = 'الكمية:'; $_['text_manufacturer'] = 'الشركة:'; $_['text_model'] = 'النوع:'; $_['text_points'] = 'نقاط المكافآت:'; $_['text_price'] = 'السعر:'; $_['text_tax'] = 'السعر بدون ضريبة :'; $_['text_compare'] = 'مقارنة المنتج (%s)'; $_['text_sort'] = 'الفرز:'; $_['text_default'] = 'الافتراضي'; $_['text_name_asc'] = 'الإسم من أ - ي'; $_['text_name_desc'] = 'الإسم من ي - أ'; $_['text_price_asc'] = 'حسب السعر (منخفض &gt; مرتفع)'; $_['text_price_desc'] = 'حسب السعر (مرتفع &gt; منخفض)'; $_['text_rating_asc'] = 'تقييم (منخفض)'; $_['text_rating_desc'] = 'تقييم (مرتفع)'; $_['text_model_asc'] = 'النوع (أ - ي)'; $_['text_model_desc'] = 'النوع (ي - أ)'; $_['text_limit'] = 'عرض:'; $_['search'] = 'البحث'; $_['Go'] = 'ابدء'; $_['View1'] = ' اظهار الكل '; $_['Befor'] = 'قبل '; $_['please'] ='الرجاء الاختيار'; $_['View1'] = 'المشاهدات'; $_['article_no'] = ' رقم الموديل :'; $_['brand_name'] = 'اسم الموديل :'; $_['Most_Selling'] = 'الأكثر مبيعا'; $_['Most_Releated'] = 'الأكثر علاقة'; $_['Best_Match'] = 'الأكثر ترابط'; $_['select'] = 'اختر'; $_['go_cart'] = 'الذهاب الى البطاقة'; $_['related'] = 'المنتجات ذات الصلة' ; $_['pr'] = 'المنتجات ذات الصلة' ;
taylorsuccessor/baghli
catalog/language/arabic/product/category.php
PHP
gpl-3.0
2,047
# frozen_string_literal: true class SearchQuerySanitizationService ANYTHING_EXCEPT_NUMBERS_AND_SPACE_REGEX = /[^[[:digit:]] ]+/.freeze ANYTHING_EXCEPT_NUMBERS_SPACE_PERIOD_REGEX = /[^[[:digit:]]. ]+/.freeze ANYTHING_EXCEPT_NUMBERS_REGEX = /[^[[:digit:]]]+/.freeze ANYTHING_EXCEPT_LETTERS_NUMBERS_COMMON_PUNCTUATION_REGEX = /[^[[:alnum:]]āēīōūĀĒĪŌŪ\-() ']+/.freeze MAX_QUERY_TERM_LENGTH = 50 # characters ## # @param [ActionController::Parameters] params # @return [Hash] # def sanitize_for_standard_search(params) # rubocop:disable Metrics/AbcSize return {} if params.nil? clean_search_term = sanitize_search_term(params['s']) clean_handshape = sanitize_handshape(params['hs']) clean_body_location_fields = sanitize_body_location_fields(params['l']) clean_body_location_groups = sanitize_body_location_groups(params['lg']) clean_usage = sanitize_usage(params['usage']) clean_tag = sanitize_tag(params['tag']) result = {} result['s'] = [clean_search_term] unless clean_search_term.empty? result['hs'] = clean_handshape.split(' ') unless clean_handshape.empty? result['l'] = clean_body_location_fields.split(' ') unless clean_body_location_fields.empty? result['lg'] = clean_body_location_groups.split(' ') unless clean_body_location_groups.empty? result['usage'] = clean_usage.split(' ') unless clean_usage.empty? result['tag'] = clean_tag.split(' ') unless clean_tag.empty? result end def sanitize_for_autocomplete_search(term) sanitize_search_term(term) end private ## # @param [String] term # @return [String] # def sanitize_search_term(term) return '' if term.nil? term .gsub(ANYTHING_EXCEPT_LETTERS_NUMBERS_COMMON_PUNCTUATION_REGEX, '') .strip .truncate(MAX_QUERY_TERM_LENGTH, omission: '') end ## # @param [String] handshape # @return [String] # def sanitize_handshape(handshape) return '' if handshape.nil? handshape .gsub(ANYTHING_EXCEPT_NUMBERS_SPACE_PERIOD_REGEX, '') .strip .truncate(MAX_QUERY_TERM_LENGTH, omission: '') end ## # @param [String] body_location_fields # @return [String] # def sanitize_body_location_fields(body_location_fields) return '' if body_location_fields.nil? body_location_fields .gsub(ANYTHING_EXCEPT_NUMBERS_AND_SPACE_REGEX, '') .strip .truncate(MAX_QUERY_TERM_LENGTH, omission: '') end ## # @param [String] body_location_groups # @return [String] # def sanitize_body_location_groups(body_location_groups) return '' if body_location_groups.nil? body_location_groups .gsub(ANYTHING_EXCEPT_NUMBERS_AND_SPACE_REGEX, '') .strip .truncate(MAX_QUERY_TERM_LENGTH, omission: '') end ## # @param [String] usage # @return [String] # def sanitize_usage(usage) return '' if usage.nil? usage .gsub(ANYTHING_EXCEPT_NUMBERS_REGEX, '') .strip .truncate(MAX_QUERY_TERM_LENGTH, omission: '') end ## # @param [String] tag # @return [String] # def sanitize_tag(tag) return '' if tag.nil? tag .gsub(ANYTHING_EXCEPT_NUMBERS_AND_SPACE_REGEX, '') .strip .truncate(MAX_QUERY_TERM_LENGTH, omission: '') end end
rabid/nzsl-online
app/services/search_query_sanitization_service.rb
Ruby
gpl-3.0
3,401
--- layout: politician2 title: r chandrika kattakada profile: party: RPI constituency: Thiruvananthapuram state: Kerala education: level: 10th Pass details: p.d.c. from kerala university photo: sex: caste: religion: current-office-title: crime-accusation-instances: 0 date-of-birth: 1958 profession: networth: assets: 1,50,000 liabilities: pan: twitter: website: youtube-interview: wikipedia: candidature: - election: Lok Sabha 2014 myneta-link: http://myneta.info/ls2014/candidate.php?candidate_id=2512 affidavit-link: expenses-link: constituency: Thiruvananthapuram party: RPI criminal-cases: 0 assets: 1,50,000 liabilities: result: crime-record: date: 2014-01-28 version: 0.0.5 tags: --- ##Summary ##Education {% include "education.html" %} ##Political Career {% include "political-career.html" %} ##Criminal Record {% include "criminal-record.html" %} ##Personal Wealth {% include "personal-wealth.html" %} ##Public Office Track Record {% include "track-record.html" %} ##References {% include "references.html" %}
vaibhavb/wisevoter
site/politicians/_posts/2014-04-09-r-chandrika-kattakada.md
Markdown
gpl-3.0
1,149
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_65) on Fri Dec 27 15:04:02 EST 2013 --> <TITLE> LexicalChain </TITLE> <META NAME="date" CONTENT="2013-12-27"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="LexicalChain"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/LexicalChain.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV CLASS&nbsp; &nbsp;<A HREF="../lexicalChain/MetaChain.html" title="class in lexicalChain"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?lexicalChain/LexicalChain.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="LexicalChain.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> lexicalChain</FONT> <BR> Class LexicalChain</H2> <PRE> java.lang.Object <IMG SRC="../resources/inherit.gif" ALT="extended by "><B>lexicalChain.LexicalChain</B> </PRE> <HR> <DL> <DT><PRE>public class <B>LexicalChain</B><DT>extends java.lang.Object</DL> </PRE> <P> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.Integer</CODE></FONT></TD> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#END">END</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#STOPWORDS">STOPWORDS</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.lang.Integer</CODE></FONT></TD> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#USED">USED</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#LexicalChain()">LexicalChain</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Parameterless constructor, just loads ELKB and stopwords.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#LexicalChain(int)">LexicalChain</A></B>(int&nbsp;year)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;<I></I>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#LexicalChain(java.lang.String)">LexicalChain</A></B>(java.lang.String&nbsp;fileName)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This constructor takes a file as input and generates lexical chains out of the sentences in the file.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#LexicalChain(java.lang.String, int)">LexicalChain</A></B>(java.lang.String&nbsp;fileName, int&nbsp;year)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;<I></I>&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#buildLCFinal()">buildLCFinal</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;buildLCFinal: Final implementation of LexicalChain builder Attempt to build Lexical Chains a la Silber and McCoy</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#calculateHeadDistribution(java.util.TreeMap, java.lang.String)">calculateHeadDistribution</A></B>(java.util.TreeMap&lt;java.lang.Integer,java.util.TreeSet&lt;java.lang.String&gt;&gt;&nbsp;headDistri, java.lang.String&nbsp;word)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;calculateHeadDistribution: similar to previous method.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#loadStopWordList(java.lang.String)">loadStopWordList</A></B>(java.lang.String&nbsp;fname)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Loads a stoplics from a file with the name passed as an argument.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#main(java.lang.String[])">main</A></B>(java.lang.String[]&nbsp;args)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Main method creates lexical chains of the file passed as the first argument.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#printCandidateWords()">printCandidateWords</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printCandidateWords: method to display word & sentence line pairs contained in ASWL</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#printHeadDistri(java.util.TreeMap)">printHeadDistri</A></B>(java.util.TreeMap&lt;?,?&gt;&nbsp;headDistri)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printHeadDistri</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../lexicalChain/LexicalChain.html#printLCFinal(java.util.Collection)">printLCFinal</A></B>(java.util.Collection&lt;<A HREF="../lexicalChain/MetaChain.html" title="class in lexicalChain">MetaChain</A>&gt;&nbsp;chainSet)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;printLCFinal: method that prints a lexical chain</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="STOPWORDS"><!-- --></A><H3> STOPWORDS</H3> <PRE> public static final java.lang.String <B>STOPWORDS</B></PRE> <DL> <DL> <DT><B>See Also:</B><DD><A HREF="../constant-values.html#lexicalChain.LexicalChain.STOPWORDS">Constant Field Values</A></DL> </DL> <HR> <A NAME="USED"><!-- --></A><H3> USED</H3> <PRE> public static final java.lang.Integer <B>USED</B></PRE> <DL> <DL> </DL> </DL> <HR> <A NAME="END"><!-- --></A><H3> END</H3> <PRE> public static final java.lang.Integer <B>END</B></PRE> <DL> <DL> </DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="LexicalChain(int)"><!-- --></A><H3> LexicalChain</H3> <PRE> <FONT SIZE="-1">@Deprecated </FONT>public <B>LexicalChain</B>(int&nbsp;year)</PRE> <DL> <DD><B>Deprecated.</B>&nbsp;<I></I> <P> <DD>Parameterless constructor, just loads ELKB and stopwords. <P> <DL> <DT><B>Parameters:</B><DD><CODE>year</CODE> - </DL> </DL> <HR> <A NAME="LexicalChain()"><!-- --></A><H3> LexicalChain</H3> <PRE> public <B>LexicalChain</B>()</PRE> <DL> <DD>Parameterless constructor, just loads ELKB and stopwords. <P> </DL> <HR> <A NAME="LexicalChain(java.lang.String, int)"><!-- --></A><H3> LexicalChain</H3> <PRE> <FONT SIZE="-1">@Deprecated </FONT>public <B>LexicalChain</B>(java.lang.String&nbsp;fileName, int&nbsp;year)</PRE> <DL> <DD><B>Deprecated.</B>&nbsp;<I></I> <P> <DD>This constructor takes a file as input and generates lexical chains out of the sentences in the file. <P> <DL> <DT><B>Parameters:</B><DD><CODE>fileName</CODE> - <DD><CODE>year</CODE> - </DL> </DL> <HR> <A NAME="LexicalChain(java.lang.String)"><!-- --></A><H3> LexicalChain</H3> <PRE> public <B>LexicalChain</B>(java.lang.String&nbsp;fileName)</PRE> <DL> <DD>This constructor takes a file as input and generates lexical chains out of the sentences in the file. <P> <DL> <DT><B>Parameters:</B><DD><CODE>fileName</CODE> - </DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="main(java.lang.String[])"><!-- --></A><H3> main</H3> <PRE> public static void <B>main</B>(java.lang.String[]&nbsp;args)</PRE> <DL> <DD>Main method creates lexical chains of the file passed as the first argument. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>args</CODE> - </DL> </DD> </DL> <HR> <A NAME="loadStopWordList(java.lang.String)"><!-- --></A><H3> loadStopWordList</H3> <PRE> public void <B>loadStopWordList</B>(java.lang.String&nbsp;fname)</PRE> <DL> <DD>Loads a stoplics from a file with the name passed as an argument. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>fname</CODE> - </DL> </DD> </DL> <HR> <A NAME="printCandidateWords()"><!-- --></A><H3> printCandidateWords</H3> <PRE> public void <B>printCandidateWords</B>()</PRE> <DL> <DD>printCandidateWords: method to display word & sentence line pairs contained in ASWL <P> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="buildLCFinal()"><!-- --></A><H3> buildLCFinal</H3> <PRE> public void <B>buildLCFinal</B>()</PRE> <DL> <DD>buildLCFinal: Final implementation of LexicalChain builder Attempt to build Lexical Chains a la Silber and McCoy <P> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="printLCFinal(java.util.Collection)"><!-- --></A><H3> printLCFinal</H3> <PRE> public void <B>printLCFinal</B>(java.util.Collection&lt;<A HREF="../lexicalChain/MetaChain.html" title="class in lexicalChain">MetaChain</A>&gt;&nbsp;chainSet)</PRE> <DL> <DD>printLCFinal: method that prints a lexical chain <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>chainSet</CODE> - </DL> </DD> </DL> <HR> <A NAME="calculateHeadDistribution(java.util.TreeMap, java.lang.String)"><!-- --></A><H3> calculateHeadDistribution</H3> <PRE> public void <B>calculateHeadDistribution</B>(java.util.TreeMap&lt;java.lang.Integer,java.util.TreeSet&lt;java.lang.String&gt;&gt;&nbsp;headDistri, java.lang.String&nbsp;word)</PRE> <DL> <DD>calculateHeadDistribution: similar to previous method. Builds a TreeSet that inidcates which Head numbers and what words are used in the text <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>headDistri</CODE> - <DD><CODE>word</CODE> - </DL> </DD> </DL> <HR> <A NAME="printHeadDistri(java.util.TreeMap)"><!-- --></A><H3> printHeadDistri</H3> <PRE> public void <B>printHeadDistri</B>(java.util.TreeMap&lt;?,?&gt;&nbsp;headDistri)</PRE> <DL> <DD>printHeadDistri <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>headDistri</CODE> - </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/LexicalChain.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV CLASS&nbsp; &nbsp;<A HREF="../lexicalChain/MetaChain.html" title="class in lexicalChain"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?lexicalChain/LexicalChain.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="LexicalChain.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
boompieman/iim_project
open_rogets_1.4/doc/lexicalChain/LexicalChain.html
HTML
gpl-3.0
18,873
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0"> <title>ColReorder example - ColVis integration</title> <link rel="stylesheet" type="text/css" href="../../../media/css/jquery.dataTables.css"> <link rel="stylesheet" type="text/css" href="../css/dataTables.colReorder.css"> <link rel="stylesheet" type="text/css" href="../../ColVis/css/dataTables.colVis.css"> <link rel="stylesheet" type="text/css" href="../../../examples/resources/syntax/shCore.css"> <link rel="stylesheet" type="text/css" href="../../../examples/resources/demo.css"> <style type="text/css" class="init"> </style> <script type="text/javascript" language="javascript" src="../../../media/js/jquery.js"></script> <script type="text/javascript" language="javascript" src="../../../media/js/jquery.dataTables.js"></script> <script type="text/javascript" language="javascript" src="../js/dataTables.colReorder.js"></script> <script type="text/javascript" language="javascript" src="../../ColVis/js/dataTables.colVis.js"></script> <script type="text/javascript" language="javascript" src="../../../examples/resources/syntax/shCore.js"></script> <script type="text/javascript" language="javascript" src="../../../examples/resources/demo.js"></script> <script type="text/javascript" language="javascript" class="init"> $(document).ready(function() { var table = $('#example').DataTable({ dom: 'RC<"clear">lfrtip', columnDefs: [ {visible: false, targets: 1} ] }); }); </script> </head> <body class="dt-example"> <div class="container"> <section> <h1>ColReorder example <span>ColVis integration</span></h1> <div class="info"> <p>ColReorder interfaces with the <a href="//datatables.net/extensions/colvis">ColVis extension</a> for DataTables by updating the order of the list of columns whenever a reorder is done. This is shown in the example below, where one column has been initially hidden to add extra emphasis to ColVis.</p> </div> <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tfoot> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$320,800</td> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>66</td> <td>2009/01/12</td> <td>$86,000</td> </tr> <tr> <td>Cedric Kelly</td> <td>Senior Javascript Developer</td> <td>Edinburgh</td> <td>22</td> <td>2012/03/29</td> <td>$433,060</td> </tr> <tr> <td>Airi Satou</td> <td>Accountant</td> <td>Tokyo</td> <td>33</td> <td>2008/11/28</td> <td>$162,700</td> </tr> <tr> <td>Brielle Williamson</td> <td>Integration Specialist</td> <td>New York</td> <td>61</td> <td>2012/12/02</td> <td>$372,000</td> </tr> <tr> <td>Herrod Chandler</td> <td>Sales Assistant</td> <td>San Francisco</td> <td>59</td> <td>2012/08/06</td> <td>$137,500</td> </tr> <tr> <td>Rhona Davidson</td> <td>Integration Specialist</td> <td>Tokyo</td> <td>55</td> <td>2010/10/14</td> <td>$327,900</td> </tr> <tr> <td>Colleen Hurst</td> <td>Javascript Developer</td> <td>San Francisco</td> <td>39</td> <td>2009/09/15</td> <td>$205,500</td> </tr> <tr> <td>Sonya Frost</td> <td>Software Engineer</td> <td>Edinburgh</td> <td>23</td> <td>2008/12/13</td> <td>$103,600</td> </tr> <tr> <td>Jena Gaines</td> <td>Office Manager</td> <td>London</td> <td>30</td> <td>2008/12/19</td> <td>$90,560</td> </tr> <tr> <td>Quinn Flynn</td> <td>Support Lead</td> <td>Edinburgh</td> <td>22</td> <td>2013/03/03</td> <td>$342,000</td> </tr> <tr> <td>Charde Marshall</td> <td>Regional Director</td> <td>San Francisco</td> <td>36</td> <td>2008/10/16</td> <td>$470,600</td> </tr> <tr> <td>Haley Kennedy</td> <td>Senior Marketing Designer</td> <td>London</td> <td>43</td> <td>2012/12/18</td> <td>$313,500</td> </tr> <tr> <td>Tatyana Fitzpatrick</td> <td>Regional Director</td> <td>London</td> <td>19</td> <td>2010/03/17</td> <td>$385,750</td> </tr> <tr> <td>Michael Silva</td> <td>Marketing Designer</td> <td>London</td> <td>66</td> <td>2012/11/27</td> <td>$198,500</td> </tr> <tr> <td>Paul Byrd</td> <td>Chief Financial Officer (CFO)</td> <td>New York</td> <td>64</td> <td>2010/06/09</td> <td>$725,000</td> </tr> <tr> <td>Gloria Little</td> <td>Systems Administrator</td> <td>New York</td> <td>59</td> <td>2009/04/10</td> <td>$237,500</td> </tr> <tr> <td>Bradley Greer</td> <td>Software Engineer</td> <td>London</td> <td>41</td> <td>2012/10/13</td> <td>$132,000</td> </tr> <tr> <td>Dai Rios</td> <td>Personnel Lead</td> <td>Edinburgh</td> <td>35</td> <td>2012/09/26</td> <td>$217,500</td> </tr> <tr> <td>Jenette Caldwell</td> <td>Development Lead</td> <td>New York</td> <td>30</td> <td>2011/09/03</td> <td>$345,000</td> </tr> <tr> <td>Yuri Berry</td> <td>Chief Marketing Officer (CMO)</td> <td>New York</td> <td>40</td> <td>2009/06/25</td> <td>$675,000</td> </tr> <tr> <td>Caesar Vance</td> <td>Pre-Sales Support</td> <td>New York</td> <td>21</td> <td>2011/12/12</td> <td>$106,450</td> </tr> <tr> <td>Doris Wilder</td> <td>Sales Assistant</td> <td>Sidney</td> <td>23</td> <td>2010/09/20</td> <td>$85,600</td> </tr> <tr> <td>Angelica Ramos</td> <td>Chief Executive Officer (CEO)</td> <td>London</td> <td>47</td> <td>2009/10/09</td> <td>$1,200,000</td> </tr> <tr> <td>Gavin Joyce</td> <td>Developer</td> <td>Edinburgh</td> <td>42</td> <td>2010/12/22</td> <td>$92,575</td> </tr> <tr> <td>Jennifer Chang</td> <td>Regional Director</td> <td>Singapore</td> <td>28</td> <td>2010/11/14</td> <td>$357,650</td> </tr> <tr> <td>Brenden Wagner</td> <td>Software Engineer</td> <td>San Francisco</td> <td>28</td> <td>2011/06/07</td> <td>$206,850</td> </tr> <tr> <td>Fiona Green</td> <td>Chief Operating Officer (COO)</td> <td>San Francisco</td> <td>48</td> <td>2010/03/11</td> <td>$850,000</td> </tr> <tr> <td>Shou Itou</td> <td>Regional Marketing</td> <td>Tokyo</td> <td>20</td> <td>2011/08/14</td> <td>$163,000</td> </tr> <tr> <td>Michelle House</td> <td>Integration Specialist</td> <td>Sidney</td> <td>37</td> <td>2011/06/02</td> <td>$95,400</td> </tr> <tr> <td>Suki Burks</td> <td>Developer</td> <td>London</td> <td>53</td> <td>2009/10/22</td> <td>$114,500</td> </tr> <tr> <td>Prescott Bartlett</td> <td>Technical Author</td> <td>London</td> <td>27</td> <td>2011/05/07</td> <td>$145,000</td> </tr> <tr> <td>Gavin Cortez</td> <td>Team Leader</td> <td>San Francisco</td> <td>22</td> <td>2008/10/26</td> <td>$235,500</td> </tr> <tr> <td>Martena Mccray</td> <td>Post-Sales support</td> <td>Edinburgh</td> <td>46</td> <td>2011/03/09</td> <td>$324,050</td> </tr> <tr> <td>Unity Butler</td> <td>Marketing Designer</td> <td>San Francisco</td> <td>47</td> <td>2009/12/09</td> <td>$85,675</td> </tr> <tr> <td>Howard Hatfield</td> <td>Office Manager</td> <td>San Francisco</td> <td>51</td> <td>2008/12/16</td> <td>$164,500</td> </tr> <tr> <td>Hope Fuentes</td> <td>Secretary</td> <td>San Francisco</td> <td>41</td> <td>2010/02/12</td> <td>$109,850</td> </tr> <tr> <td>Vivian Harrell</td> <td>Financial Controller</td> <td>San Francisco</td> <td>62</td> <td>2009/02/14</td> <td>$452,500</td> </tr> <tr> <td>Timothy Mooney</td> <td>Office Manager</td> <td>London</td> <td>37</td> <td>2008/12/11</td> <td>$136,200</td> </tr> <tr> <td>Jackson Bradshaw</td> <td>Director</td> <td>New York</td> <td>65</td> <td>2008/09/26</td> <td>$645,750</td> </tr> <tr> <td>Olivia Liang</td> <td>Support Engineer</td> <td>Singapore</td> <td>64</td> <td>2011/02/03</td> <td>$234,500</td> </tr> <tr> <td>Bruno Nash</td> <td>Software Engineer</td> <td>London</td> <td>38</td> <td>2011/05/03</td> <td>$163,500</td> </tr> <tr> <td>Sakura Yamamoto</td> <td>Support Engineer</td> <td>Tokyo</td> <td>37</td> <td>2009/08/19</td> <td>$139,575</td> </tr> <tr> <td>Thor Walton</td> <td>Developer</td> <td>New York</td> <td>61</td> <td>2013/08/11</td> <td>$98,540</td> </tr> <tr> <td>Finn Camacho</td> <td>Support Engineer</td> <td>San Francisco</td> <td>47</td> <td>2009/07/07</td> <td>$87,500</td> </tr> <tr> <td>Serge Baldwin</td> <td>Data Coordinator</td> <td>Singapore</td> <td>64</td> <td>2012/04/09</td> <td>$138,575</td> </tr> <tr> <td>Zenaida Frank</td> <td>Software Engineer</td> <td>New York</td> <td>63</td> <td>2010/01/04</td> <td>$125,250</td> </tr> <tr> <td>Zorita Serrano</td> <td>Software Engineer</td> <td>San Francisco</td> <td>56</td> <td>2012/06/01</td> <td>$115,000</td> </tr> <tr> <td>Jennifer Acosta</td> <td>Junior Javascript Developer</td> <td>Edinburgh</td> <td>43</td> <td>2013/02/01</td> <td>$75,650</td> </tr> <tr> <td>Cara Stevens</td> <td>Sales Assistant</td> <td>New York</td> <td>46</td> <td>2011/12/06</td> <td>$145,600</td> </tr> <tr> <td>Hermione Butler</td> <td>Regional Director</td> <td>London</td> <td>47</td> <td>2011/03/21</td> <td>$356,250</td> </tr> <tr> <td>Lael Greer</td> <td>Systems Administrator</td> <td>London</td> <td>21</td> <td>2009/02/27</td> <td>$103,500</td> </tr> <tr> <td>Jonas Alexander</td> <td>Developer</td> <td>San Francisco</td> <td>30</td> <td>2010/07/14</td> <td>$86,500</td> </tr> <tr> <td>Shad Decker</td> <td>Regional Director</td> <td>Edinburgh</td> <td>51</td> <td>2008/11/13</td> <td>$183,000</td> </tr> <tr> <td>Michael Bruce</td> <td>Javascript Developer</td> <td>Singapore</td> <td>29</td> <td>2011/06/27</td> <td>$183,000</td> </tr> <tr> <td>Donna Snider</td> <td>Customer Support</td> <td>New York</td> <td>27</td> <td>2011/01/25</td> <td>$112,000</td> </tr> </tbody> </table> <ul class="tabs"> <li class="active">Javascript</li> <li>HTML</li> <li>CSS</li> <li>Ajax</li> <li>Server-side script</li> </ul> <div class="tabs"> <div class="js"> <p>The Javascript shown below is used to initialise the table shown in this example:</p><code class="multiline brush: js;">$(document).ready(function() { var table = $('#example').DataTable( { dom: 'RC&lt;&quot;clear&quot;&gt;lfrtip', columnDefs: [ { visible: false, targets: 1 } ] } ); } );</code> <p>In addition to the above code, the following Javascript library files are loaded for use in this example:</p> <ul> <li><a href="../../../media/js/jquery.js">../../../media/js/jquery.js</a></li> <li><a href= "../../../media/js/jquery.dataTables.js">../../../media/js/jquery.dataTables.js</a></li> <li><a href="../js/dataTables.colReorder.js">../js/dataTables.colReorder.js</a></li> <li><a href= "../../ColVis/js/dataTables.colVis.js">../../ColVis/js/dataTables.colVis.js</a></li> </ul> </div> <div class="table"> <p>The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:</p> </div> <div class="css"> <div> <p>This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The additional CSS used is shown below:</p><code class="multiline brush: js;"></code> </div> <p>The following CSS library files are loaded for use in this example to provide the styling of the table:</p> <ul> <li><a href= "../../../media/css/jquery.dataTables.css">../../../media/css/jquery.dataTables.css</a></li> <li><a href="../css/dataTables.colReorder.css">../css/dataTables.colReorder.css</a></li> <li><a href= "../../ColVis/css/dataTables.colVis.css">../../ColVis/css/dataTables.colVis.css</a></li> </ul> </div> <div class="ajax"> <p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is loaded.</p> </div> <div class="php"> <p>The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side processing scripts can be written in any language, using <a href="//datatables.net/manual/server-side">the protocol described in the DataTables documentation</a>.</p> </div> </div> </section> </div> <section> <div class="footer"> <div class="gradient"></div> <div class="liner"> <h2>Other examples</h2> <div class="toc"> <div class="toc-group"> <h3><a href="./index.html">Examples</a></h3> <ul class="toc active"> <li><a href="./simple.html">Basic initialisation</a></li> <li><a href="./new_init.html">Initialisation using `new`</a></li> <li><a href="./alt_insert.html">Alternative insert styling</a></li> <li><a href="./realtime.html">Realtime updating</a></li> <li><a href="./state_save.html">State saving</a></li> <li><a href="./scrolling.html">Scrolling table</a></li> <li><a href="./predefined.html">Predefined column ordering</a></li> <li><a href="./reset.html">Reset ordering API</a></li> <li class="active"><a href="./colvis.html">ColVis integration</a></li> <li><a href="./fixedcolumns.html">FixedColumns integration</a></li> <li><a href="./fixedheader.html">FixedHeader integration</a></li> <li><a href="./jqueryui.html">jQuery UI styling</a></li> <li><a href="./col_filter.html">Individual column filtering</a></li> <li><a href="./server_side.html">Server-side processing</a></li> </ul> </div> </div> <div class="epilogue"> <p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full information about its API properties and methods.<br> Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and <a href="http://www.datatables.net/plug-ins">plug-ins</a> which extend the capabilities of DataTables.</p> <p class="copyright">DataTables designed and created by <a href= "http://www.sprymedia.co.uk">SpryMedia Ltd</a> &#169; 2007-2014<br> DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p> </div> </div> </div> </section> </body> </html>
csalgadow/demokratian_2.x.x
modulos/DataTables-1.10.3/extensions/ColReorder/examples/colvis.html
HTML
gpl-3.0
29,826
{% extends "global/Page.html" %} {% load staticfiles otree_tags %} {% block title %} Partie 1 {% endblock %} {% block content %} <head> <style> table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even){background-color: #f2f2f2} th { background-color: #4CAF50; color: white; } </style> </head> <font size="5">Phase 2</font> <br> <br> {%if group.tableau_reverse_1 == 1%} <div class="form-group required"> <table class="table table-bordered" style="width:100%"> <tr> <th colspan = 3 class="text-center">Prenez vos décisions</th> </tr> <tr> <th class="text-center">Option A</th><th class="text-center">Option B</th><th class="text-center" width="20%">Vos décisions ?</th> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 10 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_13 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 9,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_12 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 9 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_11 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 8,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_10 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 8 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_9 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 7,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_8 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 7 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_7 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 6,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_6 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 6 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_5 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 5,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_4 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_3 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 4,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_2 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 4 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_1 %}</td> </tr> </table> {% elif group.tableau_reverse_1 == 0 %} <div class="form-group required"> <table class="table table-bordered" style="width:100%"> <tr> <th colspan = 3 class="text-center">Prenez vos décisions</th> </tr> <tr> <th class="text-center">Option A</th><th class="text-center">Option B</th><th class="text-center" width="20%">Vos décisions ?</th> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 4 euros et B gagne 3 euros de manière certaine</td> <td colspan = 3>{% formfield player.tab_1_1 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 4,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_2 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_3 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 5,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_4 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 6 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_5 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 6,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_6 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 7 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_7 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 7,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_8 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 8 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_9 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 8,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_10 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 9 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_11 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 9,5 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_12 %}</td> </tr> <tr> <td><ul><li>50% que vous gagnez 4 euros et que B gagne 3 euros;</li> <li>50% que vous gagnez 10 euros et que B gagne 3 euros </li></ul></td> <td>Vous gagnez 10 euros et B gagne 3 euros de manière certaine</td> <td>{% formfield player.tab_1_13 %}</td> </tr> </table> </div> {%endif%} <div> <button class="btn btn-primary btn-large">Suivant</button> </div> {% endblock %}
anthropo-lab/XP
Fabrice_equiv_certain/templates/Fabrice_equiv_certain/Tableau_1_1.html
HTML
gpl-3.0
10,016
# Makefile.in generated by automake 1.11 from Makefile.am. # man/Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, # Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. pkgdatadir = $(datadir)/chordii pkgincludedir = $(includedir)/chordii pkglibdir = $(libdir)/chordii pkglibexecdir = $(libexecdir)/chordii am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : subdir = man DIST_COMMON = $(dist_man_MANS) $(srcdir)/Makefile.am \ $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/src/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = SOURCES = DIST_SOURCES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' man1dir = $(mandir)/man1 am__installdirs = "$(DESTDIR)$(man1dir)" NROFF = nroff MANS = $(dist_man_MANS) $(man_MANS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = ${SHELL} U:/progetti/chordii-4.3/missing --run aclocal-1.11 ALLOCA = AMTAR = tar.exe AUTOCONF = ${SHELL} U:/progetti/chordii-4.3/missing --run autoconf AUTOHEADER = ${SHELL} U:/progetti/chordii-4.3/missing --run autoheader AUTOMAKE = ${SHELL} U:/progetti/chordii-4.3/missing --run automake-1.11 AWK = gawk CC = gcc CCDEPMODE = depmode=gcc3 CFLAGS = -D__EMX__ -DOS2 -D__ST_MT_ERRNO__ -g -Wall -Werror -pedantic-errors -g CPP = gcc -E CPPFLAGS = CYGPATH_W = echo DEFS = -DHAVE_CONFIG_H DEPDIR = .deps ECHO_C = ECHO_N = -n ECHO_T = EGREP = U:/MOZTOOLS/grep.exe -E EXEEXT = .exe GREP = U:/MOZTOOLS/grep.exe INSTALL = u:/bin/install.exe INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s LDFLAGS = -Zexe -Zomf -Zmap -Zargs-wild -D__ST_MT_ERRNO__ LIBOBJS = ${LIBOBJDIR}X$U.o ${LIBOBJDIR}$CC$U.o ${LIBOBJDIR}-c$U.o ${LIBOBJDIR}$CFLAGS$U.o ${LIBOBJDIR}$CPPFLAGS$U.o ${LIBOBJDIR}conftest.$ac_ext$U.o ${LIBOBJDIR}>&5$U.o LIBS = LTLIBOBJS = ${LIBOBJDIR}X$U.lo ${LIBOBJDIR}$CC$U.lo ${LIBOBJDIR}-c$U.lo ${LIBOBJDIR}$CFLAGS$U.lo ${LIBOBJDIR}$CPPFLAGS$U.lo ${LIBOBJDIR}conftest.$ac_ext$U.lo ${LIBOBJDIR}>&5$U.lo MAKEINFO = makeinfo --no-split MKDIR_P = u:/bin/mkdir.exe -p OBJEXT = o PACKAGE = chordii PACKAGE_BUGREPORT = jvromans@users.sourceforge.net PACKAGE_NAME = Chordii PACKAGE_STRING = Chordii 4.3 PACKAGE_TARNAME = chordii PACKAGE_VERSION = 4.3 PATCH_LEVEL = 0 PATH_SEPARATOR = ; SET_MAKE = SHELL = sh STRIP = VERSION = 4.3 abs_builddir = U:/progetti/chordii-4.3/man abs_srcdir = U:/progetti/chordii-4.3/man abs_top_builddir = U:/progetti/chordii-4.3 abs_top_srcdir = U:/progetti/chordii-4.3 ac_ct_CC = gcc am__include = include am__leading_dot = . am__quote = am__tar = ${AMTAR} chof - "$$tardir" am__untar = ${AMTAR} xf - bindir = ${exec_prefix}/bin build_alias = builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host_alias = htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = ${SHELL} U:/progetti/chordii-4.3/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = u:/bin/mkdir.exe -p oldincludedir = /usr/include pdfdir = ${docdir} prefix = /usr/local program_transform_name = s,x,x, psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target_alias = top_build_prefix = ../ top_builddir = .. top_srcdir = .. dist_man_MANS = chordii.1 a2crd.1 man_MANS = chordii.1 a2crd.1 all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu man/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu man/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-man1: $(dist_man_MANS) $(man_MANS) @$(NORMAL_INSTALL) test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)" @list=''; test -n "$(man1dir)" || exit 0; \ { for i in $$list; do echo "$$i"; done; \ l2='$(dist_man_MANS) $(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.1[a-z]*$$/p'; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \ done; } uninstall-man1: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man1dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(dist_man_MANS) $(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.1[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ test -z "$$files" || { \ echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(man1dir)" && rm -f $$files; } tags: TAGS TAGS: ctags: CTAGS CTAGS: distdir: $(DISTFILES) @list='$(MANS)'; if test -n "$$list"; then \ list=`for p in $$list; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \ if test -n "$$list" && \ grep 'ab help2man is required to generate this page' $$list >/dev/null; then \ echo "error: found man pages containing the \`missing help2man' replacement text:" >&2; \ grep -l 'ab help2man is required to generate this page' $$list | sed 's/^/ /' >&2; \ echo " to fix them, install help2man, remove and regenerate the man pages;" >&2; \ echo " typically \`make maintainer-clean' will remove them" >&2; \ exit 1; \ else :; fi; \ else :; fi @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(MANS) installdirs: for dir in "$(DESTDIR)$(man1dir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ `test -z '$(STRIP)' || \ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-generic mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-man install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man1 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-man uninstall-man: uninstall-man1 .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic distclean \ distclean-generic distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-man1 install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic pdf pdf-am ps ps-am uninstall \ uninstall-am uninstall-man uninstall-man1 # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
OS2World/MM-UTIL-ChordII
man/Makefile
Makefile
gpl-3.0
12,848
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CR4ResourceDefinitionsDLCMounter : IGameplayDLCMounter { [Ordinal(1)] [RED("resourceDefinitionXmlFilePath")] public CString ResourceDefinitionXmlFilePath { get; set;} public CR4ResourceDefinitionsDLCMounter(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CR4ResourceDefinitionsDLCMounter(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
Traderain/Wolven-kit
WolvenKit.CR2W/Types/W3/RTTIConvert/CR4ResourceDefinitionsDLCMounter.cs
C#
gpl-3.0
833
/* * mssql.cpp * * Created on: Jul 20, 2012 * Author: lion */ #include "object.h" #include "ifs/db.h" #ifdef _WIN32 #include "mssql.h" #include "Url.h" #include "DBResult.h" #include "Buffer.h" #include "date.h" #include "trans.h" namespace fibjs { result_t db_base::openMSSQL(exlib::string connString, obj_ptr<MSSQL_base>& retVal, AsyncEvent* ac) { if (ac->isSync()) return CHECK_ERROR(CALL_E_LONGSYNC); if (qstrcmp(connString.c_str(), "mssql:", 6)) return CHECK_ERROR(CALL_E_INVALIDARG); obj_ptr<Url> u = new Url(); result_t hr = u->parse(connString); if (hr < 0) return hr; obj_ptr<mssql> conn = new mssql(); hr = conn->connect(u->m_hostname.c_str(), u->m_username.c_str(), u->m_password.c_str(), u->m_pathname.length() > 0 ? u->m_pathname.c_str() + 1 : ""); if (hr < 0) return hr; retVal = conn; return 0; } static result_t close_conn(ADODB::_Connection* conn) { conn->Close(); conn->Release(); return 0; } mssql::~mssql() { if (m_conn) { asyncCall(close_conn, m_conn); m_conn = NULL; } } result_t mssql::connect(const char* server, const char* username, const char* password, const char* dbName) { if (m_conn) return CHECK_ERROR(CALL_E_INVALID_CALL); HRESULT hr; hr = CoCreateInstance(__uuidof(ADODB::Connection), NULL, CLSCTX_INPROC_SERVER, __uuidof(ADODB::_Connection), (void**)&m_conn); if (FAILED(hr)) return hr; exlib::string connStr; connStr.append("Provider=\'sqloledb\';Data Source=\'"); connStr.append(server); connStr.append("\';Initial Catalog=\'"); connStr.append(*dbName ? dbName : "master"); connStr.append("\';"); bstr_t bstrConn(UTF8_W(connStr)); bstr_t bstrUser(UTF8_W(username)); bstr_t bstrPass(UTF8_W(password)); hr = m_conn->Open(bstrConn, bstrUser, bstrPass, ADODB::adConnectUnspecified); if (FAILED(hr)) return error(hr); m_conn->put_CommandTimeout(0); return 0; } result_t mssql::get_type(exlib::string& retVal) { retVal = "mssql"; return 0; } result_t mssql::close(AsyncEvent* ac) { if (!m_conn) return CHECK_ERROR(CALL_E_INVALID_CALL); if (ac->isSync()) return CHECK_ERROR(CALL_E_LONGSYNC); m_conn->Close(); m_conn->Release(); m_conn = NULL; return 0; } result_t mssql::use(exlib::string dbName, AsyncEvent* ac) { if (!m_conn) return CHECK_ERROR(CALL_E_INVALID_CALL); if (ac->isSync()) return CHECK_ERROR(CALL_E_LONGSYNC); bstr_t bstrName(utf8to16String(dbName).c_str()); HRESULT hr; hr = m_conn->put_DefaultDatabase(bstrName); if (FAILED(hr)) return error(hr); return 0; } result_t mssql::begin(AsyncEvent* ac) { if (!m_conn) return CHECK_ERROR(CALL_E_INVALID_CALL); if (ac->isSync()) return CHECK_ERROR(CALL_E_LONGSYNC); HRESULT hr; long level = 0; hr = m_conn->BeginTrans(&level); if (FAILED(hr)) return error(hr); return 0; } result_t mssql::commit(AsyncEvent* ac) { if (!m_conn) return CHECK_ERROR(CALL_E_INVALID_CALL); if (ac->isSync()) return CHECK_ERROR(CALL_E_LONGSYNC); HRESULT hr; hr = m_conn->CommitTrans(); if (FAILED(hr)) return error(hr); return 0; } result_t mssql::rollback(AsyncEvent* ac) { if (!m_conn) return CHECK_ERROR(CALL_E_INVALID_CALL); if (ac->isSync()) return CHECK_ERROR(CALL_E_LONGSYNC); HRESULT hr; hr = m_conn->RollbackTrans(); if (FAILED(hr)) return error(hr); return 0; } result_t mssql::trans(v8::Local<v8::Function> func) { return _trans(this, func); } result_t mssql::execute(const char* sql, int32_t sLen, obj_ptr<object_base>& retVal) { if (!m_conn) return CHECK_ERROR(CALL_E_INVALID_CALL); HRESULT hr; ADODB::_Recordset* rs = NULL; bstr_t bstrCom(utf8to16String(sql, sLen).c_str()); _variant_t affected((long)0); hr = m_conn->Execute(bstrCom, &affected, ADODB::adCmdText, &rs); if (FAILED(hr)) return error(hr); obj_ptr<DBResult> res; VARIANT_BOOL bEof = VARIANT_TRUE; rs->get_adoEOF(&bEof); if (bEof == VARIANT_FALSE) { ADODB::Fields* fields = NULL; rs->get_Fields(&fields); if (FAILED(hr)) { rs->Release(); return error(hr); } long columns; fields->get_Count(&columns); if (columns > 0) { int32_t i; res = new DBResult(columns); for (i = 0; i < columns; i++) { ADODB::Field* field = NULL; _variant_t vi((long)i); BSTR bstrName = NULL; fields->get_Item(vi, &field); field->get_Name(&bstrName); res->setField(i, utf16to8String(bstrName)); SysFreeString(bstrName); field->Release(); } while (bEof == VARIANT_FALSE) { int32_t i; res->beginRow(); for (i = 0; i < columns; i++) { Variant v; ADODB::Field* field = NULL; _variant_t vi((long)i); fields->get_Item(vi, &field); if (field) { _variant_t value; field->get_Value(&value); switch (value.vt) { case VT_NULL: v.setNull(); break; case VT_BOOL: v = (value.boolVal != VARIANT_FALSE); break; case VT_I2: v = value.iVal; break; case VT_UI2: v = value.uiVal; break; case VT_I4: case VT_INT: v = value.lVal; break; case VT_UI4: case VT_UINT: v = (int64_t)value.ulVal; break; case VT_R4: v = value.dblVal; break; case VT_BSTR: v = utf16to8String(value.bstrVal); break; case VT_DATE: { date_t d; SYSTEMTIME st; VariantTimeToSystemTime(value.date, &st); d.create(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); d.toUTC(); v = d; break; } case VT_DECIMAL: { double myDouble = value; v = myDouble; break; } case VT_UI1 | VT_ARRAY: v = new Buffer(value.parray->pvData, value.parray->rgsabound[0].cElements); break; } field->Release(); } res->rowValue(i, v); } res->endRow(); rs->MoveNext(); rs->get_adoEOF(&bEof); } } else res = new DBResult(0, affected); fields->Release(); } else res = new DBResult(0, affected); rs->Release(); retVal = res; return 0; } result_t mssql::execute(exlib::string sql, obj_ptr<object_base>& retVal, AsyncEvent* ac) { if (!m_conn) return CHECK_ERROR(CALL_E_INVALID_CALL); if (ac->isSync()) return CHECK_ERROR(CALL_E_LONGSYNC); return execute(sql.c_str(), (int32_t)sql.length(), retVal); } result_t mssql::execute(exlib::string sql, OptArgs args, obj_ptr<object_base>& retVal, AsyncEvent* ac) { if (!m_conn) return CHECK_ERROR(CALL_E_INVALID_CALL); if (ac->isSync()) { exlib::string str; result_t hr = format(sql, args, str); if (hr < 0) return hr; ac->m_ctx.resize(1); ac->m_ctx[0] = str; return CHECK_ERROR(CALL_E_NOSYNC); } exlib::string str = ac->m_ctx[0].string(); return execute(str, retVal, ac); } result_t mssql::format(exlib::string sql, OptArgs args, exlib::string& retVal) { return db_base::formatMSSQL(sql, args, retVal); } } /* namespace fibjs */ #else namespace fibjs { result_t db_base::openMSSQL(exlib::string connString, obj_ptr<MSSQL_base>& retVal, AsyncEvent* ac) { return CALL_E_INVALIDARG; } } /* namespace fibjs */ #endif
onceyoung/fibjs
fibjs/src/db/sql/mssql.cpp
C++
gpl-3.0
9,056
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>LPCOpen Platform for LPC18XX/43XX microcontrollers: C:/w/lpcopen_docs/software/lpc_core/lpc_board/board_common/lpc_phy_dp83848.c Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="driver.png"/></td> <td style="padding-left: 0.5em;"> <div id="projectname">LPCOpen Platform for LPC18XX/43XX microcontrollers &#160;<span id="projectnumber">18XX43XX</span> </div> <div id="projectbrief">LPCOpen Platform for the NXP LPC18XX/43XX family of Microcontrollers</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_c8fa76d8dc1b9e06ff8aeb3121608b1b.html">software</a></li><li class="navelem"><a class="el" href="dir_b7e4ec23273c3b0265e149bb747aff2e.html">lpc_core</a></li><li class="navelem"><a class="el" href="dir_003cbb7b0f3d4f0c2b47ccca24fcb1b3.html">lpc_board</a></li><li class="navelem"><a class="el" href="dir_eac8694f2535cf18627cc7f1050847f8.html">board_common</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">lpc_phy_dp83848.c</div> </div> </div><!--header--> <div class="contents"> <a href="lpc__phy__dp83848_8c.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span>&#160;<span class="comment">/*</span></div> <div class="line"><a name="l00002"></a><span class="lineno"> 2</span>&#160;<span class="comment"> * @brief Mational DP83848 simple PHY driver</span></div> <div class="line"><a name="l00003"></a><span class="lineno"> 3</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00004"></a><span class="lineno"> 4</span>&#160;<span class="comment"> * @note</span></div> <div class="line"><a name="l00005"></a><span class="lineno"> 5</span>&#160;<span class="comment"> * Copyright(C) NXP Semiconductors, 2012</span></div> <div class="line"><a name="l00006"></a><span class="lineno"> 6</span>&#160;<span class="comment"> * All rights reserved.</span></div> <div class="line"><a name="l00007"></a><span class="lineno"> 7</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00008"></a><span class="lineno"> 8</span>&#160;<span class="comment"> * @par</span></div> <div class="line"><a name="l00009"></a><span class="lineno"> 9</span>&#160;<span class="comment"> * Software that is described herein is for illustrative purposes only</span></div> <div class="line"><a name="l00010"></a><span class="lineno"> 10</span>&#160;<span class="comment"> * which provides customers with programming information regarding the</span></div> <div class="line"><a name="l00011"></a><span class="lineno"> 11</span>&#160;<span class="comment"> * LPC products. This software is supplied &quot;AS IS&quot; without any warranties of</span></div> <div class="line"><a name="l00012"></a><span class="lineno"> 12</span>&#160;<span class="comment"> * any kind, and NXP Semiconductors and its licensor disclaim any and</span></div> <div class="line"><a name="l00013"></a><span class="lineno"> 13</span>&#160;<span class="comment"> * all warranties, express or implied, including all implied warranties of</span></div> <div class="line"><a name="l00014"></a><span class="lineno"> 14</span>&#160;<span class="comment"> * merchantability, fitness for a particular purpose and non-infringement of</span></div> <div class="line"><a name="l00015"></a><span class="lineno"> 15</span>&#160;<span class="comment"> * intellectual property rights. NXP Semiconductors assumes no responsibility</span></div> <div class="line"><a name="l00016"></a><span class="lineno"> 16</span>&#160;<span class="comment"> * or liability for the use of the software, conveys no license or rights under any</span></div> <div class="line"><a name="l00017"></a><span class="lineno"> 17</span>&#160;<span class="comment"> * patent, copyright, mask work right, or any other intellectual property rights in</span></div> <div class="line"><a name="l00018"></a><span class="lineno"> 18</span>&#160;<span class="comment"> * or to any products. NXP Semiconductors reserves the right to make changes</span></div> <div class="line"><a name="l00019"></a><span class="lineno"> 19</span>&#160;<span class="comment"> * in the software without notification. NXP Semiconductors also makes no</span></div> <div class="line"><a name="l00020"></a><span class="lineno"> 20</span>&#160;<span class="comment"> * representation or warranty that such application will be suitable for the</span></div> <div class="line"><a name="l00021"></a><span class="lineno"> 21</span>&#160;<span class="comment"> * specified use without further testing or modification.</span></div> <div class="line"><a name="l00022"></a><span class="lineno"> 22</span>&#160;<span class="comment"> *</span></div> <div class="line"><a name="l00023"></a><span class="lineno"> 23</span>&#160;<span class="comment"> * @par</span></div> <div class="line"><a name="l00024"></a><span class="lineno"> 24</span>&#160;<span class="comment"> * Permission to use, copy, modify, and distribute this software and its</span></div> <div class="line"><a name="l00025"></a><span class="lineno"> 25</span>&#160;<span class="comment"> * documentation is hereby granted, under NXP Semiconductors&#39; and its</span></div> <div class="line"><a name="l00026"></a><span class="lineno"> 26</span>&#160;<span class="comment"> * licensor&#39;s relevant copyrights in the software, without fee, provided that it</span></div> <div class="line"><a name="l00027"></a><span class="lineno"> 27</span>&#160;<span class="comment"> * is used in conjunction with NXP Semiconductors microcontrollers. This</span></div> <div class="line"><a name="l00028"></a><span class="lineno"> 28</span>&#160;<span class="comment"> * copyright, permission, and disclaimer notice must appear in all copies of</span></div> <div class="line"><a name="l00029"></a><span class="lineno"> 29</span>&#160;<span class="comment"> * this code.</span></div> <div class="line"><a name="l00030"></a><span class="lineno"> 30</span>&#160;<span class="comment"> */</span></div> <div class="line"><a name="l00031"></a><span class="lineno"> 31</span>&#160;</div> <div class="line"><a name="l00032"></a><span class="lineno"> 32</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="chip_8h.html">chip.h</a>&quot;</span></div> <div class="line"><a name="l00033"></a><span class="lineno"> 33</span>&#160;<span class="preprocessor">#include &quot;<a class="code" href="lpc__phy_8h.html">lpc_phy.h</a>&quot;</span></div> <div class="line"><a name="l00034"></a><span class="lineno"> 34</span>&#160;</div> <div class="line"><a name="l00043"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga892a7317d57dda903e52c7cd54b73cec"> 43</a></span>&#160;<span class="preprocessor">#define DP8_BMCR_REG 0x0 </span></div> <div class="line"><a name="l00044"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gacf21a2e57a97bc0e44b650cba5d79b49"> 44</a></span>&#160;<span class="preprocessor">#define DP8_BMSR_REG 0x1 </span></div> <div class="line"><a name="l00045"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga80c3e5080467615187ae7526d10e248e"> 45</a></span>&#160;<span class="preprocessor">#define DP8_ANADV_REG 0x4 </span></div> <div class="line"><a name="l00046"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga49bc191d8d7440d62a6475581a8b989b"> 46</a></span>&#160;<span class="preprocessor">#define DP8_ANLPA_REG 0x5 </span></div> <div class="line"><a name="l00047"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga4234b76a387261d2924d9b2f18c589a4"> 47</a></span>&#160;<span class="preprocessor">#define DP8_ANEEXP_REG 0x6 </span></div> <div class="line"><a name="l00048"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga187972bb76c6452082fe5d8871646c3c"> 48</a></span>&#160;<span class="preprocessor">#define DP8_PHY_STAT_REG 0x10</span></div> <div class="line"><a name="l00049"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gae7fdb2d7a16d0e8e05b637808e490d99"> 49</a></span>&#160;<span class="preprocessor">#define DP8_PHY_INT_CTL_REG 0x11</span></div> <div class="line"><a name="l00050"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gadf696963d0abbb4beb829fc973495b7f"> 50</a></span>&#160;<span class="preprocessor">#define DP8_PHY_RBR_REG 0x17</span></div> <div class="line"><a name="l00051"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga39507933324751d088fba401c476695a"> 51</a></span>&#160;<span class="preprocessor">#define DP8_PHY_STS_REG 0x19</span></div> <div class="line"><a name="l00053"></a><span class="lineno"> 53</span>&#160;<span class="preprocessor"></span><span class="comment">/* DP83848 Control register definitions */</span><span class="preprocessor"></span></div> <div class="line"><a name="l00054"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga20124f1992fe8442bf86336e5eb3f8c9"> 54</a></span>&#160;<span class="preprocessor"></span><span class="preprocessor">#define DP8_RESET (1 &lt;&lt; 15) </span></div> <div class="line"><a name="l00055"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga715fe70306d013e46711ae3af8c731ce"> 55</a></span>&#160;<span class="preprocessor">#define DP8_LOOPBACK (1 &lt;&lt; 14) </span></div> <div class="line"><a name="l00056"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga41b97dcb346e3bbe4030dcb461d83dc5"> 56</a></span>&#160;<span class="preprocessor">#define DP8_SPEED_SELECT (1 &lt;&lt; 13) </span></div> <div class="line"><a name="l00057"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga11fb5024f522364daffa86d8aa3e686a"> 57</a></span>&#160;<span class="preprocessor">#define DP8_AUTONEG (1 &lt;&lt; 12) </span></div> <div class="line"><a name="l00058"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gac133bb396b83069bf1628cbbcabbd902"> 58</a></span>&#160;<span class="preprocessor">#define DP8_POWER_DOWN (1 &lt;&lt; 11) </span></div> <div class="line"><a name="l00059"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga54c847ec7406c074d4c866a8cff14a90"> 59</a></span>&#160;<span class="preprocessor">#define DP8_ISOLATE (1 &lt;&lt; 10) </span></div> <div class="line"><a name="l00060"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gabead2c0e6ef31985969b58c501e24e7e"> 60</a></span>&#160;<span class="preprocessor">#define DP8_RESTART_AUTONEG (1 &lt;&lt; 9) </span></div> <div class="line"><a name="l00061"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga0775ca4632435fb4263758dd0d49e03f"> 61</a></span>&#160;<span class="preprocessor">#define DP8_DUPLEX_MODE (1 &lt;&lt; 8) </span></div> <div class="line"><a name="l00062"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gaf57a3f3da27b7f6427d144dfbc501d7e"> 62</a></span>&#160;<span class="preprocessor">#define DP8_COLLISION_TEST (1 &lt;&lt; 7) </span></div> <div class="line"><a name="l00064"></a><span class="lineno"> 64</span>&#160;<span class="preprocessor"></span><span class="comment">/* DP83848 Status register definitions */</span><span class="preprocessor"></span></div> <div class="line"><a name="l00065"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga7f1e5de3982e895b3081e31036836be7"> 65</a></span>&#160;<span class="preprocessor"></span><span class="preprocessor">#define DP8_100BASE_T4 (1 &lt;&lt; 15) </span></div> <div class="line"><a name="l00066"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga22a4620d78b443d894d52f0bba51cdb4"> 66</a></span>&#160;<span class="preprocessor">#define DP8_100BASE_TX_FD (1 &lt;&lt; 14) </span></div> <div class="line"><a name="l00067"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gae061d49146212257ca8b65348f70c6c6"> 67</a></span>&#160;<span class="preprocessor">#define DP8_100BASE_TX_HD (1 &lt;&lt; 13) </span></div> <div class="line"><a name="l00068"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga549cbee4d79031ebad4d5afbc350b30e"> 68</a></span>&#160;<span class="preprocessor">#define DP8_10BASE_T_FD (1 &lt;&lt; 12) </span></div> <div class="line"><a name="l00069"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gaf0bfc15858ca34be66e8b7e005c892bf"> 69</a></span>&#160;<span class="preprocessor">#define DP8_10BASE_T_HD (1 &lt;&lt; 11) </span></div> <div class="line"><a name="l00070"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gae5c797e525b9c95825f180731891006b"> 70</a></span>&#160;<span class="preprocessor">#define DP8_MF_PREAMB_SUPPR (1 &lt;&lt; 6) </span></div> <div class="line"><a name="l00071"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gaac8d664dec8b7071562e733c9cb0b5d9"> 71</a></span>&#160;<span class="preprocessor">#define DP8_AUTONEG_COMP (1 &lt;&lt; 5) </span></div> <div class="line"><a name="l00072"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga4a4b19b91c08b3c298db4a74ac6be272"> 72</a></span>&#160;<span class="preprocessor">#define DP8_RMT_FAULT (1 &lt;&lt; 4) </span></div> <div class="line"><a name="l00073"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga51cabf99606cab37dd5ecc8e563ed473"> 73</a></span>&#160;<span class="preprocessor">#define DP8_AUTONEG_ABILITY (1 &lt;&lt; 3) </span></div> <div class="line"><a name="l00074"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga12aedc69b7be38d04be703c0a505297f"> 74</a></span>&#160;<span class="preprocessor">#define DP8_LINK_STATUS (1 &lt;&lt; 2) </span></div> <div class="line"><a name="l00075"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gac2894a7f13f719b080de703653413523"> 75</a></span>&#160;<span class="preprocessor">#define DP8_JABBER_DETECT (1 &lt;&lt; 1) </span></div> <div class="line"><a name="l00076"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gac9dd005b401c7ed79341bce193ea5b8e"> 76</a></span>&#160;<span class="preprocessor">#define DP8_EXTEND_CAPAB (1 &lt;&lt; 0) </span></div> <div class="line"><a name="l00078"></a><span class="lineno"> 78</span>&#160;<span class="preprocessor"></span><span class="comment">/* DP83848 PHY RBR MII dode definitions */</span><span class="preprocessor"></span></div> <div class="line"><a name="l00079"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga0add7cbf634b4f110bbf5b3252581535"> 79</a></span>&#160;<span class="preprocessor"></span><span class="preprocessor">#define DP8_RBR_RMII_MODE (1 &lt;&lt; 5) </span></div> <div class="line"><a name="l00081"></a><span class="lineno"> 81</span>&#160;<span class="preprocessor"></span><span class="comment">/* DP83848 PHY status definitions */</span><span class="preprocessor"></span></div> <div class="line"><a name="l00082"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gabeaac10c0efedc94c7662b95c42ab6b3"> 82</a></span>&#160;<span class="preprocessor"></span><span class="preprocessor">#define DP8_REMOTEFAULT (1 &lt;&lt; 6) </span></div> <div class="line"><a name="l00083"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gaa96c2ae7a3f76bf6ef26ad549c0ba348"> 83</a></span>&#160;<span class="preprocessor">#define DP8_FULLDUPLEX (1 &lt;&lt; 2) </span></div> <div class="line"><a name="l00084"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga90ee3d108a5f6db2f94d55c90b8484bd"> 84</a></span>&#160;<span class="preprocessor">#define DP8_SPEED10MBPS (1 &lt;&lt; 1) </span></div> <div class="line"><a name="l00085"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga0216e81b2b460c1f6b1c739badb2a27a"> 85</a></span>&#160;<span class="preprocessor">#define DP8_VALID_LINK (1 &lt;&lt; 0) </span></div> <div class="line"><a name="l00087"></a><span class="lineno"> 87</span>&#160;<span class="preprocessor"></span><span class="comment">/* DP83848 PHY ID register definitions */</span><span class="preprocessor"></span></div> <div class="line"><a name="l00088"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga38f995f0d1a9524c0a62ee6c32880b07"> 88</a></span>&#160;<span class="preprocessor"></span><span class="preprocessor">#define DP8_PHYID1_OUI 0x2000 </span></div> <div class="line"><a name="l00089"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gaccd78f910c8655f6ca404e2458147d90"> 89</a></span>&#160;<span class="preprocessor">#define DP8_PHYID2_OUI 0x5c90 </span></div> <div class="line"><a name="l00091"></a><span class="lineno"> 91</span>&#160;<span class="preprocessor"></span><span class="comment">/* DP83848 PHY update flags */</span><span class="preprocessor"></span></div> <div class="line"><a name="l00092"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460"> 92</a></span>&#160;<span class="preprocessor"></span><span class="keyword">static</span> uint32_t <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a>, <a class="code" href="group___d_p83848___p_h_y.html#ga0cf36f6bdb20115a22ef1478d47f7dec">olddphysts</a>;</div> <div class="line"><a name="l00093"></a><span class="lineno"> 93</span>&#160;</div> <div class="line"><a name="l00094"></a><span class="lineno"> 94</span>&#160;<span class="comment">/* PHY update counter for state machine */</span></div> <div class="line"><a name="l00095"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gab8232b6720275552dae1309a8c6baf99"> 95</a></span>&#160;<span class="keyword">static</span> int32_t <a class="code" href="group___d_p83848___p_h_y.html#gab8232b6720275552dae1309a8c6baf99">phyustate</a>;</div> <div class="line"><a name="l00096"></a><span class="lineno"> 96</span>&#160;</div> <div class="line"><a name="l00097"></a><span class="lineno"> 97</span>&#160;<span class="comment">/* Pointer to delay function used for this driver */</span></div> <div class="line"><a name="l00098"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga4adbccc342faa0f724a24a0d8261a286"> 98</a></span>&#160;<span class="keyword">static</span> <a class="code" href="group___b_o_a_r_d___c_o_m_m_o_n___a_p_i.html#gabd040b6a5eb9bbf2697cbe943b8ecbc8" title="Function prototype for a MS delay function. Board layers or example code may define this function as ...">p_msDelay_func_t</a> <a class="code" href="group___d_p83848___p_h_y.html#ga4adbccc342faa0f724a24a0d8261a286">pDelayMs</a>;</div> <div class="line"><a name="l00099"></a><span class="lineno"> 99</span>&#160;</div> <div class="line"><a name="l00100"></a><span class="lineno"> 100</span>&#160;<span class="comment">/* Write to the PHY. Will block for delays based on the pDelayMs function. Returns</span></div> <div class="line"><a name="l00101"></a><span class="lineno"> 101</span>&#160;<span class="comment"> true on success, or false on failure */</span></div> <div class="line"><a name="l00102"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga0e569d5be15c4c069e8262ca470ebb71"> 102</a></span>&#160;<span class="keyword">static</span> <a class="code" href="group___l_p_c___types___public___types.html#ga67a0db04d321a74b7e7fcfd3f1a3f70b">Status</a> <a class="code" href="group___d_p83848___p_h_y.html#ga0e569d5be15c4c069e8262ca470ebb71">lpc_mii_write</a>(uint8_t reg, uint16_t data)</div> <div class="line"><a name="l00103"></a><span class="lineno"> 103</span>&#160;{</div> <div class="line"><a name="l00104"></a><span class="lineno"> 104</span>&#160; <a class="code" href="group___l_p_c___types___public___types.html#ga67a0db04d321a74b7e7fcfd3f1a3f70b">Status</a> sts = <a class="code" href="group___l_p_c___types___public___types.html#gga67a0db04d321a74b7e7fcfd3f1a3f70ba2fd6f336d08340583bd620a7f5694c90">ERROR</a>;</div> <div class="line"><a name="l00105"></a><span class="lineno"> 105</span>&#160; int32_t mst = 250;</div> <div class="line"><a name="l00106"></a><span class="lineno"> 106</span>&#160;</div> <div class="line"><a name="l00107"></a><span class="lineno"> 107</span>&#160; <span class="comment">/* Write value for register */</span></div> <div class="line"><a name="l00108"></a><span class="lineno"> 108</span>&#160; <a class="code" href="group___e_n_e_t__18_x_x__43_x_x.html#gade9f31bbc04119bc06638fd8ce874f73" title="Starts a PHY write via the MII.">Chip_ENET_StartMIIWrite</a>(<a class="code" href="group___p_e_r_i_p_h__18_x_x___b_a_s_e.html#gaddb977e4442891b21ced3344c71440d7">LPC_ETHERNET</a>, reg, data);</div> <div class="line"><a name="l00109"></a><span class="lineno"> 109</span>&#160;</div> <div class="line"><a name="l00110"></a><span class="lineno"> 110</span>&#160; <span class="comment">/* Wait for unbusy status */</span></div> <div class="line"><a name="l00111"></a><span class="lineno"> 111</span>&#160; <span class="keywordflow">while</span> (mst &gt; 0) {</div> <div class="line"><a name="l00112"></a><span class="lineno"> 112</span>&#160; <span class="keywordflow">if</span> (<a class="code" href="group___e_n_e_t__18_x_x__43_x_x.html#ga2ae5389a2b99d6006980083d02667e07" title="Returns MII link (PHY) busy status.">Chip_ENET_IsMIIBusy</a>(<a class="code" href="group___p_e_r_i_p_h__18_x_x___b_a_s_e.html#gaddb977e4442891b21ced3344c71440d7">LPC_ETHERNET</a>)) {</div> <div class="line"><a name="l00113"></a><span class="lineno"> 113</span>&#160; mst--;</div> <div class="line"><a name="l00114"></a><span class="lineno"> 114</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga4adbccc342faa0f724a24a0d8261a286">pDelayMs</a>(1);</div> <div class="line"><a name="l00115"></a><span class="lineno"> 115</span>&#160; }</div> <div class="line"><a name="l00116"></a><span class="lineno"> 116</span>&#160; <span class="keywordflow">else</span> {</div> <div class="line"><a name="l00117"></a><span class="lineno"> 117</span>&#160; mst = 0;</div> <div class="line"><a name="l00118"></a><span class="lineno"> 118</span>&#160; sts = <a class="code" href="group___l_p_c___types___public___types.html#gga67a0db04d321a74b7e7fcfd3f1a3f70bac7f69f7c9e5aea9b8f54cf02870e2bf8">SUCCESS</a>;</div> <div class="line"><a name="l00119"></a><span class="lineno"> 119</span>&#160; }</div> <div class="line"><a name="l00120"></a><span class="lineno"> 120</span>&#160; }</div> <div class="line"><a name="l00121"></a><span class="lineno"> 121</span>&#160;</div> <div class="line"><a name="l00122"></a><span class="lineno"> 122</span>&#160; <span class="keywordflow">return</span> sts;</div> <div class="line"><a name="l00123"></a><span class="lineno"> 123</span>&#160;}</div> <div class="line"><a name="l00124"></a><span class="lineno"> 124</span>&#160;</div> <div class="line"><a name="l00125"></a><span class="lineno"> 125</span>&#160;<span class="comment">/* Read from the PHY. Will block for delays based on the pDelayMs function. Returns</span></div> <div class="line"><a name="l00126"></a><span class="lineno"> 126</span>&#160;<span class="comment"> true on success, or false on failure */</span></div> <div class="line"><a name="l00127"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gae7aa3808da3345de4aee9bbe11e02366"> 127</a></span>&#160;<span class="keyword">static</span> <a class="code" href="group___l_p_c___types___public___types.html#ga67a0db04d321a74b7e7fcfd3f1a3f70b">Status</a> <a class="code" href="group___d_p83848___p_h_y.html#gae7aa3808da3345de4aee9bbe11e02366">lpc_mii_read</a>(uint8_t reg, uint16_t *data)</div> <div class="line"><a name="l00128"></a><span class="lineno"> 128</span>&#160;{</div> <div class="line"><a name="l00129"></a><span class="lineno"> 129</span>&#160; <a class="code" href="group___l_p_c___types___public___types.html#ga67a0db04d321a74b7e7fcfd3f1a3f70b">Status</a> sts = <a class="code" href="group___l_p_c___types___public___types.html#gga67a0db04d321a74b7e7fcfd3f1a3f70ba2fd6f336d08340583bd620a7f5694c90">ERROR</a>;</div> <div class="line"><a name="l00130"></a><span class="lineno"> 130</span>&#160; int32_t mst = 250;</div> <div class="line"><a name="l00131"></a><span class="lineno"> 131</span>&#160;</div> <div class="line"><a name="l00132"></a><span class="lineno"> 132</span>&#160; <span class="comment">/* Start register read */</span></div> <div class="line"><a name="l00133"></a><span class="lineno"> 133</span>&#160; <a class="code" href="group___e_n_e_t__18_x_x__43_x_x.html#gaca2166605d385fd5150f173cd33a3ac2" title="Starts a PHY read via the MII.">Chip_ENET_StartMIIRead</a>(<a class="code" href="group___p_e_r_i_p_h__18_x_x___b_a_s_e.html#gaddb977e4442891b21ced3344c71440d7">LPC_ETHERNET</a>, reg);</div> <div class="line"><a name="l00134"></a><span class="lineno"> 134</span>&#160;</div> <div class="line"><a name="l00135"></a><span class="lineno"> 135</span>&#160; <span class="comment">/* Wait for unbusy status */</span></div> <div class="line"><a name="l00136"></a><span class="lineno"> 136</span>&#160; <span class="keywordflow">while</span> (mst &gt; 0) {</div> <div class="line"><a name="l00137"></a><span class="lineno"> 137</span>&#160; <span class="keywordflow">if</span> (!<a class="code" href="group___e_n_e_t__18_x_x__43_x_x.html#ga2ae5389a2b99d6006980083d02667e07" title="Returns MII link (PHY) busy status.">Chip_ENET_IsMIIBusy</a>(<a class="code" href="group___p_e_r_i_p_h__18_x_x___b_a_s_e.html#gaddb977e4442891b21ced3344c71440d7">LPC_ETHERNET</a>)) {</div> <div class="line"><a name="l00138"></a><span class="lineno"> 138</span>&#160; mst = 0;</div> <div class="line"><a name="l00139"></a><span class="lineno"> 139</span>&#160; *data = <a class="code" href="group___e_n_e_t__18_x_x__43_x_x.html#ga47f1d10185cb9ed0c484c9fd3ac07423" title="Returns the value read from the PHY.">Chip_ENET_ReadMIIData</a>(<a class="code" href="group___p_e_r_i_p_h__18_x_x___b_a_s_e.html#gaddb977e4442891b21ced3344c71440d7">LPC_ETHERNET</a>);</div> <div class="line"><a name="l00140"></a><span class="lineno"> 140</span>&#160; sts = <a class="code" href="group___l_p_c___types___public___types.html#gga67a0db04d321a74b7e7fcfd3f1a3f70bac7f69f7c9e5aea9b8f54cf02870e2bf8">SUCCESS</a>;</div> <div class="line"><a name="l00141"></a><span class="lineno"> 141</span>&#160; }</div> <div class="line"><a name="l00142"></a><span class="lineno"> 142</span>&#160; <span class="keywordflow">else</span> {</div> <div class="line"><a name="l00143"></a><span class="lineno"> 143</span>&#160; mst--;</div> <div class="line"><a name="l00144"></a><span class="lineno"> 144</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga4adbccc342faa0f724a24a0d8261a286">pDelayMs</a>(1);</div> <div class="line"><a name="l00145"></a><span class="lineno"> 145</span>&#160; }</div> <div class="line"><a name="l00146"></a><span class="lineno"> 146</span>&#160; }</div> <div class="line"><a name="l00147"></a><span class="lineno"> 147</span>&#160;</div> <div class="line"><a name="l00148"></a><span class="lineno"> 148</span>&#160; <span class="keywordflow">return</span> sts;</div> <div class="line"><a name="l00149"></a><span class="lineno"> 149</span>&#160;}</div> <div class="line"><a name="l00150"></a><span class="lineno"> 150</span>&#160;</div> <div class="line"><a name="l00151"></a><span class="lineno"> 151</span>&#160;<span class="comment">/* Update PHY status from passed value */</span></div> <div class="line"><a name="l00152"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga13c06e6f1a0654ef91ac9acc77b471cd"> 152</a></span>&#160;<span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="group___d_p83848___p_h_y.html#ga13c06e6f1a0654ef91ac9acc77b471cd">lpc_update_phy_sts</a>(uint16_t linksts)</div> <div class="line"><a name="l00153"></a><span class="lineno"> 153</span>&#160;{</div> <div class="line"><a name="l00154"></a><span class="lineno"> 154</span>&#160; <span class="comment">/* Update link active status */</span></div> <div class="line"><a name="l00155"></a><span class="lineno"> 155</span>&#160; <span class="keywordflow">if</span> (linksts &amp; <a class="code" href="group___d_p83848___p_h_y.html#ga0216e81b2b460c1f6b1c739badb2a27a">DP8_VALID_LINK</a>) {</div> <div class="line"><a name="l00156"></a><span class="lineno"> 156</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> |= <a class="code" href="group___b_o_a_r_d___p_h_y.html#ga4355878edd2f4e71c449318d65caff96">PHY_LINK_CONNECTED</a>;</div> <div class="line"><a name="l00157"></a><span class="lineno"> 157</span>&#160; }</div> <div class="line"><a name="l00158"></a><span class="lineno"> 158</span>&#160; <span class="keywordflow">else</span> {</div> <div class="line"><a name="l00159"></a><span class="lineno"> 159</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> &amp;= ~<a class="code" href="group___b_o_a_r_d___p_h_y.html#ga4355878edd2f4e71c449318d65caff96">PHY_LINK_CONNECTED</a>;</div> <div class="line"><a name="l00160"></a><span class="lineno"> 160</span>&#160; }</div> <div class="line"><a name="l00161"></a><span class="lineno"> 161</span>&#160;</div> <div class="line"><a name="l00162"></a><span class="lineno"> 162</span>&#160; <span class="comment">/* Full or half duplex */</span></div> <div class="line"><a name="l00163"></a><span class="lineno"> 163</span>&#160; <span class="keywordflow">if</span> (linksts &amp; <a class="code" href="group___d_p83848___p_h_y.html#gaa96c2ae7a3f76bf6ef26ad549c0ba348">DP8_FULLDUPLEX</a>) {</div> <div class="line"><a name="l00164"></a><span class="lineno"> 164</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> |= <a class="code" href="group___b_o_a_r_d___p_h_y.html#ga4b400b487b0e6a1bfc52fbc50e72be3e">PHY_LINK_FULLDUPLX</a>;</div> <div class="line"><a name="l00165"></a><span class="lineno"> 165</span>&#160; }</div> <div class="line"><a name="l00166"></a><span class="lineno"> 166</span>&#160; <span class="keywordflow">else</span> {</div> <div class="line"><a name="l00167"></a><span class="lineno"> 167</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> &amp;= ~<a class="code" href="group___b_o_a_r_d___p_h_y.html#ga4b400b487b0e6a1bfc52fbc50e72be3e">PHY_LINK_FULLDUPLX</a>;</div> <div class="line"><a name="l00168"></a><span class="lineno"> 168</span>&#160; }</div> <div class="line"><a name="l00169"></a><span class="lineno"> 169</span>&#160;</div> <div class="line"><a name="l00170"></a><span class="lineno"> 170</span>&#160; <span class="comment">/* Configure 100MBit/10MBit mode. */</span></div> <div class="line"><a name="l00171"></a><span class="lineno"> 171</span>&#160; <span class="keywordflow">if</span> (linksts &amp; <a class="code" href="group___d_p83848___p_h_y.html#ga90ee3d108a5f6db2f94d55c90b8484bd">DP8_SPEED10MBPS</a>) {</div> <div class="line"><a name="l00172"></a><span class="lineno"> 172</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> &amp;= ~<a class="code" href="group___b_o_a_r_d___p_h_y.html#gaa09dfe28e00af59bceb69ef503f88e68">PHY_LINK_SPEED100</a>;</div> <div class="line"><a name="l00173"></a><span class="lineno"> 173</span>&#160; }</div> <div class="line"><a name="l00174"></a><span class="lineno"> 174</span>&#160; <span class="keywordflow">else</span> {</div> <div class="line"><a name="l00175"></a><span class="lineno"> 175</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> |= <a class="code" href="group___b_o_a_r_d___p_h_y.html#gaa09dfe28e00af59bceb69ef503f88e68">PHY_LINK_SPEED100</a>;</div> <div class="line"><a name="l00176"></a><span class="lineno"> 176</span>&#160; }</div> <div class="line"><a name="l00177"></a><span class="lineno"> 177</span>&#160;</div> <div class="line"><a name="l00178"></a><span class="lineno"> 178</span>&#160; <span class="comment">/* If the status has changed, indicate via change flag */</span></div> <div class="line"><a name="l00179"></a><span class="lineno"> 179</span>&#160; <span class="keywordflow">if</span> ((<a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> &amp; (<a class="code" href="group___b_o_a_r_d___p_h_y.html#gaa09dfe28e00af59bceb69ef503f88e68">PHY_LINK_SPEED100</a> | <a class="code" href="group___b_o_a_r_d___p_h_y.html#ga4b400b487b0e6a1bfc52fbc50e72be3e">PHY_LINK_FULLDUPLX</a> | <a class="code" href="group___b_o_a_r_d___p_h_y.html#ga4355878edd2f4e71c449318d65caff96">PHY_LINK_CONNECTED</a>)) !=</div> <div class="line"><a name="l00180"></a><span class="lineno"> 180</span>&#160; (<a class="code" href="group___d_p83848___p_h_y.html#ga0cf36f6bdb20115a22ef1478d47f7dec">olddphysts</a> &amp; (<a class="code" href="group___b_o_a_r_d___p_h_y.html#gaa09dfe28e00af59bceb69ef503f88e68">PHY_LINK_SPEED100</a> | <a class="code" href="group___b_o_a_r_d___p_h_y.html#ga4b400b487b0e6a1bfc52fbc50e72be3e">PHY_LINK_FULLDUPLX</a> | <a class="code" href="group___b_o_a_r_d___p_h_y.html#ga4355878edd2f4e71c449318d65caff96">PHY_LINK_CONNECTED</a>))) {</div> <div class="line"><a name="l00181"></a><span class="lineno"> 181</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga0cf36f6bdb20115a22ef1478d47f7dec">olddphysts</a> = <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a>;</div> <div class="line"><a name="l00182"></a><span class="lineno"> 182</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> |= <a class="code" href="group___b_o_a_r_d___p_h_y.html#ga024ecb53e2bd08b11916fe3df9881fe6">PHY_LINK_CHANGED</a>;</div> <div class="line"><a name="l00183"></a><span class="lineno"> 183</span>&#160; }</div> <div class="line"><a name="l00184"></a><span class="lineno"> 184</span>&#160;}</div> <div class="line"><a name="l00185"></a><span class="lineno"> 185</span>&#160;</div> <div class="line"><a name="l00186"></a><span class="lineno"> 186</span>&#160;<span class="comment">/* Initialize the DP83848 PHY */</span></div> <div class="line"><a name="l00187"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#ga9d09c9f5e31d5213b738ab80863776d5"> 187</a></span>&#160;uint32_t <a class="code" href="group___b_o_a_r_d___p_h_y.html#ga9d09c9f5e31d5213b738ab80863776d5" title="Initialize the PHY.">lpc_phy_init</a>(<span class="keywordtype">bool</span> rmii, <a class="code" href="group___b_o_a_r_d___c_o_m_m_o_n___a_p_i.html#gabd040b6a5eb9bbf2697cbe943b8ecbc8" title="Function prototype for a MS delay function. Board layers or example code may define this function as ...">p_msDelay_func_t</a> pDelayMsFunc)</div> <div class="line"><a name="l00188"></a><span class="lineno"> 188</span>&#160;{</div> <div class="line"><a name="l00189"></a><span class="lineno"> 189</span>&#160; uint16_t tmp;</div> <div class="line"><a name="l00190"></a><span class="lineno"> 190</span>&#160; int32_t i;</div> <div class="line"><a name="l00191"></a><span class="lineno"> 191</span>&#160;</div> <div class="line"><a name="l00192"></a><span class="lineno"> 192</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga4adbccc342faa0f724a24a0d8261a286">pDelayMs</a> = pDelayMsFunc;</div> <div class="line"><a name="l00193"></a><span class="lineno"> 193</span>&#160;</div> <div class="line"><a name="l00194"></a><span class="lineno"> 194</span>&#160; <span class="comment">/* Initial states for PHY status and state machine */</span></div> <div class="line"><a name="l00195"></a><span class="lineno"> 195</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga0cf36f6bdb20115a22ef1478d47f7dec">olddphysts</a> = <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> = <a class="code" href="group___d_p83848___p_h_y.html#gab8232b6720275552dae1309a8c6baf99">phyustate</a> = 0;</div> <div class="line"><a name="l00196"></a><span class="lineno"> 196</span>&#160;</div> <div class="line"><a name="l00197"></a><span class="lineno"> 197</span>&#160; <span class="comment">/* Only first read and write are checked for failure */</span></div> <div class="line"><a name="l00198"></a><span class="lineno"> 198</span>&#160; <span class="comment">/* Put the DP83848C in reset mode and wait for completion */</span></div> <div class="line"><a name="l00199"></a><span class="lineno"> 199</span>&#160; <span class="keywordflow">if</span> (<a class="code" href="group___d_p83848___p_h_y.html#ga0e569d5be15c4c069e8262ca470ebb71">lpc_mii_write</a>(<a class="code" href="group___d_p83848___p_h_y.html#ga892a7317d57dda903e52c7cd54b73cec" title="DP83848 PHY register offsets.">DP8_BMCR_REG</a>, <a class="code" href="group___d_p83848___p_h_y.html#ga20124f1992fe8442bf86336e5eb3f8c9">DP8_RESET</a>) != <a class="code" href="group___l_p_c___types___public___types.html#gga67a0db04d321a74b7e7fcfd3f1a3f70bac7f69f7c9e5aea9b8f54cf02870e2bf8">SUCCESS</a>) {</div> <div class="line"><a name="l00200"></a><span class="lineno"> 200</span>&#160; <span class="keywordflow">return</span> <a class="code" href="group___l_p_c___types___public___types.html#gga67a0db04d321a74b7e7fcfd3f1a3f70ba2fd6f336d08340583bd620a7f5694c90">ERROR</a>;</div> <div class="line"><a name="l00201"></a><span class="lineno"> 201</span>&#160; }</div> <div class="line"><a name="l00202"></a><span class="lineno"> 202</span>&#160; i = 400;</div> <div class="line"><a name="l00203"></a><span class="lineno"> 203</span>&#160; <span class="keywordflow">while</span> (i &gt; 0) {</div> <div class="line"><a name="l00204"></a><span class="lineno"> 204</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga4adbccc342faa0f724a24a0d8261a286">pDelayMs</a>(1);</div> <div class="line"><a name="l00205"></a><span class="lineno"> 205</span>&#160; <span class="keywordflow">if</span> (<a class="code" href="group___d_p83848___p_h_y.html#gae7aa3808da3345de4aee9bbe11e02366">lpc_mii_read</a>(<a class="code" href="group___d_p83848___p_h_y.html#ga892a7317d57dda903e52c7cd54b73cec" title="DP83848 PHY register offsets.">DP8_BMCR_REG</a>, &amp;tmp) != <a class="code" href="group___l_p_c___types___public___types.html#gga67a0db04d321a74b7e7fcfd3f1a3f70bac7f69f7c9e5aea9b8f54cf02870e2bf8">SUCCESS</a>) {</div> <div class="line"><a name="l00206"></a><span class="lineno"> 206</span>&#160; <span class="keywordflow">return</span> <a class="code" href="group___l_p_c___types___public___types.html#gga67a0db04d321a74b7e7fcfd3f1a3f70ba2fd6f336d08340583bd620a7f5694c90">ERROR</a>;</div> <div class="line"><a name="l00207"></a><span class="lineno"> 207</span>&#160; }</div> <div class="line"><a name="l00208"></a><span class="lineno"> 208</span>&#160;</div> <div class="line"><a name="l00209"></a><span class="lineno"> 209</span>&#160; <span class="keywordflow">if</span> (!(tmp &amp; (<a class="code" href="group___d_p83848___p_h_y.html#ga20124f1992fe8442bf86336e5eb3f8c9">DP8_RESET</a> | <a class="code" href="group___d_p83848___p_h_y.html#gac133bb396b83069bf1628cbbcabbd902">DP8_POWER_DOWN</a>))) {</div> <div class="line"><a name="l00210"></a><span class="lineno"> 210</span>&#160; i = -1;</div> <div class="line"><a name="l00211"></a><span class="lineno"> 211</span>&#160; }</div> <div class="line"><a name="l00212"></a><span class="lineno"> 212</span>&#160; <span class="keywordflow">else</span> {</div> <div class="line"><a name="l00213"></a><span class="lineno"> 213</span>&#160; i--;</div> <div class="line"><a name="l00214"></a><span class="lineno"> 214</span>&#160; }</div> <div class="line"><a name="l00215"></a><span class="lineno"> 215</span>&#160; }</div> <div class="line"><a name="l00216"></a><span class="lineno"> 216</span>&#160; <span class="comment">/* Timeout? */</span></div> <div class="line"><a name="l00217"></a><span class="lineno"> 217</span>&#160; <span class="keywordflow">if</span> (i == 0) {</div> <div class="line"><a name="l00218"></a><span class="lineno"> 218</span>&#160; <span class="keywordflow">return</span> <a class="code" href="group___l_p_c___types___public___types.html#gga67a0db04d321a74b7e7fcfd3f1a3f70ba2fd6f336d08340583bd620a7f5694c90">ERROR</a>;</div> <div class="line"><a name="l00219"></a><span class="lineno"> 219</span>&#160; }</div> <div class="line"><a name="l00220"></a><span class="lineno"> 220</span>&#160;</div> <div class="line"><a name="l00221"></a><span class="lineno"> 221</span>&#160;<span class="preprocessor">#if 0</span></div> <div class="line"><a name="l00222"></a><span class="lineno"> 222</span>&#160;<span class="preprocessor"></span> <span class="comment">/* Setup link based on configuration options */</span></div> <div class="line"><a name="l00223"></a><span class="lineno"> 223</span>&#160;<span class="preprocessor">#if PHY_USE_AUTONEG == 1</span></div> <div class="line"><a name="l00224"></a><span class="lineno"> 224</span>&#160;<span class="preprocessor"></span> tmp = <a class="code" href="group___d_p83848___p_h_y.html#ga11fb5024f522364daffa86d8aa3e686a">DP8_AUTONEG</a>;</div> <div class="line"><a name="l00225"></a><span class="lineno"> 225</span>&#160;<span class="preprocessor">#else</span></div> <div class="line"><a name="l00226"></a><span class="lineno"> 226</span>&#160;<span class="preprocessor"></span> tmp = 0;</div> <div class="line"><a name="l00227"></a><span class="lineno"> 227</span>&#160;<span class="preprocessor">#endif</span></div> <div class="line"><a name="l00228"></a><span class="lineno"> 228</span>&#160;<span class="preprocessor"></span><span class="preprocessor">#if PHY_USE_100MBS == 1</span></div> <div class="line"><a name="l00229"></a><span class="lineno"> 229</span>&#160;<span class="preprocessor"></span> tmp |= <a class="code" href="group___d_p83848___p_h_y.html#ga41b97dcb346e3bbe4030dcb461d83dc5">DP8_SPEED_SELECT</a>;</div> <div class="line"><a name="l00230"></a><span class="lineno"> 230</span>&#160;<span class="preprocessor">#endif</span></div> <div class="line"><a name="l00231"></a><span class="lineno"> 231</span>&#160;<span class="preprocessor"></span><span class="preprocessor">#if PHY_USE_FULL_DUPLEX == 1</span></div> <div class="line"><a name="l00232"></a><span class="lineno"> 232</span>&#160;<span class="preprocessor"></span> tmp |= <a class="code" href="group___d_p83848___p_h_y.html#ga0775ca4632435fb4263758dd0d49e03f">DP8_DUPLEX_MODE</a>;</div> <div class="line"><a name="l00233"></a><span class="lineno"> 233</span>&#160;<span class="preprocessor">#endif</span></div> <div class="line"><a name="l00234"></a><span class="lineno"> 234</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00235"></a><span class="lineno"> 235</span>&#160;<span class="preprocessor">#else</span></div> <div class="line"><a name="l00236"></a><span class="lineno"> 236</span>&#160;<span class="preprocessor"></span> tmp = <a class="code" href="group___d_p83848___p_h_y.html#ga11fb5024f522364daffa86d8aa3e686a">DP8_AUTONEG</a>;</div> <div class="line"><a name="l00237"></a><span class="lineno"> 237</span>&#160;<span class="preprocessor">#endif</span></div> <div class="line"><a name="l00238"></a><span class="lineno"> 238</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00239"></a><span class="lineno"> 239</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga0e569d5be15c4c069e8262ca470ebb71">lpc_mii_write</a>(<a class="code" href="group___d_p83848___p_h_y.html#ga892a7317d57dda903e52c7cd54b73cec" title="DP83848 PHY register offsets.">DP8_BMCR_REG</a>, tmp);</div> <div class="line"><a name="l00240"></a><span class="lineno"> 240</span>&#160;</div> <div class="line"><a name="l00241"></a><span class="lineno"> 241</span>&#160; <span class="comment">/* Enable RMII mode for PHY */</span></div> <div class="line"><a name="l00242"></a><span class="lineno"> 242</span>&#160; <span class="keywordflow">if</span> (rmii) {</div> <div class="line"><a name="l00243"></a><span class="lineno"> 243</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga0e569d5be15c4c069e8262ca470ebb71">lpc_mii_write</a>(<a class="code" href="group___d_p83848___p_h_y.html#gadf696963d0abbb4beb829fc973495b7f">DP8_PHY_RBR_REG</a>, <a class="code" href="group___d_p83848___p_h_y.html#ga0add7cbf634b4f110bbf5b3252581535">DP8_RBR_RMII_MODE</a>);</div> <div class="line"><a name="l00244"></a><span class="lineno"> 244</span>&#160; }</div> <div class="line"><a name="l00245"></a><span class="lineno"> 245</span>&#160;</div> <div class="line"><a name="l00246"></a><span class="lineno"> 246</span>&#160; <span class="comment">/* The link is not set active at this point, but will be detected</span></div> <div class="line"><a name="l00247"></a><span class="lineno"> 247</span>&#160;<span class="comment"> later */</span></div> <div class="line"><a name="l00248"></a><span class="lineno"> 248</span>&#160;</div> <div class="line"><a name="l00249"></a><span class="lineno"> 249</span>&#160; <span class="keywordflow">return</span> <a class="code" href="group___l_p_c___types___public___types.html#gga67a0db04d321a74b7e7fcfd3f1a3f70bac7f69f7c9e5aea9b8f54cf02870e2bf8">SUCCESS</a>;</div> <div class="line"><a name="l00250"></a><span class="lineno"> 250</span>&#160;}</div> <div class="line"><a name="l00251"></a><span class="lineno"> 251</span>&#160;</div> <div class="line"><a name="l00252"></a><span class="lineno"> 252</span>&#160;<span class="comment">/* Phy status update state machine */</span></div> <div class="line"><a name="l00253"></a><span class="lineno"><a class="code" href="group___d_p83848___p_h_y.html#gab5a4203ab2c54fa3fb243e784f9b3ddc"> 253</a></span>&#160;uint32_t <a class="code" href="group___b_o_a_r_d___p_h_y.html#gab5a4203ab2c54fa3fb243e784f9b3ddc" title="Phy status update state machine.">lpcPHYStsPoll</a>(<span class="keywordtype">void</span>)</div> <div class="line"><a name="l00254"></a><span class="lineno"> 254</span>&#160;{</div> <div class="line"><a name="l00255"></a><span class="lineno"> 255</span>&#160; <span class="keywordflow">switch</span> (<a class="code" href="group___d_p83848___p_h_y.html#gab8232b6720275552dae1309a8c6baf99">phyustate</a>) {</div> <div class="line"><a name="l00256"></a><span class="lineno"> 256</span>&#160; <span class="keywordflow">default</span>:</div> <div class="line"><a name="l00257"></a><span class="lineno"> 257</span>&#160; <span class="keywordflow">case</span> 0:</div> <div class="line"><a name="l00258"></a><span class="lineno"> 258</span>&#160; <span class="comment">/* Read BMSR to clear faults */</span></div> <div class="line"><a name="l00259"></a><span class="lineno"> 259</span>&#160; <a class="code" href="group___e_n_e_t__18_x_x__43_x_x.html#gaca2166605d385fd5150f173cd33a3ac2" title="Starts a PHY read via the MII.">Chip_ENET_StartMIIRead</a>(<a class="code" href="group___p_e_r_i_p_h__18_x_x___b_a_s_e.html#gaddb977e4442891b21ced3344c71440d7">LPC_ETHERNET</a>, <a class="code" href="group___d_p83848___p_h_y.html#ga187972bb76c6452082fe5d8871646c3c">DP8_PHY_STAT_REG</a>);</div> <div class="line"><a name="l00260"></a><span class="lineno"> 260</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> &amp;= ~<a class="code" href="group___b_o_a_r_d___p_h_y.html#ga024ecb53e2bd08b11916fe3df9881fe6">PHY_LINK_CHANGED</a>;</div> <div class="line"><a name="l00261"></a><span class="lineno"> 261</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> = <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> | <a class="code" href="group___b_o_a_r_d___p_h_y.html#gae9570359588a14f9e79b363a4861b461">PHY_LINK_BUSY</a>;</div> <div class="line"><a name="l00262"></a><span class="lineno"> 262</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#gab8232b6720275552dae1309a8c6baf99">phyustate</a> = 1;</div> <div class="line"><a name="l00263"></a><span class="lineno"> 263</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00264"></a><span class="lineno"> 264</span>&#160;</div> <div class="line"><a name="l00265"></a><span class="lineno"> 265</span>&#160; <span class="keywordflow">case</span> 1:</div> <div class="line"><a name="l00266"></a><span class="lineno"> 266</span>&#160; <span class="comment">/* Wait for read status state */</span></div> <div class="line"><a name="l00267"></a><span class="lineno"> 267</span>&#160; <span class="keywordflow">if</span> (!<a class="code" href="group___e_n_e_t__18_x_x__43_x_x.html#ga2ae5389a2b99d6006980083d02667e07" title="Returns MII link (PHY) busy status.">Chip_ENET_IsMIIBusy</a>(<a class="code" href="group___p_e_r_i_p_h__18_x_x___b_a_s_e.html#gaddb977e4442891b21ced3344c71440d7">LPC_ETHERNET</a>)) {</div> <div class="line"><a name="l00268"></a><span class="lineno"> 268</span>&#160; <span class="comment">/* Update PHY status */</span></div> <div class="line"><a name="l00269"></a><span class="lineno"> 269</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a> &amp;= ~<a class="code" href="group___b_o_a_r_d___p_h_y.html#gae9570359588a14f9e79b363a4861b461">PHY_LINK_BUSY</a>;</div> <div class="line"><a name="l00270"></a><span class="lineno"> 270</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#ga13c06e6f1a0654ef91ac9acc77b471cd">lpc_update_phy_sts</a>(<a class="code" href="group___e_n_e_t__18_x_x__43_x_x.html#ga47f1d10185cb9ed0c484c9fd3ac07423" title="Returns the value read from the PHY.">Chip_ENET_ReadMIIData</a>(<a class="code" href="group___p_e_r_i_p_h__18_x_x___b_a_s_e.html#gaddb977e4442891b21ced3344c71440d7">LPC_ETHERNET</a>));</div> <div class="line"><a name="l00271"></a><span class="lineno"> 271</span>&#160; <a class="code" href="group___d_p83848___p_h_y.html#gab8232b6720275552dae1309a8c6baf99">phyustate</a> = 0;</div> <div class="line"><a name="l00272"></a><span class="lineno"> 272</span>&#160; }</div> <div class="line"><a name="l00273"></a><span class="lineno"> 273</span>&#160; <span class="keywordflow">break</span>;</div> <div class="line"><a name="l00274"></a><span class="lineno"> 274</span>&#160; }</div> <div class="line"><a name="l00275"></a><span class="lineno"> 275</span>&#160;</div> <div class="line"><a name="l00276"></a><span class="lineno"> 276</span>&#160; <span class="keywordflow">return</span> <a class="code" href="group___d_p83848___p_h_y.html#ga5699d62624b72bdd5874b1781fe94460">physts</a>;</div> <div class="line"><a name="l00277"></a><span class="lineno"> 277</span>&#160;}</div> <div class="line"><a name="l00278"></a><span class="lineno"> 278</span>&#160;</div> </div><!-- fragment --></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Fri Feb 20 2015 21:29:41 for LPCOpen Platform for LPC18XX/43XX microcontrollers by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
gaspa92/SintetizadorAnalogico_EDU-CIAA
documentacion_util/lpcopen_2_16_docs_18xx_43xx/lpc__phy__dp83848_8c_source.html
HTML
gpl-3.0
53,565
// tex.h -- texture base class // // Copyright (C) 2008, 2010, 2011, 2013 Miles Bader <miles@gnu.org> // // This source code 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, or (at // your option) any later version. See the file COPYING for more details. // // Written by Miles Bader <miles@gnu.org> // #ifndef SNOGRAY_TEX_H #define SNOGRAY_TEX_H #include "util/ref.h" #include "tex-coords.h" namespace snogray { typedef float tparam_t; // A texture. // template<typename T> class Tex : public RefCounted { public: // Evaluate this texture at TEX_COORDS. // virtual T eval (const TexCoords &tex_coords) const = 0; }; // A textured value. It is either a constant value or refers to a // texture which can be used to generate a value. // template<typename T> class TexVal { public: TexVal (const T &val) : default_val (val) { } template<typename T2> TexVal (const Ref<Tex<T2> > &_tex) : tex (_tex), default_val (0) { } template<typename T2> TexVal (const Ref<const Tex<T2> > &_tex) : tex (_tex), default_val (0) { } TexVal &operator= (const T &val) { tex = 0; default_val = val; return *this; } template<typename T2> TexVal &operator= (const Ref<Tex<T2> > &_tex) { tex = _tex; return *this; } // Evaluate this texture at TEX_COORDS. // T eval (const TexCoords &tex_coords) const { return tex ? tex->eval (tex_coords) : default_val; } Ref<const Tex<T> > tex; T default_val; }; } #endif // SNOGRAY_TEX_H
snogglethorpe/snogray
texture/tex.h
C
gpl-3.0
1,624
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_11) on Mon Jun 16 17:36:06 PDT 2014 --> <title>Uses of Interface javax.imageio.ImageTranscoder (Java Platform SE 8 )</title> <meta name="date" content="2014-06-16"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface javax.imageio.ImageTranscoder (Java Platform SE 8 )"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../javax/imageio/ImageTranscoder.html" title="interface in javax.imageio">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;8</strong></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?javax/imageio/class-use/ImageTranscoder.html" target="_top">Frames</a></li> <li><a href="ImageTranscoder.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface javax.imageio.ImageTranscoder" class="title">Uses of Interface<br>javax.imageio.ImageTranscoder</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../javax/imageio/ImageTranscoder.html" title="interface in javax.imageio">ImageTranscoder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#javax.imageio">javax.imageio</a></td> <td class="colLast"> <div class="block">The main package of the Java Image I/O API.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#javax.imageio.spi">javax.imageio.spi</a></td> <td class="colLast"> <div class="block">A package of the Java Image I/O API containing the plug-in interfaces for readers, writers, transcoders, and streams, and a runtime registry.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="javax.imageio"> <!-- --> </a> <h3>Uses of <a href="../../../javax/imageio/ImageTranscoder.html" title="interface in javax.imageio">ImageTranscoder</a> in <a href="../../../javax/imageio/package-summary.html">javax.imageio</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../javax/imageio/package-summary.html">javax.imageio</a> that implement <a href="../../../javax/imageio/ImageTranscoder.html" title="interface in javax.imageio">ImageTranscoder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../javax/imageio/ImageWriter.html" title="class in javax.imageio">ImageWriter</a></span></code> <div class="block">An abstract superclass for encoding and writing images.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../javax/imageio/package-summary.html">javax.imageio</a> that return types with arguments of type <a href="../../../javax/imageio/ImageTranscoder.html" title="interface in javax.imageio">ImageTranscoder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../java/util/Iterator.html" title="interface in java.util">Iterator</a>&lt;<a href="../../../javax/imageio/ImageTranscoder.html" title="interface in javax.imageio">ImageTranscoder</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">ImageIO.</span><code><span class="memberNameLink"><a href="../../../javax/imageio/ImageIO.html#getImageTranscoders-javax.imageio.ImageReader-javax.imageio.ImageWriter-">getImageTranscoders</a></span>(<a href="../../../javax/imageio/ImageReader.html" title="class in javax.imageio">ImageReader</a>&nbsp;reader, <a href="../../../javax/imageio/ImageWriter.html" title="class in javax.imageio">ImageWriter</a>&nbsp;writer)</code> <div class="block">Returns an <code>Iterator</code> containing all currently registered <code>ImageTranscoder</code>s that claim to be able to transcode between the metadata of the given <code>ImageReader</code> and <code>ImageWriter</code>.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="javax.imageio.spi"> <!-- --> </a> <h3>Uses of <a href="../../../javax/imageio/ImageTranscoder.html" title="interface in javax.imageio">ImageTranscoder</a> in <a href="../../../javax/imageio/spi/package-summary.html">javax.imageio.spi</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../javax/imageio/spi/package-summary.html">javax.imageio.spi</a> that return <a href="../../../javax/imageio/ImageTranscoder.html" title="interface in javax.imageio">ImageTranscoder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>abstract <a href="../../../javax/imageio/ImageTranscoder.html" title="interface in javax.imageio">ImageTranscoder</a></code></td> <td class="colLast"><span class="typeNameLabel">ImageTranscoderSpi.</span><code><span class="memberNameLink"><a href="../../../javax/imageio/spi/ImageTranscoderSpi.html#createTranscoderInstance--">createTranscoderInstance</a></span>()</code> <div class="block">Returns an instance of the <code>ImageTranscoder</code> implementation associated with this service provider.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../javax/imageio/ImageTranscoder.html" title="interface in javax.imageio">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;8</strong></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?javax/imageio/class-use/ImageTranscoder.html" target="_top">Frames</a></li> <li><a href="ImageTranscoder.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://download.oracle.com/javase/8/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> Copyright &#x00a9; 1993, 2014, Oracle and/or its affiliates. All rights reserved. </font></small></p> </body> </html>
DeanAaron/jdk8
jdk8en_us/docs/api/javax/imageio/class-use/ImageTranscoder.html
HTML
gpl-3.0
10,229
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_11) on Mon Jun 16 17:36:04 PDT 2014 --> <title>Uses of Class java.lang.Compiler (Java Platform SE 8 )</title> <meta name="date" content="2014-06-16"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class java.lang.Compiler (Java Platform SE 8 )"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../java/lang/Compiler.html" title="class in java.lang">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;8</strong></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?java/lang/class-use/Compiler.html" target="_top">Frames</a></li> <li><a href="Compiler.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class java.lang.Compiler" class="title">Uses of Class<br>java.lang.Compiler</h2> </div> <div class="classUseContainer">No usage of java.lang.Compiler</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../java/lang/Compiler.html" title="class in java.lang">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;8</strong></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?java/lang/class-use/Compiler.html" target="_top">Frames</a></li> <li><a href="Compiler.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://download.oracle.com/javase/8/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> Copyright &#x00a9; 1993, 2014, Oracle and/or its affiliates. All rights reserved. </font></small></p> </body> </html>
DeanAaron/jdk8
jdk8en_us/docs/api/java/lang/class-use/Compiler.html
HTML
gpl-3.0
4,893
// // SuperTuxKart - a fun racing game with go-kart // Copyright (C) 2007-2008 Robert Schuster <robertschuster@fsfe.org> // // 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef HEADER_INPUT_HPP #define HEADER_INPUT_HPP /** * \defgroup input * Contains classes for input management (keyboard and gamepad) */ #include <string> #include <irrString.h> class Binding; const int DEADZONE_MOUSE = 150; const int DEADZONE_MOUSE_SENSE = 200; const int DEADZONE_JOYSTICK = 2000; const int MULTIPLIER_MOUSE = 750; /** * \ingroup input */ struct Input { static const int MAX_VALUE = 32768; static const int HAT_H_ID = 100; static const int HAT_V_ID = 101; enum AxisDirection { AD_NEGATIVE, AD_POSITIVE, AD_NEUTRAL }; enum AxisRange { AR_HALF, AR_FULL }; enum InputType { IT_NONE = 0, IT_KEYBOARD, IT_STICKMOTION, IT_STICKBUTTON, //IT_STICKHAT, IT_MOUSEMOTION, IT_MOUSEBUTTON }; static const int IT_LAST = IT_MOUSEBUTTON; InputType m_type; int m_device_id; int m_button_id; // or axis ID for gamepads axes int m_axis_direction; int m_axis_range; wchar_t m_character; Input() : m_type(IT_NONE), m_device_id(0), m_button_id(0), m_axis_direction(0), m_character(0) { // Nothing to do. } /** Creates an Input instance which represents an arbitrary way of getting * game input using a type specifier and 3 integers. * * Meaning of the 3 integers for each InputType: * IT_NONE: This means nothing. In certain cases this is regarded as an * unset binding. * IT_KEYBOARD: id0 is a irrLicht value. * IT_STICKMOTION: id0 - stick index, id1 - axis index, id2 - axis direction * (negative, positive). You can assume that axis 0 is the X-Axis where the * negative direction is to the left and that axis 1 is the Y-Axis with the * negative direction being upwards. * IT_STICKBUTTON: id0 - stick index, id1 - button index. Button 0 and 1 are * usually reached most easily. * IT_STICKHAT: This is not yet implemented. * IT_MOUSEMOTION: id0 - axis index (0 -> X, 1 -> Y). Mouse wheel is * represented as buttons! * IT_MOUSEBUTTON: id0 - button number (1 -> left, 2 -> middle, 3 -> right, * ...) * * Note: For joystick bindings that are actice in the menu the joystick's * index should be zero. The binding will react to all joysticks connected * to the system. */ Input(InputType ntype, int deviceID , int btnID = 0, int axisDirection= 0) : m_type(ntype), m_device_id(deviceID), m_button_id(btnID), m_axis_direction(axisDirection) { // Nothing to do. } }; // struct Input /** * \brief types of input events / what actions the players can do * \ingroup input */ enum PlayerAction { PA_BEFORE_FIRST = -1, PA_STEER_LEFT = 0, PA_STEER_RIGHT, PA_ACCEL, PA_BRAKE, PA_NITRO, PA_DRIFT, PA_RESCUE, PA_FIRE, PA_LOOK_BACK, PA_PAUSE_RACE, PA_MENU_UP, PA_MENU_DOWN, PA_MENU_LEFT, PA_MENU_RIGHT, PA_MENU_SELECT, PA_MENU_CANCEL, PA_COUNT }; const PlayerAction PA_FIRST_GAME_ACTION = PA_STEER_LEFT; const PlayerAction PA_LAST_GAME_ACTION = PA_PAUSE_RACE; const PlayerAction PA_FIRST_MENU_ACTION = PA_MENU_UP; const PlayerAction PA_LAST_MENU_ACTION = PA_MENU_CANCEL; /** * \brief human-readable strings for each PlayerAction * \ingroup input */ static std::string KartActionStrings[PA_COUNT] = {std::string("steerLeft"), std::string("steerRight"), std::string("accel"), std::string("brake"), std::string("nitro"), std::string("drift"), std::string("rescue"), std::string("fire"), std::string("lookBack"), std::string("pauserace"), std::string("menuUp"), std::string("menuDown"), std::string("menuLeft"), std::string("menuRight"), std::string("menuSelect"), std::string("menuCancel") }; #endif
clbr/stk
src/input/input.hpp
C++
gpl-3.0
5,551
/* FormBundle */ .form-submitaction-group-header { font-size: 1.1em; font-weight: bold; } #mauticforms_fields .mauticform-row, #mauticforms_actions .mauticform-row { padding: 10px; } #mauticforms_fields .mauticform-row { margin-bottom: 0 !important; } #mauticforms_actions .mauticform-row .action-label { font-size: 1.1em; font-weight: bold; display: block; } #mauticforms_actions .mauticform-row .action-descr { font-size: 0.9em; display: block; } #mauticforms_actions .form-buttons { float: right; margin-top: 3px; } #mauticforms_fields .form-buttons { float: right; margin-top: 8px; } #mauticforms_fields input, #mauticforms_fields textarea, #mauticforms_fields select { background-color: #fff; box-shadow: 0px 0px 0px #fff inset; padding: 0.5em 0.5em; width: 50%; } .mauticform-row { min-height: 60px; } #mauticforms_fields .panel-footer { padding: 3px 15px; } textarea.form-html { height: 200px; } .col-form-id, .col-formresult-id { width: 75px; } .col-form-submissions { width: 100px; } .formresult-list th .input-group { margin-top: 10px; } .formresult-list th:not(.col-formresult-id):not(.col-actions) { min-width: 125px; } .inline-spacer { padding-right: 20px; } #mauticforms_fields input[type="date"], #mauticforms_fields input[type="time"], #mauticforms_fields input[type="datetime-local"], #mauticforms_fields input[type="month"] { line-height: inherit; }
mqueme/mautic
app/bundles/FormBundle/Assets/css/form.css
CSS
gpl-3.0
1,488
\section{Sensors} \label{ss:aquagpusph:sensors} % In \NAME sensors are points where pressure and density fields will be measured. The method to add sensors into the simulations has been described in the section \ref{sss:XML:Sensors}.\rc % Internally, the sensors are set as particles similar to the fluid ones, but with $imove = 0$ flag (fluid particles have $imove > 0$ flag, and solid boundary elements $imove < 0$), and a null mass. The fields are interpolated in the way described in section \ref{ss:sph_description}, where the discretized operators can be defined such that % \begin{eqnarray} \label{eq:sensors:interpolation} \langle p \rangle_a & = & \frac{1}{\gamma_a} \sum\limits_{b \in \mathrm{Fluid}} \frac{p_b}{\rho_b} W_{ab} m_b \vspace{0.3cm} \\ \langle \rho \rangle_a & = & \frac{1}{\gamma_a} \sum\limits_{b \in \mathrm{Fluid}} W_{ab} m_b \end{eqnarray} % Sensors measured values are ever renormalized with the Shepard correction ($\gamma_a$ is not forced to be equal to 1), even though Shepard correction has switched off for the forces and density rate computation, but in order to you can revert the correction $\gamma_a$ (formerly $sumW$) is included into the output sensors data file.\rc % The sensors output data file is printed in the execution folder (so enough permissions are expected) with the name ``\textbf{Sensors.dat}'', inside the file a header will be printed, where the fields included are documented, and then several rows (one per output time instant) with the following data distributed in columns: % \begin{enumerate} \item Time instant $t \mbox{[s]}$. \item Sensor data columns (one per sensor). \begin{enumerate} \item X position $X \mbox{[m]}$. \item Y position $Y \mbox{[m]}$. \item Z position $Z \mbox{[m]}$ (only for 3D cases). \item Pressure $p \mbox{[Pa]}$. \item Density $\rho \mbox{[kg/m}^3\mbox{]}$. \item Kernel completeness factor $\gamma$. \end{enumerate} \end{enumerate} % The fields are separated by tabulators. This file can be directly plot with gnuplot, or loaded easily with almost data sheets. %
Juanlu001/aquagpusph
doc/userManual/sensors.tex
TeX
gpl-3.0
2,071
<html><body>Magister Errickin:<br> You don't have to introduce yourself--I already know all about you. I am Magister Errikin. Perhaps you've already noticed that this town is a dangerous place. You could easily be called on to defend not only your life, but more importantly, your honor.<br> <Button ALIGN=LEFT ICON="NORMAL" action="bypass -h npc_%objectId%_SkillList">Learn skills.</Button> <Button ALIGN=LEFT ICON="NORMAL" action="bypass -h Quest HealerTrainer SkillTransfer">Ask about Skill Transfer.</Button> <Button ALIGN=LEFT ICON="NORMAL" action="bypass -h npc_%objectId%_Link common/skill_enchant_help.htm">Ask about Skill Enchanting.</Button> <Button ALIGN=LEFT ICON="QUEST" action="bypass -h npc_%objectId%_Quest">Quest</Button> </body></html>
karolusw/l2j
game/data/scripts/ai/npc/Trainers/HealerTrainer/30701.html
HTML
gpl-3.0
753
//placeholder for custom scripts
Renogmusic/GStore
GStore/GStoreWeb/Content/Server/Scripts/Scripts.js
JavaScript
gpl-3.0
35
var classConsor_1_1RadioBox = [ [ "RadioBox", "classConsor_1_1RadioBox_aae20cff4d62bf98f51a48d77599a3481.html#aae20cff4d62bf98f51a48d77599a3481", null ], [ "~RadioBox", "classConsor_1_1RadioBox_a7e6c1b1b1b6474b2f9af331f135cfe7e.html#a7e6c1b1b1b6474b2f9af331f135cfe7e", null ], [ "AddChoice", "classConsor_1_1RadioBox_ade2eaabbe0ae109c9c813be8e377f40c.html#ade2eaabbe0ae109c9c813be8e377f40c", null ], [ "CanFocus", "classConsor_1_1RadioBox_af6c1e92a0bc75cba40fbf0be7a46ecbf.html#af6c1e92a0bc75cba40fbf0be7a46ecbf", null ], [ "Draw", "classConsor_1_1RadioBox_a01d2e143fb687dc49c84d98f4a63b317.html#a01d2e143fb687dc49c84d98f4a63b317", null ], [ "ForceResize", "classConsor_1_1RadioBox_a3202dbb3efbc14314dfba446e9c2416b.html#a3202dbb3efbc14314dfba446e9c2416b", null ], [ "GetChoice", "classConsor_1_1RadioBox_a36c8226cfac515640201fe8e9631e1a9.html#a36c8226cfac515640201fe8e9631e1a9", null ], [ "GetSize", "classConsor_1_1RadioBox_a67cc2bf06e9a9d16a07dc795d3e4fcf1.html#a67cc2bf06e9a9d16a07dc795d3e4fcf1", null ], [ "HandleInput", "classConsor_1_1RadioBox_a9613819a0ec347925f14fac056c749bd.html#a9613819a0ec347925f14fac056c749bd", null ], [ "OnResize", "classConsor_1_1RadioBox_a9797064782a333895795eb9b6449b9d2.html#a9797064782a333895795eb9b6449b9d2", null ], [ "_Checkboxes", "classConsor_1_1RadioBox_a9e90f4655e491fb99734dfadeb1c46a2.html#a9e90f4655e491fb99734dfadeb1c46a2", null ], [ "_FlowContainer", "classConsor_1_1RadioBox_a7461345288b9f70ef123782c95c76127.html#a7461345288b9f70ef123782c95c76127", null ], [ "OnValueChanged", "classConsor_1_1RadioBox_a3a42be4b48f0f485c5d4a6b92d2f7e3a.html#a3a42be4b48f0f485c5d4a6b92d2f7e3a", null ] ];
KateAdams/kateadams.eu
static/*.kateadams.eu/Consor/Doxygen/classConsor_1_1RadioBox.js
JavaScript
gpl-3.0
1,690
// // UMLayerSCCPApplicationContextProtocol.h // ulibsccp // // Created by Andreas Fink on 24.01.17. // Copyright © 2017 Andreas Fink (andreas@fink.org). All rights reserved. // #import <Foundation/Foundation.h> #import "UMSCCP_FilterProtocol.h" @class UMLayerMTP3; @protocol UMLayerSCCPApplicationContextProtocol<NSObject,UMSCCP_FilterDelegateProtocol> - (UMLayerMTP3 *)getMTP3:(NSString *)name; - (UMLayerSCCP *)getSCCP:(NSString *)name; - (UMSynchronizedDictionary *)dbPools; - (NSString *)filterEnginesPath; - (id)licenseDirectory; - (UMPrometheus *)prometheus; @end
andreasfink/ulibsccp
Classes/UMLayerSCCPApplicationContextProtocol.h
C
gpl-3.0
579
/********************************************************** * Version $Id$ *********************************************************/ /////////////////////////////////////////////////////////// // // // SAGA // // // // System for Automated Geoscientific Analyses // // // // Application Programming Interface // // // // Library: SAGA_API // // // //-------------------------------------------------------// // // // api_file.cpp // // // // Copyright (C) 2005 by Olaf Conrad // // // //-------------------------------------------------------// // // // This file is part of 'SAGA - System for Automated // // Geoscientific Analyses'. // // // // This library is free software; you can redistribute // // it and/or modify it under the terms of the GNU Lesser // // General Public License as published by the Free // // Software Foundation, version 2.1 of the License. // // // // This library is distributed in the hope that it will // // be useful, but WITHOUT ANY WARRANTY; without even the // // implied warranty of MERCHANTABILITY or FITNESS FOR A // // PARTICULAR PURPOSE. See the GNU Lesser General Public // // License for more details. // // // // You should have received a copy of the GNU Lesser // // General Public License along with this program; if // // not, write to the Free Software Foundation, Inc., // // 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, // // USA. // // // //-------------------------------------------------------// // // // contact: Olaf Conrad // // Institute of Geography // // University of Goettingen // // Goldschmidtstr. 5 // // 37077 Goettingen // // Germany // // // // e-mail: oconrad@saga-gis.org // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- #include <wx/utils.h> #include <wx/filename.h> #include "api_core.h" #if defined(_SAGA_VC) #define SG_FILE_TELL _ftelli64 #define SG_FILE_SEEK _fseeki64 #define SG_FILE_SIZE __int64 #else #define SG_FILE_TELL ftell #define SG_FILE_SEEK fseek #define SG_FILE_SIZE long #endif /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- CSG_File::CSG_File(void) { m_pStream = NULL; m_Encoding = SG_FILE_ENCODING_CHAR; } //--------------------------------------------------------- CSG_File::CSG_File(const CSG_String &FileName, int Mode, bool bBinary, int Encoding) { m_pStream = NULL; Open(FileName, Mode, bBinary, Encoding); } //--------------------------------------------------------- CSG_File::~CSG_File(void) { Close(); } //--------------------------------------------------------- bool CSG_File::Attach(FILE *Stream) { Close(); m_pStream = Stream; return( true ); } //--------------------------------------------------------- bool CSG_File::Detach(void) { m_pStream = NULL; return( true ); } //--------------------------------------------------------- bool CSG_File::Open(const CSG_String &File_Name, int Mode, bool bBinary, int Encoding) { Close(); m_Encoding = Encoding; CSG_String sMode; switch( Mode ) { default: return( false ); case SG_FILE_R: sMode = bBinary ? SG_T("rb" ) : SG_T("r" ); break; case SG_FILE_W: sMode = bBinary ? SG_T("wb" ) : SG_T("w" ); break; case SG_FILE_RW: sMode = bBinary ? SG_T("wb+") : SG_T("w+"); break; case SG_FILE_WA: sMode = bBinary ? SG_T("ab" ) : SG_T("a" ); break; case SG_FILE_RWA: sMode = bBinary ? SG_T("rb+") : SG_T("r+"); break; } switch( Encoding ) { case SG_FILE_ENCODING_CHAR: default: break; case SG_FILE_ENCODING_UNICODE: sMode += SG_T(", ccs=UNICODE"); break; case SG_FILE_ENCODING_UTF8: sMode += SG_T(", ccs=UTF-8" ); break; case SG_FILE_ENCODING_UTF16: sMode += SG_T(", ccs=UTF-16" ); break; } if( File_Name.Length() > 0 ) { m_pStream = fopen(File_Name, sMode); } return( m_pStream != NULL ); } //--------------------------------------------------------- bool CSG_File::Close(void) { if( m_pStream ) { fclose(m_pStream); m_pStream = NULL; return( true ); } return( false ); } //--------------------------------------------------------- sLong CSG_File::Length(void) const { if( m_pStream ) { SG_FILE_SIZE pos = SG_FILE_TELL(m_pStream); SG_FILE_SEEK(m_pStream, 0, SEEK_END); SG_FILE_SIZE len = SG_FILE_TELL(m_pStream); SG_FILE_SEEK(m_pStream, pos, SEEK_SET); return( len ); } return( -1 ); } //--------------------------------------------------------- bool CSG_File::is_EOF(void) const { return( m_pStream == NULL || feof(m_pStream) != 0 ); } //--------------------------------------------------------- bool CSG_File::Seek(sLong Offset, int Origin) const { switch( Origin ) { default: case SG_FILE_START: Origin = SEEK_SET; break; case SG_FILE_CURRENT: Origin = SEEK_CUR; break; case SG_FILE_END: Origin = SEEK_END; break; } return( m_pStream ? !SG_FILE_SEEK(m_pStream, Offset, Origin) : false ); } //--------------------------------------------------------- bool CSG_File::Seek_Start(void) const { return( m_pStream && SG_FILE_SEEK(m_pStream, 0, SEEK_SET) == 0 ); } //--------------------------------------------------------- bool CSG_File::Seek_End(void) const { return( m_pStream && SG_FILE_SEEK(m_pStream, 0, SEEK_END) == 0 ); } //--------------------------------------------------------- sLong CSG_File::Tell(void) const { return( m_pStream ? SG_FILE_TELL(m_pStream) : -1 ); } //--------------------------------------------------------- bool CSG_File::Flush(void) const { return( m_pStream ? !fflush(m_pStream) : false ); } //--------------------------------------------------------- int CSG_File::Printf(const char *Format, ...) { if( !m_pStream ) { return( 0 ); } #ifdef _SAGA_LINUX wxString _Format(Format); _Format.Replace("%s", "%ls"); // workaround as we only use wide characters since wx 2.9.4 so interpret strings as multibyte va_list argptr; va_start(argptr, _Format); int result = wxVfprintf(m_pStream, _Format, argptr); #else va_list argptr; va_start(argptr, Format); int result = wxVfprintf(m_pStream, Format, argptr); #endif va_end(argptr); return( result ); } //--------------------------------------------------------- int CSG_File::Printf(const wchar_t *Format, ...) { if( !m_pStream ) { return( 0 ); } #ifdef _SAGA_LINUX wxString _Format(Format); _Format.Replace("%s", "%ls"); // workaround as we only use wide characters since wx 2.9.4 so interpret strings as multibyte va_list argptr; va_start(argptr, _Format); int result = wxVfprintf(m_pStream, _Format, argptr); #else va_list argptr; va_start(argptr, Format); int result = wxVfprintf(m_pStream, Format, argptr); #endif va_end(argptr); return( result ); } //--------------------------------------------------------- size_t CSG_File::Read(void *Buffer, size_t Size, size_t Count) const { return( m_pStream ? fread(Buffer, Size, Count, m_pStream) : 0 ); } size_t CSG_File::Read(CSG_String &Buffer, size_t Size) const { if( m_pStream ) { char *b = (char *)SG_Calloc(Size + 1, sizeof(char)); size_t i = fread(b, sizeof(char), Size, m_pStream); Buffer = b; SG_Free(b); return( i ); } return( 0 ); } //--------------------------------------------------------- size_t CSG_File::Write(void *Buffer, size_t Size, size_t Count) const { return( m_pStream && Size > 0 && Count > 0 ? fwrite(Buffer, Size, Count, m_pStream) : 0 ); } size_t CSG_File::Write(const CSG_String &Buffer) const { return( Write((void *)Buffer.b_str(), sizeof(char), strlen(Buffer.b_str())) ); } //--------------------------------------------------------- bool CSG_File::Read_Line(CSG_String &sLine) const { int c; if( m_pStream && !feof(m_pStream) ) { sLine.Clear(); while( !feof(m_pStream) && (c = fgetc(m_pStream)) != 0x0A && c != EOF ) { if( c != 0x0D ) { sLine.Append((char)c); } } return( true ); } return( false ); } //--------------------------------------------------------- int CSG_File::Read_Char(void) const { if( m_pStream ) { return( getc(m_pStream) ); } return( 0 ); } //--------------------------------------------------------- int CSG_File::Read_Int(bool bByteOrderBig) const { int Value = 0; if( Read(&Value, sizeof(Value)) == 1 ) { if( bByteOrderBig ) { SG_Swap_Bytes(&Value, sizeof(Value)); } } return( Value ); } bool CSG_File::Write_Int(int Value, bool bByteOrderBig) { if( bByteOrderBig ) { SG_Swap_Bytes(&Value, sizeof(Value)); } return( Write(&Value, sizeof(Value)) == sizeof(Value) ); } //--------------------------------------------------------- double CSG_File::Read_Double(bool bByteOrderBig) const { double Value = 0; if( Read(&Value, sizeof(Value)) == 1 ) { if( bByteOrderBig ) { SG_Swap_Bytes(&Value, sizeof(Value)); } } return( Value ); } bool CSG_File::Write_Double(double Value, bool bByteOrderBig) { if( bByteOrderBig ) { SG_Swap_Bytes(&Value, sizeof(Value)); } return( Write(&Value, sizeof(Value)) == sizeof(Value) ); } //--------------------------------------------------------- bool CSG_File::Scan(int &Value) const { return( m_pStream && fscanf(m_pStream, "%d" , &Value) == 1 ); } bool CSG_File::Scan(double &Value) const { return( m_pStream && fscanf(m_pStream, "%lf", &Value) == 1 ); } bool CSG_File::Scan(CSG_String &Value, SG_Char Separator) const { if( m_pStream && !feof(m_pStream) ) { int c; Value.Clear(); while( !feof(m_pStream) && (c = fgetc(m_pStream)) != Separator && c != EOF ) { Value += (char)c; } return( true ); } return( false ); } //--------------------------------------------------------- int CSG_File::Scan_Int(void) const { int Value; return( Scan(Value) ? Value : 0 ); } double CSG_File::Scan_Double(void) const { double Value; return( Scan(Value) ? Value : 0.0 ); } CSG_String CSG_File::Scan_String(SG_Char Separator) const { CSG_String Value; Scan(Value, Separator); return( Value ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- bool SG_Dir_Exists(const SG_Char *Directory) { return( Directory && *Directory && wxFileName::DirExists(Directory) ); } //--------------------------------------------------------- bool SG_Dir_Create(const SG_Char *Directory) { if( SG_Dir_Exists(Directory) ) { return( true ); } return( wxFileName::Mkdir(Directory) ); } //--------------------------------------------------------- CSG_String SG_Dir_Get_Current(void) { wxString cwd = wxFileName::GetCwd(); return( CSG_String(&cwd) ); } //--------------------------------------------------------- CSG_String SG_Dir_Get_Temp(void) { wxString fname = wxFileName::GetTempDir(); return( CSG_String(&fname) ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- bool SG_File_Exists(const SG_Char *FileName) { return( FileName && *FileName && wxFileExists(FileName) ); } //--------------------------------------------------------- bool SG_File_Delete(const SG_Char *FileName) { return( SG_File_Exists(FileName) && wxRemoveFile(FileName) ); } //--------------------------------------------------------- CSG_String SG_File_Get_Name_Temp(const SG_Char *Prefix, const SG_Char *Directory) { if( !SG_Dir_Exists(Directory) ) { return( CSG_String(wxFileName::CreateTempFileName(Prefix).wc_str()) ); } return( CSG_String(wxFileName::CreateTempFileName(SG_File_Make_Path(Directory, Prefix).w_str()).wc_str()) ); } //--------------------------------------------------------- CSG_String SG_File_Get_Name(const SG_Char *full_Path, bool bExtension) { wxFileName fn(full_Path); CSG_String s(fn.GetFullName().wc_str()); return( !bExtension && s.Find(SG_T(".")) >= 0 ? s.BeforeLast(SG_T('.')) : s ); } //--------------------------------------------------------- CSG_String SG_File_Get_Path(const SG_Char *full_Path) { if( full_Path && *full_Path ) { wxFileName fn(full_Path); return( CSG_String(fn.GetPath(wxPATH_GET_VOLUME|wxPATH_GET_SEPARATOR).wc_str()) ); } return( SG_T("") ); } //--------------------------------------------------------- CSG_String SG_File_Get_Path_Absolute (const SG_Char *full_Path) { wxString Path; if( full_Path && *full_Path ) { wxFileName fn(full_Path); fn.MakeAbsolute(); Path = fn.GetFullPath(); } return( &Path ); } //--------------------------------------------------------- CSG_String SG_File_Get_Path_Relative (const SG_Char *Directory, const SG_Char *full_Path) { wxFileName fn(full_Path); fn.MakeRelativeTo(Directory); return( CSG_String(fn.GetFullPath().wc_str()) ); } //--------------------------------------------------------- CSG_String SG_File_Make_Path(const SG_Char *Directory, const SG_Char *Name, const SG_Char *Extension) { wxFileName fn; fn.AssignDir(Directory && *Directory ? Directory : SG_File_Get_Path(Name).c_str()); if( Extension && *Extension ) { fn.SetName (SG_File_Get_Name(Name, false).c_str()); fn.SetExt (Extension); } else { fn.SetFullName (SG_File_Get_Name(Name, true).c_str()); } return( CSG_String(fn.GetFullPath().wc_str()) ); } //--------------------------------------------------------- bool SG_File_Cmp_Extension(const SG_Char *File_Name, const SG_Char *Extension) { wxFileName fn(File_Name); return( fn.GetExt().CmpNoCase(Extension) == 0 ); } //--------------------------------------------------------- bool SG_File_Set_Extension(CSG_String &File_Name, const CSG_String &Extension) { if( File_Name.Length() > 0 && Extension.Length() > 0 ) { wxFileName fn(File_Name.w_str()); fn.SetExt(Extension.w_str()); File_Name = fn.GetFullPath().wc_str(); return( true ); } return( false ); } //--------------------------------------------------------- CSG_String SG_File_Get_Extension(const SG_Char *File_Name) { wxFileName fn(File_Name); return( CSG_String(fn.GetExt().wc_str()) ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- bool SG_Read_Line(FILE *Stream, CSG_String &Line) { char c; if( Stream && !feof(Stream) ) { Line.Clear(); while( !feof(Stream) && (c = fgetc(Stream)) != 0x0A && c != 0x0D ) { Line.Append(c); } return( true ); } return( false ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //--------------------------------------------------------- bool SG_Get_Environment(const CSG_String &Variable, CSG_String *Value) { if( Value == NULL) { return( wxGetEnv(Variable.w_str(), NULL) ); } wxString s; if( wxGetEnv(Variable.w_str(), &s) ) { *Value = s.wc_str(); return( true ); } return( false ); } //--------------------------------------------------------- bool SG_Set_Environment(const CSG_String &Variable, const CSG_String &Value) { return( wxSetEnv(Variable.w_str(), Value.w_str()) ); } /////////////////////////////////////////////////////////// // // // // // // /////////////////////////////////////////////////////////// //---------------------------------------------------------
UoA-eResearch/saga-gis
saga-gis/src/saga_core/saga_api/api_file.cpp
C++
gpl-3.0
17,368
# What's new The contents of this page are copied over from CHANGELOG.md when the Github Action "Build Docs" runs. So, to edit this page, see CHANGELOG.md which does not live in the docs folder, it's at the root of the repository.
Tangerine-Community/Tangerine
docs/whats-new.md
Markdown
gpl-3.0
232
package org.vpac.ndg.query.iteration; import java.util.Collection; import java.util.Iterator; /** * Flattens any number of iterables of the same type. * @author Alex Fraser * * @param <T> The type contained in the iterables. */ public class Flatten<T> implements Iterable<T> { private Collection<? extends Iterable<T>> lists; public Flatten(Collection<? extends Iterable<T>> lists) { this.lists = lists; } @Override public Iterator<T> iterator() { return new FlattenIterator(lists); } final class FlattenIterator implements Iterator<T> { private Iterator<? extends Iterable<T>> outerIter; private Iterator<T> innerIter; public FlattenIterator(Collection<? extends Iterable<T>> lists) { outerIter = lists.iterator(); innerIter = null; } @Override public boolean hasNext() { advanceOuter(); return innerIter != null && innerIter.hasNext(); } void advanceOuter() { if (innerIter != null && innerIter.hasNext()) return; if (outerIter.hasNext()) innerIter = outerIter.next().iterator(); } @Override public T next() { advanceOuter(); return innerIter.next(); } @Override public void remove() { throw new UnsupportedOperationException( "Can't remove value from a flatten."); } } }
vpac-innovations/rsa
src/rsaquery/src/main/java/org/vpac/ndg/query/iteration/Flatten.java
Java
gpl-3.0
1,274
from datetime import timedelta from django import template import ws.utils.dates as date_utils import ws.utils.perms as perm_utils from ws import forms from ws.utils.itinerary import get_cars register = template.Library() @register.inclusion_tag('for_templatetags/show_wimp.html') def show_wimp(wimp): return { 'participant': wimp, } @register.inclusion_tag('for_templatetags/trip_itinerary.html') def trip_itinerary(trip): """Return a stripped form for read-only display. Drivers will be displayed separately, and the 'accuracy' checkbox isn't needed for display. """ if not trip.info: return {'info_form': None} info_form = forms.TripInfoForm(instance=trip.info) info_form.fields.pop('drivers') info_form.fields.pop('accurate') return {'info_form': info_form} @register.inclusion_tag('for_templatetags/trip_info.html', takes_context=True) def trip_info(context, trip, show_participants_if_no_itinerary=False): participant = context['viewing_participant'] # After a sufficiently long waiting period, hide medical information # (We could need medical info a day or two after a trip was due back) # Some trips last for multiple days (trip date is Friday, return is Sunday) # Because we only record a single trip date, give a few extra days' buffer is_old_trip = date_utils.local_date() > (trip.trip_date + timedelta(days=5)) return { 'trip': trip, 'participants': ( trip.signed_up_participants.filter(signup__on_trip=True).select_related( 'emergency_info__emergency_contact' ) ), 'trip_leaders': ( trip.leaders.select_related('emergency_info__emergency_contact') ), 'cars': get_cars(trip), 'show_participants_if_no_itinerary': show_participants_if_no_itinerary, 'hide_sensitive_info': is_old_trip, 'is_trip_leader': perm_utils.leader_on_trip(participant, trip), }
DavidCain/mitoc-trips
ws/templatetags/medical_tags.py
Python
gpl-3.0
1,991
'use strict'; var localConnection; var remoteConnection; var sendChannel; var receiveChannel; var pcConstraint; var dataConstraint; var dataChannelSend = document.querySelector('textarea#dataChannelSend'); var dataChannelReceive = document.querySelector('textarea#dataChannelReceive'); var startButton = document.querySelector('button#commentStartButton'); var sendButton = document.querySelector('button#commentSendButton'); var closeButton = document.querySelector('button#commentCloseButton'); startButton.onclick = createConnection; sendButton.onclick = sendData; closeButton.onclick = closeDataChannels; function enableStartButton() { startButton.disabled = false; } function disableSendButton() { sendButton.disabled = true; } function createConnection() { dataChannelSend.placeholder = ''; var servers = null; pcConstraint = null; dataConstraint = null; trace('Using SCTP based data channels'); // For SCTP, reliable and ordered delivery is true by default. // Add localConnection to global scope to make it visible // from the browser console. window.localConnection = localConnection = new RTCPeerConnection(servers, pcConstraint); trace('Created local peer connection object localConnection'); sendChannel = localConnection.createDataChannel('sendDataChannel', dataConstraint); trace('Created send data channel'); localConnection.onicecandidate = iceCallback1; sendChannel.onopen = onSendChannelStateChange; sendChannel.onclose = onSendChannelStateChange; // Add remoteConnection to global scope to make it visible // from the browser console. window.remoteConnection = remoteConnection = new RTCPeerConnection(servers, pcConstraint); trace('Created remote peer connection object remoteConnection'); remoteConnection.onicecandidate = iceCallback2; remoteConnection.ondatachannel = receiveChannelCallback; localConnection.createOffer().then( gotDescription1, onCreateSessionDescriptionError ); startButton.disabled = true; closeButton.disabled = false; } function onCreateSessionDescriptionError(error) { trace('Failed to create session description: ' + error.toString()); } function sendData() { var data = dataChannelSend.value; sendChannel.send(data); trace('Sent Data: ' + data); } function closeDataChannels() { trace('Closing data channels'); sendChannel.close(); trace('Closed data channel with label: ' + sendChannel.label); receiveChannel.close(); trace('Closed data channel with label: ' + receiveChannel.label); localConnection.close(); remoteConnection.close(); localConnection = null; remoteConnection = null; trace('Closed peer connections'); startButton.disabled = false; sendButton.disabled = true; closeButton.disabled = true; dataChannelSend.value = ''; dataChannelReceive.value = ''; dataChannelSend.disabled = true; disableSendButton(); enableStartButton(); } function gotDescription1(desc) { localConnection.setLocalDescription(desc); trace('Offer from localConnection \n' + desc.sdp); remoteConnection.setRemoteDescription(desc); remoteConnection.createAnswer().then( gotDescription2, onCreateSessionDescriptionError ); } function gotDescription2(desc) { remoteConnection.setLocalDescription(desc); trace('Answer from remoteConnection \n' + desc.sdp); localConnection.setRemoteDescription(desc); } function iceCallback1(event) { trace('local ice callback'); if (event.candidate) { remoteConnection.addIceCandidate( event.candidate ).then( onAddIceCandidateSuccess, onAddIceCandidateError ); trace('Local ICE candidate: \n' + event.candidate.candidate); } } function iceCallback2(event) { trace('remote ice callback'); if (event.candidate) { localConnection.addIceCandidate( event.candidate ).then( onAddIceCandidateSuccess, onAddIceCandidateError ); trace('Remote ICE candidate: \n ' + event.candidate.candidate); } } function onAddIceCandidateSuccess() { trace('AddIceCandidate success.'); } function onAddIceCandidateError(error) { trace('Failed to add Ice Candidate: ' + error.toString()); } function receiveChannelCallback(event) { trace('Receive Channel Callback'); receiveChannel = event.channel; receiveChannel.onmessage = onReceiveMessageCallback; receiveChannel.onopen = onReceiveChannelStateChange; receiveChannel.onclose = onReceiveChannelStateChange; } function onReceiveMessageCallback(event) { trace('Received Message'); dataChannelReceive.value = event.data; } function onSendChannelStateChange() { var readyState = sendChannel.readyState; trace('Send channel state is: ' + readyState); if (readyState === 'open') { dataChannelSend.disabled = false; dataChannelSend.focus(); sendButton.disabled = false; closeButton.disabled = false; } else { dataChannelSend.disabled = true; sendButton.disabled = true; closeButton.disabled = true; } } function onReceiveChannelStateChange() { var readyState = receiveChannel.readyState; trace('Receive channel state is: ' + readyState); } function trace(text) { if (text[text.length - 1] === '\n') { text = text.substring(0, text.length - 1); } if (window.performance) { var now = (window.performance.now() / 1000).toFixed(3); console.log(now + ': ' + text); } else { console.log(text); } }
Kebatoufragile/Videodorant
public/js/comments.js
JavaScript
gpl-3.0
5,410
/* * Copyright 2014 Rohan Garg <rohan@kde.org> * Copyright 2021 Harald Sitter <sitter@kde.org> * * 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) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * 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 "driverevent.h" #include <drivermanager_interface.h> #include <QDBusConnection> #include <QDebug> #include <QApt/Backend> #include <KToolInvocation> #include <KConfig> #include <KConfigGroup> DriverEvent::DriverEvent(QObject *parent) : Event(parent, "Driver") , m_showNotification(false) , m_aptBackendInitialized(false) { qDBusRegisterMetaType<DeviceList>(); show(); } void DriverEvent::show() { if (isHidden()) { return; } if (!m_aptBackendInitialized) { m_aptBackend = new QApt::Backend(this); if (!m_aptBackend->init()) { qWarning() << m_aptBackend->initErrorMessage(); m_aptBackendInitialized = false; } else { m_aptBackendInitialized = true; } } if (m_aptBackendInitialized) { if(m_aptBackend->xapianIndexNeedsUpdate()) { m_aptBackend->updateXapianIndex(); connect(m_aptBackend, SIGNAL(xapianUpdateFinished()), SLOT(updateFinished())); } else { updateFinished(); } } } void DriverEvent::updateFinished() { if (!m_aptBackend->openXapianIndex()) { qDebug() << "Xapian update could not be opened, probably broken."; return; } m_manager = new OrgKubuntuDriverManagerInterface("org.kubuntu.DriverManager", "/DriverManager", QDBusConnection::sessionBus()); // Force no dbus timeout. // There is exactly one method we use and it must always return. The only // situations where it does not return are those when something is terribly // wrong, however we cannot necessarily detect that with an async connection // either, so instead of asyncyfing the connection, we simply force no timeout. // TODO: this may be practical and equivalent to async connection // but is really shitty and should be replaced by async connections. // alas, those have their own unique problems with timer handling in // python... m_manager->setTimeout(INT_MAX); QDBusPendingReply<DeviceList> reply = m_manager->devices(); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onDevicesReady(QDBusPendingCallWatcher*))); } void DriverEvent::onDevicesReady(QDBusPendingCallWatcher *call) { QDBusPendingReply<DeviceList> reply = *call; if (reply.isError()) { qDebug() << "got dbus error; abort"; return; } DeviceList devices = reply.value(); call->deleteLater(); // deep copy, delete caller qDebug() << "data " << devices; KConfig driver_manager("kcmdrivermanagerrc"); KConfigGroup pciGroup( &driver_manager, "PCI" ); foreach (Device device, devices) { if (pciGroup.readEntry(device.id) != QLatin1String("true")) { // Not seen before, check whether we have recommended drivers. for (int i = 0; i < device.drivers.length(); ++i) { // Supposedly Driver is not a pod due to ctor, so it can't // be fully used by QList :'< // Manually iter instead. Driver driver = device.drivers.at(i); // If there is only one driver listed, we consider it an option. // This works around an issue with virtualbox where the one and // only driver is not marked as recommended. However, from // a notification point of view it makes sense to notify about // single-option drivers all the same as even if not considered // recommended they probably should be looked at by the user. if (driver.recommended || device.drivers.length() == 1) { QApt::Package *package = m_aptBackend->package(driver.packageName); if (package) { if (!package->isInstalled()) { m_showNotification = true; break; } } else { qDebug() << "package" << driver.packageName << "could not be found"; } } } } else { qDebug() << device.id << "has already been processed by the KCM"; } } if (m_showNotification) { QString icon = QString("hwinfo"); QString text(i18nc("Notification when additional packages are required for activating proprietary hardware", "Proprietary drivers might be required to enable additional features")); QStringList actions; actions << i18nc("Launches KDE Control Module to manage drivers", "Manage Drivers"); actions << i18nc("Button to dismiss this notification once", "Ignore for now"); actions << i18nc("Button to make this notification never show up again", "Never show again"); Event::show(icon, text, actions); } } void DriverEvent::run() { KToolInvocation::kdeinitExec("kcmshell5", QStringList() << "kcm_driver_manager"); Event::run(); }
KDE/kubuntu-notification-helper
src/daemon/driverevent/driverevent.cpp
C++
gpl-3.0
6,107
/******************************************************************************* * Copyright 2015 Dimitri L. <dimdimdimdim at gmx dot fr> * * 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 <stdafx.h> #include <base.h> #include <sysutils.h> #include <criticalsection.h> #include "keyboard.h" #include "threading.h" // from Geenie.cpp extern uint8_t keyCode; extern AuxKeyboardData auxKeyData; namespace Kernel { namespace Win32 { CalcKeyboardDesc::CalcKeyboardDesc(Device *device) :DeviceDescriptor(device), WaitableObjectRedirect((CalcKeyboard *)device) { } size_t CalcKeyboardDesc::read(void *data, size_t len) { return ((CalcKeyboard *)getDevice())->read(data, len); } CalcKeyboard::CalcKeyboard(DeviceClass *devClass) :Device(devClass) { enable(); } void CalcKeyboard::runHandler() { bool wasEmpty = buffer.isEmpty(); buffer.write(&keyCode, 1); if (wasEmpty) { __disable_irq(); bool resch = setWaitFlagAndWakeupOne(WaitCond::READ_READY); __enable_irq(); if (resch) Scheduler::reschedule(); } } size_t CalcKeyboard::read(void *data, size_t len) { size_t n; synchronized(section) { disable(); n = buffer.read((uint8_t *)data, len); if (buffer.isEmpty()) unsetWaitFlag(WaitCond::READ_READY); enable(); } return n; } ComputerKeyboardDesc::ComputerKeyboardDesc(Device *device) :DeviceDescriptor(device), WaitableObjectRedirect((ComputerKeyboard *)device) { } size_t ComputerKeyboardDesc::read(void *data, size_t len) { return ((ComputerKeyboard *)getDevice())->read(data, len); } ComputerKeyboard::ComputerKeyboard(DeviceClass *devClass) :Device(devClass) { enable(); } void ComputerKeyboard::runHandler() { bool wasEmpty = buffer.isEmpty(); buffer.write(&auxKeyData, 1); if (wasEmpty) { __disable_irq(); bool resch = setWaitFlagAndWakeupOne(WaitCond::READ_READY); __enable_irq(); if (resch) Scheduler::reschedule(); } } size_t ComputerKeyboard::read(void *data, size_t len) { if (len != sizeof(AuxKeyboardData)) gcthrownew(EInvalidArgument); size_t n; synchronized(section) { disable(); n = buffer.read((AuxKeyboardData *)data, 1); if (buffer.isEmpty()) unsetWaitFlag(WaitCond::READ_READY); enable(); } return n * sizeof(AuxKeyboardData); } } }
dimdimdimdim/geenie-firmware
src/system/kernel/archs/win32/keyboard.cpp
C++
gpl-3.0
3,037
package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( strfmt "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/errors" ) // VirtualMachineScaleSetExtensionProfile Describes a virtual machine scale set extension profile. // swagger:model VirtualMachineScaleSetExtensionProfile type VirtualMachineScaleSetExtensionProfile struct { // The virtual machine scale set child extension resources. Extensions []*VirtualMachineScaleSetExtension `json:"extensions"` } // Validate validates this virtual machine scale set extension profile func (m *VirtualMachineScaleSetExtensionProfile) Validate(formats strfmt.Registry) error { var res []error if err := m.validateExtensions(formats); err != nil { // prop res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *VirtualMachineScaleSetExtensionProfile) validateExtensions(formats strfmt.Registry) error { if swag.IsZero(m.Extensions) { // not required return nil } for i := 0; i < len(m.Extensions); i++ { if swag.IsZero(m.Extensions[i]) { // not required continue } if m.Extensions[i] != nil { if err := m.Extensions[i].Validate(formats); err != nil { return err } } } return nil }
jkawamoto/roadie
cloud/azure/compute/models/virtual_machine_scale_set_extension_profile.go
GO
gpl-3.0
1,378
package allegro.input.events; import allegro.math.BitAlgorithms; import java.nio.ByteBuffer; import java.util.ArrayList; /** * Created by LeqxLeqx on 10/25/16. */ public class TimerEvent extends Event { public static int parseEvent(ArrayList<Event> events, byte[] data, int start) { long count; ByteBuffer byteBuffer = ByteBuffer.allocate(8); byteBuffer.put(data, start, 8); byteBuffer.position(0); count = BitAlgorithms.reverseEndianOrder(byteBuffer.getLong()); events.add(new TimerEvent(count)); return start + 8; } public final long count; public TimerEvent(long count) { super(Type.TIMER); this.count = count; } }
LeqxLeqx/jllegro
Java/src/allegro/input/events/TimerEvent.java
Java
gpl-3.0
724
// ****************************************************************************** // Filename: Texture.h // Project: Vogue // Author: Steven Ball // // Purpose: // An OpenGL texture object. // // Revision History: // Initial Revision - 08/06/06 // // Copyright (c) 2005-2016, Steven Ball // ****************************************************************************** #pragma once #ifdef _WIN32 #include <windows.h> #endif //_WIN32 #include <GL/gl.h> #include <GL/glu.h> #pragma comment (lib, "opengl32") #pragma comment (lib, "glu32") #include <string> using namespace std; int LoadFileTGA(const char *filename, unsigned char **pixels, int *width, int *height, bool flipvert); int LoadFileBMP(const char *filename, unsigned char **pixels, int *width, int *height); //int LoadFileJPG(const char *filename, unsigned char **pixels, int *width, int *height); enum TextureFileType { TextureFileType_BMP = 0, TextureFileType_JPG, TextureFileType_TGA, }; class Texture { public: Texture(); ~Texture(); string GetFileName() const { return m_fileName; } int GetWidth(); int GetHeight(); int GetWidthPower2(); int GetHeightPower2(); GLuint GetId() const; TextureFileType GetFileType() const; bool Load(string fileName, int *width, int *height, int *width_power2, int *height_power2, bool refresh); void GenerateEmptyTexture(); void Bind(); private: string m_fileName; int m_width; int m_height; int m_width_power2; int m_height_power2; GLuint m_id; TextureFileType m_filetype; };
AlwaysGeeky/Vogue
source/Renderer/texture.h
C
gpl-3.0
1,526
/* * This file is part of CubeEngine. * CubeEngine is licensed under the GNU General Public License Version 3. * * CubeEngine 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. * * CubeEngine 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 CubeEngine. If not, see <http://www.gnu.org/licenses/>. */ package org.cubeengine.module.locker.data; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.entity.EntityType; import static org.cubeengine.module.locker.data.ProtectionFlag.BLOCK_BREAK; import static org.cubeengine.module.locker.data.ProtectionFlag.BLOCK_EXPLOSION; import static org.cubeengine.module.locker.data.ProtectionFlag.BLOCK_INTERACT; import static org.cubeengine.module.locker.data.ProtectionFlag.BLOCK_REDSTONE; import static org.cubeengine.module.locker.data.ProtectionFlag.ENTITY_DAMAGE; import static org.cubeengine.module.locker.data.ProtectionFlag.ENTITY_INTERACT; import static org.cubeengine.module.locker.data.ProtectionFlag.INVENTORY_HOPPER_PUT; import static org.cubeengine.module.locker.data.ProtectionFlag.INVENTORY_HOPPER_TAKE; import static org.spongepowered.api.block.BlockTypes.*; import static org.spongepowered.api.entity.EntityTypes.*; public enum ProtectedType { CONTAINER(BLOCK_BREAK, BLOCK_EXPLOSION, BLOCK_INTERACT, BLOCK_REDSTONE, INVENTORY_HOPPER_PUT, INVENTORY_HOPPER_TAKE), BLOCK(BLOCK_BREAK, BLOCK_EXPLOSION, BLOCK_INTERACT, BLOCK_REDSTONE), ENTITY_CONTAINER(ENTITY_INTERACT, ENTITY_DAMAGE), ENTITY_LIVING(ENTITY_INTERACT, ENTITY_DAMAGE), ENTITY_VEHICLE(ENTITY_INTERACT, ENTITY_DAMAGE), ENTITY(ENTITY_INTERACT, ENTITY_DAMAGE), ENTITY_CONTAINER_LIVING(ENTITY_INTERACT, ENTITY_DAMAGE), ; private final static Map<BlockType, ProtectedType> blocks = new HashMap<>(); private final static Map<EntityType, ProtectedType> entities = new HashMap<>(); public final Collection<ProtectionFlag> supportedFlags; static { blocks.put(CHEST.get(), CONTAINER); blocks.put(TRAPPED_CHEST.get(), CONTAINER); blocks.put(DISPENSER.get(), CONTAINER); blocks.put(DROPPER.get(), CONTAINER); blocks.put(FURNACE.get(), CONTAINER); blocks.put(BREWING_STAND.get(), CONTAINER); blocks.put(DROPPER.get(), CONTAINER); blocks.put(BEACON.get(), CONTAINER); blocks.put(HOPPER.get(), CONTAINER); entities.put(CHEST_MINECART.get(), ENTITY_CONTAINER); entities.put(HOPPER_MINECART.get(), ENTITY_CONTAINER); entities.put(HORSE.get(), ENTITY_CONTAINER_LIVING); entities.put(LEASH_KNOT.get(), ENTITY); entities.put(PAINTING.get(), ENTITY); entities.put(ITEM_FRAME.get(), ENTITY); entities.put(FURNACE_MINECART.get(), ENTITY); entities.put(TNT_MINECART.get(), ENTITY); entities.put(SPAWNER_MINECART.get(), ENTITY); entities.put(BOAT.get(), ENTITY_VEHICLE); entities.put(MINECART.get(), ENTITY_VEHICLE); } ProtectedType(ProtectionFlag... supportedFlags) { this.supportedFlags = Arrays.asList(supportedFlags); } public static ProtectedType getProtectedType(BlockType material) { return blocks.getOrDefault(material, BLOCK); } public static ProtectedType getProtectedType(EntityType type) { return entities.getOrDefault(type, ENTITY); } }
CubeEngine/modules-main
locker/src/main/java/org/cubeengine/module/locker/data/ProtectedType.java
Java
gpl-3.0
3,909
<?php namespace PacksAnSpielBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use PacksAnSpielBundle\Repository\TeamRepository; use PacksAnSpielBundle\Repository\GameRepository; use PacksAnSpielBundle\Entity\Team; /** * ActionLog controller. * * @Route("admin/logs") */ class ActionLogController extends Controller { /** * Lists last 100 game action logs. * * @Route("/", name="actionlog_index") */ public function indexAction(Request $request) { $em = $this->getDoctrine()->getManager(); $form = $this->createFormBuilder() ->add('gameId', TextType::class, array('label' => false, 'required' => false)) ->add('teamId', TextType::class, array('label' => false, 'required' => false)) ->add('logLevel', ChoiceType::class, array( 'choices' => array('INFO' => '1', 'WARNING' => '2', 'CRITICAL' => '3'), 'required' => false )) ->add('submit', SubmitType::class) ->getForm(); $actionLogs =[]; if ($request->getMethod() == 'POST') { $form->handleRequest($request); // data is an array with "gameId", "teamId", and "logLevel" keys $data = $form->getData(); if (null == $data['gameId'] && null == $data['teamId'] & null == $data['logLevel']) { $actionLogs = $em->getRepository('PacksAnSpielBundle:ActionLog')->findAll(); } // check for filters if ($data['gameId'] !== null) { $filteredLogs = $em->getRepository('PacksAnSpielBundle:ActionLog')->findByGame($data['gameId']); foreach ($filteredLogs as $filteredLog) { array_push($actionLogs, $filteredLog); } } if ($data['teamId'] !== null) { $filteredLogs = $em->getRepository('PacksAnSpielBundle:ActionLog')->findByTeam($data['teamId']); foreach ($filteredLogs as $filteredLog) { array_push($actionLogs, $filteredLog); } } if ($data['logLevel'] !== null) { $filteredLogs = $em->getRepository('PacksAnSpielBundle:ActionLog')->findByLogLevel($data['logLevel']); foreach ($filteredLogs as $filteredLog) { array_push($actionLogs, $filteredLog); } } // if none was set if (null == $data['gameId'] && null == $data['teamId'] & null == $data['logLevel']) { return $this->render('PacksAnSpielBundle::admin/actionlog/index.html.twig', array( 'logs' => array(array('timestamp' => 'no data', 'game' => 'no data', 'group' => 'no data', 'text' => 'no data', 'loglvl' => 'NONE')), 'form' => $form->createView() )); } } // if actionLogs still empty (e.g. GET request) if (empty($actionLogs)) { $actionLogs = $em->getRepository('PacksAnSpielBundle:ActionLog')->findAll(); } $logs = []; foreach ($actionLogs as $index => $actionLog) { $logs[$index]['timestamp'] = date("d.m.Y H:i:s", $actionLog->getTimeStamp()); $logs[$index]['game'] = $actionLog->getGame()->getName(); $logs[$index]['group'] = $actionLog->getTeam()->getId(); $logs[$index]['text'] = $actionLog->getLogText(); switch ($actionLog->getLogLevel()) { case 1: $logs[$index]['loglvl'] = 'INFO';break; case 2: $logs[$index]['loglvl'] = 'WARN';break; case 3: $logs[$index]['loglvl'] = 'CRITICAL';break; default: $logs[$index]['loglvl'] = 'NONE'; } } return $this->render('PacksAnSpielBundle::admin/actionlog/index.html.twig', array( 'logs' => $logs, 'form' => $form->createView() )); } }
schroeder/packsanspiel
src/PacksAnSpielBundle/Controller/ActionLogController.php
PHP
gpl-3.0
4,391
/** \file ZLLSensors.cpp Copyright Notice\n Copyright (C) 2020 Jan Rogall - developer\n This file is part of hueplusplus. hueplusplus 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. hueplusplus 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 hueplusplus. If not, see <http://www.gnu.org/licenses/>. */ #include "hueplusplus/ZLLSensors.h" #include "hueplusplus/HueExceptionMacro.h" namespace hueplusplus { namespace sensors { constexpr int ZGPSwitch::c_button1; constexpr int ZGPSwitch::c_button2; constexpr int ZGPSwitch::c_button3; constexpr int ZGPSwitch::c_button4; constexpr const char* ZGPSwitch::typeStr; bool ZGPSwitch::isOn() const { return state.getValue().at("config").at("on").get<bool>(); } void ZGPSwitch::setOn(bool on) { sendPutRequest("/config", nlohmann::json {{"on", on}}, CURRENT_FILE_INFO); } int ZGPSwitch::getButtonEvent() const { return state.getValue().at("state").at("buttonevent").get<int>(); } constexpr int ZLLSwitch::c_ON_INITIAL_PRESS; constexpr int ZLLSwitch::c_ON_HOLD; constexpr int ZLLSwitch::c_ON_SHORT_RELEASED; constexpr int ZLLSwitch::c_ON_LONG_RELEASED; constexpr int ZLLSwitch::c_UP_INITIAL_PRESS; constexpr int ZLLSwitch::c_UP_HOLD; constexpr int ZLLSwitch::c_UP_SHORT_RELEASED; constexpr int ZLLSwitch::c_UP_LONG_RELEASED; constexpr int ZLLSwitch::c_DOWN_INITIAL_PRESS; constexpr int ZLLSwitch::c_DOWN_HOLD; constexpr int ZLLSwitch::c_DOWN_SHORT_RELEASED; constexpr int ZLLSwitch::c_DOWN_LONG_RELEASED; constexpr int ZLLSwitch::c_OFF_INITIAL_PRESS; constexpr int ZLLSwitch::c_OFF_HOLD; constexpr int ZLLSwitch::c_OFF_SHORT_RELEASED; constexpr int ZLLSwitch::c_OFF_LONG_RELEASED; constexpr const char* ZLLSwitch::typeStr; bool ZLLSwitch::isOn() const { return state.getValue().at("config").at("on").get<bool>(); } void ZLLSwitch::setOn(bool on) { sendPutRequest("/config", nlohmann::json {{"on", on}}, CURRENT_FILE_INFO); } bool ZLLSwitch::hasBatteryState() const { return state.getValue().at("config").count("battery") != 0; } int ZLLSwitch::getBatteryState() const { return state.getValue().at("config").at("battery").get<int>(); } Alert ZLLSwitch::getLastAlert() const { std::string alert = state.getValue().at("config").at("alert").get<std::string>(); return alertFromString(alert); } void ZLLSwitch::sendAlert(Alert type) { sendPutRequest("/config", nlohmann::json {{"alert", alertToString(type)}}, CURRENT_FILE_INFO); } bool ZLLSwitch::isReachable() const { return state.getValue().at("config").at("reachable").get<bool>(); } int ZLLSwitch::getButtonEvent() const { return state.getValue().at("state").at("buttonevent").get<int>(); } time::AbsoluteTime ZLLSwitch::getLastUpdated() const { const nlohmann::json& stateJson = state.getValue().at("state"); auto it = stateJson.find("lastupdated"); if (it == stateJson.end() || !it->is_string() || *it == "none") { return time::AbsoluteTime(std::chrono::system_clock::time_point(std::chrono::seconds {0})); } return time::AbsoluteTime::parseUTC(it->get<std::string>()); } constexpr const char* ZLLPresence::typeStr; bool ZLLPresence::isOn() const { return state.getValue().at("config").at("on").get<bool>(); } void ZLLPresence::setOn(bool on) { sendPutRequest("/config", nlohmann::json {{"on", on}}, CURRENT_FILE_INFO); } bool ZLLPresence::hasBatteryState() const { return state.getValue().at("config").count("battery") != 0; } int ZLLPresence::getBatteryState() const { return state.getValue().at("config").at("battery").get<int>(); } Alert ZLLPresence::getLastAlert() const { std::string alert = state.getValue().at("config").at("alert").get<std::string>(); return alertFromString(alert); } void ZLLPresence::sendAlert(Alert type) { sendPutRequest("/config", nlohmann::json {{"alert", alertToString(type)}}, CURRENT_FILE_INFO); } bool ZLLPresence::isReachable() const { return state.getValue().at("config").at("reachable").get<bool>(); } int ZLLPresence::getSensitivity() const { return state.getValue().at("config").at("sensitivity").get<int>(); } int ZLLPresence::getMaxSensitivity() const { return state.getValue().at("config").at("sensitivitymax").get<int>(); } void ZLLPresence::setSensitivity(int sensitivity) { sendPutRequest("/config", nlohmann::json {{"sensitivity", sensitivity}}, CURRENT_FILE_INFO); } bool ZLLPresence::getPresence() const { return state.getValue().at("state").at("presence").get<bool>(); } time::AbsoluteTime ZLLPresence::getLastUpdated() const { const nlohmann::json& stateJson = state.getValue().at("state"); auto it = stateJson.find("lastupdated"); if (it == stateJson.end() || !it->is_string() || *it == "none") { return time::AbsoluteTime(std::chrono::system_clock::time_point(std::chrono::seconds {0})); } return time::AbsoluteTime::parseUTC(it->get<std::string>()); } constexpr const char* ZLLTemperature::typeStr; bool ZLLTemperature::isOn() const { return state.getValue().at("config").at("on").get<bool>(); } void ZLLTemperature::setOn(bool on) { sendPutRequest("/config", {{"on", on}}, CURRENT_FILE_INFO); } bool ZLLTemperature::hasBatteryState() const { return state.getValue().at("config").count("battery") != 0; } int ZLLTemperature::getBatteryState() const { return state.getValue().at("config").at("battery").get<int>(); } Alert ZLLTemperature::getLastAlert() const { std::string alert = state.getValue().at("config").at("alert").get<std::string>(); return alertFromString(alert); } void ZLLTemperature::sendAlert(Alert type) { sendPutRequest("/config", nlohmann::json {{"alert", alertToString(type)}}, CURRENT_FILE_INFO); } bool ZLLTemperature::isReachable() const { return state.getValue().at("config").at("reachable").get<bool>(); } int ZLLTemperature::getTemperature() const { return state.getValue().at("state").at("temperature").get<int>(); } time::AbsoluteTime ZLLTemperature::getLastUpdated() const { const nlohmann::json& stateJson = state.getValue().at("state"); auto it = stateJson.find("lastupdated"); if (it == stateJson.end() || !it->is_string() || *it == "none") { return time::AbsoluteTime(std::chrono::system_clock::time_point(std::chrono::seconds{ 0 })); } return time::AbsoluteTime::parseUTC(it->get<std::string>()); } constexpr const char* ZLLLightLevel::typeStr; bool ZLLLightLevel::isOn() const { return state.getValue().at("config").at("on").get<bool>(); } void ZLLLightLevel::setOn(bool on) { sendPutRequest("/config", {{"on", on}}, CURRENT_FILE_INFO); } bool ZLLLightLevel::hasBatteryState() const { return state.getValue().at("config").count("battery") != 0; } int ZLLLightLevel::getBatteryState() const { return state.getValue().at("config").at("battery").get<int>(); } bool ZLLLightLevel::isReachable() const { return state.getValue().at("config").at("reachable").get<bool>(); } int ZLLLightLevel::getDarkThreshold() const { return state.getValue().at("config").at("tholddark").get<int>(); } void ZLLLightLevel::setDarkThreshold(int threshold) { sendPutRequest("/config", nlohmann::json {{"tholddark", threshold}}, CURRENT_FILE_INFO); } int ZLLLightLevel::getThresholdOffset() const { return state.getValue().at("config").at("tholdoffset").get<int>(); } void ZLLLightLevel::setThresholdOffset(int offset) { sendPutRequest("/config", nlohmann::json {{"tholdoffset", offset}}, CURRENT_FILE_INFO); } int ZLLLightLevel::getLightLevel() const { return state.getValue().at("state").at("lightlevel").get<int>(); } bool ZLLLightLevel::isDark() const { return state.getValue().at("state").at("dark").get<bool>(); } bool ZLLLightLevel::isDaylight() const { return state.getValue().at("state").at("daylight").get<bool>(); } time::AbsoluteTime ZLLLightLevel::getLastUpdated() const { const nlohmann::json& stateJson = state.getValue().at("state"); auto it = stateJson.find("lastupdated"); if (it == stateJson.end() || !it->is_string() || *it == "none") { return time::AbsoluteTime(std::chrono::system_clock::time_point(std::chrono::seconds {0})); } return time::AbsoluteTime::parseUTC(it->get<std::string>()); } detail::ConditionHelper<bool> makeConditionDark(const ZLLLightLevel& sensor) { return detail::ConditionHelper<bool>("/sensors/" + std::to_string(sensor.getId()) + "/state/dark"); } detail::ConditionHelper<bool> makeConditionDaylight(const ZLLLightLevel& sensor) { return detail::ConditionHelper<bool>("/sensors/" + std::to_string(sensor.getId()) + "/state/daylight"); } detail::ConditionHelper<int> makeConditionLightLevel(const ZLLLightLevel& sensor) { return detail::ConditionHelper<int>("/sensors/" + std::to_string(sensor.getId()) + "/state/lightlevel"); } } // namespace sensors } // namespace hueplusplus
enwi/hueplusplus
src/ZLLSensors.cpp
C++
gpl-3.0
9,345
#!/bin/bash #----------------MetaCentrum---------------- #PBS -l walltime=24:00:00 #PBS -l select=1:ncpus=1:mem=8gb:scratch_local=8gb #PBS -j oe #PBS -N HybPhyloMaker8g_BUCKy #PBS -m abe #-------------------HYDRA------------------- #$ -S /bin/bash #$ -q mThC.q #$ -l mres=6G,h_data=6G,h_vmem=6G #$ -cwd #$ -j y #$ -N HybPhyloMaker8g_BUCKy #$ -o HybPhyloMaker8g_BUCKy.log # ******************************************************************************** # * HybPhyloMaker - Pipeline for Hyb-Seq data processing and tree building * # * https://github.com/tomas-fer/HybPhyloMaker * # * Script 08g - BUCKy concordant analysis * # * v.1.8.0a * # * Tomas Fer, Dept. of Botany, Charles University, Prague, Czech Republic, 2021 * # * tomas.fer@natur.cuni.cz * # ******************************************************************************** #Compute species tree and CF from selected concatenated genes #Take genes specified in /71selected${MISSINGPERCENT}/selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}.txt #from /71selected/deleted_above${MISSINGPERCENT} #Run first #(1) HybPhyloMaker5_missingdataremoval.sh with the same ${MISSINGPERCENT} and ${SPECIESPRESENCE} values #Complete path and set configuration for selected location if [[ $PBS_O_HOST == *".cz" ]]; then echo -e "\nHybPhyloMaker8g is running on MetaCentrum..." #settings for MetaCentrum #Move to scratch cd $SCRATCHDIR #Copy file with settings from home and set variables from settings.cfg cp $PBS_O_WORKDIR/settings.cfg . . settings.cfg . /packages/run/modules-2.0/init/bash path=/storage/$server/home/$LOGNAME/$data source=/storage/$server/home/$LOGNAME/HybSeqSource #Add necessary modules module add bucky-1.4.4 module add R-3.4.3-gcc #Set package library for R export R_LIBS="/storage/$server/home/$LOGNAME/Rpackages" elif [[ $HOSTNAME == compute-*-*.local ]]; then echo -e "\nHybPhyloMaker8g is running on Hydra..." #settings for Hydra #set variables from settings.cfg . settings.cfg path=../$data source=../HybSeqSource #Make and enter work directory mkdir -p workdir08g cd workdir08g #Add necessary modules module load bioinformatics/bucky/1.4.4 module load tools/R/3.4.1 else echo -e "\nHybPhyloMaker8g is running locally..." #settings for local run #set variables from settings.cfg . settings.cfg path=../$data source=../HybSeqSource #Make and enter work directory mkdir -p workdir08g cd workdir08g fi #Setting for the case when working with cpDNA if [[ $cp =~ "yes" ]]; then echo -en "Working with cpDNA" type="cp" else echo -en "Working with exons" type="exons" fi #Settings for selection and (un)corrected reading frame if [ -z "$selection" ]; then if [[ $corrected =~ "yes" ]]; then mafftpath=$type/61mafft_corrected alnpath=$type/80concatenated_exon_alignments_corrected alnpathselected=$type/81selected_corrected treepath=$type/82trees_corrected echo -en "...with corrected reading frame" else mafftpath=$type/60mafft alnpath=$type/70concatenated_exon_alignments alnpathselected=$type/71selected treepath=$type/72trees fi else if [[ $corrected =~ "yes" ]]; then mafftpath=$type/$selection/61mafft_corrected alnpath=$type/$selection/80concatenated_exon_alignments_corrected alnpathselected=$type/$selection/81selected_corrected treepath=$type/$selection/82trees_corrected echo -en "...with corrected reading frame...and for selection: $selection" else mafftpath=$type/$selection/60mafft alnpath=$type/$selection/70concatenated_exon_alignments alnpathselected=$type/$selection/71selected treepath=$type/$selection/72trees echo -en "...and for selection: $selection" fi fi #Check necessary file echo -ne "\nTesting if input data are available..." if [[ $update =~ "yes" ]]; then if [ -f "$path/${alnpathselected}${MISSINGPERCENT}/updatedSelectedGenes/selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}_update.txt" ]; then if [ 0 -lt $(ls $path/${alnpathselected}${MISSINGPERCENT}/deleted_above${MISSINGPERCENT}/*ssembly_*_modif${MISSINGPERCENT}.fas 2>/dev/null | wc -w) ]; then echo -e "OK\n" else echo -e "no alignment files in FASTA format found in '$path/${alnpathselected}${MISSINGPERCENT}/deleted_above${MISSINGPERCENT}'. Exiting..." rm -d ../workdir08e 2>/dev/null exit 3 fi else echo -e "'$path/${alnpathselected}${MISSINGPERCENT}/updatedSelectedGenes/selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}_update.txt' is missing. Exiting...\n" rm -d ../workdir08e 2>/dev/null exit 3 fi else if [ -f "$path/${alnpathselected}${MISSINGPERCENT}/selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}.txt" ]; then if [ 0 -lt $(ls $path/${alnpathselected}${MISSINGPERCENT}/deleted_above${MISSINGPERCENT}/*ssembly_*_modif${MISSINGPERCENT}.fas 2>/dev/null | wc -w) ]; then echo -e "OK\n" else echo -e "no alignment files in FASTA format found in '$path/${alnpathselected}${MISSINGPERCENT}/deleted_above${MISSINGPERCENT}'. Exiting..." rm -d ../workdir08e 2>/dev/null exit 3 fi else echo -e "'$path/${alnpathselected}${MISSINGPERCENT}/selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}.txt' is missing. Exiting...\n" rm -d ../workdir08e 2>/dev/null exit 3 fi fi #Test if folder for results exits if [[ $update =~ "yes" ]]; then if [ -d "$path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/update/species_trees/BUCKy" ]; then echo -e "Directory '$path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/update/species_trees/BUCKy' already exists. Delete it or rename before running this script again. Exiting...\n" rm -d ../workdir08e 2>/dev/null exit 3 fi else if [ -d "$path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/species_trees/BUCKy" ]; then echo -e "Directory '$path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/species_trees/BUCKy' already exists. Delete it or rename before running this script again. Exiting...\n" rm -d ../workdir08e 2>/dev/null exit 3 fi fi if [[ ! $location == "1" ]]; then if [ "$(ls -A ../workdir08g)" ]; then echo -e "Directory 'workdir08g' already exists and is not empty. Delete it or rename before running this script again. Exiting...\n" rm -d ../workdir08e 2>/dev/null exit 3 fi fi #Write log logname=HPM8g echo -e "HybPhyloMaker8g: BUCKy concordant analysis" > ${logname}.log if [[ $PBS_O_HOST == *".cz" ]]; then echo -e "run on MetaCentrum: $PBS_O_HOST" >> ${logname}.log elif [[ $HOSTNAME == compute-*-*.local ]]; then echo -e "run on Hydra: $HOSTNAME" >> ${logname}.log else echo -e "local run: "`hostname`"/"`whoami` >> ${logname}.log fi echo -e "\nBegin:" `date '+%A %d-%m-%Y %X'` >> ${logname}.log echo -e "\nSettings" >> ${logname}.log if [[ $PBS_O_HOST == *".cz" ]]; then printf "%-25s %s\n" `echo -e "\nServer:\t$server"` >> ${logname}.log fi for set in data selection cp corrected update MISSINGPERCENT SPECIESPRESENCE tree FastTreeBoot nrbucky nrruns nrchains alpha; do printf "%-25s %s\n" `echo -e "${set}:\t" ${!set}` >> ${logname}.log done if [ ! -z "$selection" ]; then echo -e "\nList of excluded samples" >> ${logname}.log cat $source/excludelist.txt >> ${logname}.log echo >> ${logname}.log fi #Add necessary scripts and files #cp $source/readWriteTrees.R . #Copy list of genes if [[ $update =~ "yes" ]]; then cp $path/${alnpathselected}${MISSINGPERCENT}/updatedSelectedGenes/selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}_update.txt . mv selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}_update.txt selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}.txt else cp $path/${alnpathselected}${MISSINGPERCENT}/selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}.txt . fi # Make new dir for results if [[ $update =~ "yes" ]]; then mkdir -p $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/update/species_trees mkdir $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/update/species_trees/BUCKy mkdir $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/update/species_trees/BUCKy/output mkdir $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/update/species_trees/BUCKy/input_files else mkdir -p $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/species_trees mkdir $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/species_trees/BUCKy mkdir $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/species_trees/BUCKy/output mkdir $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/species_trees/BUCKy/input_files fi #Copy bootrapped gene tree files (if tree=RAxML or tree=FastTree and FastTreeBoot=yes) if [[ $tree =~ "RAxML" ]]; then #Copy RAxML bootstraped trees if [[ $update =~ "yes" ]]; then cp $path/${alnpathselected}${MISSINGPERCENT}/updatedSelectedGenes/selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}_update.txt . for i in $(cat selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}_update.txt); do cp $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/RAxML/RAxML_bootstrap*ssembly_${i}_modif${MISSINGPERCENT}.result . done else cp $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/RAxML/RAxML_bootstrap* . fi #Make a list of bootstraped trees ls *bootstrap* > bs-files.txt elif [[ $tree =~ "FastTree" && $FastTreeBoot =~ "yes" ]]; then #Copy FastTree bootstraped trees if [[ $update =~ "yes" ]]; then cp $path/${alnpathselected}${MISSINGPERCENT}/updatedSelectedGenes/selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}_update.txt . for i in $(cat selected_genes_${MISSINGPERCENT}_${SPECIESPRESENCE}_update.txt); do cp $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/FastTree/*ssembly_${i}_*.boot.fast.trees . done else cp $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/FastTree/*.boot.fast.trees . fi #Make a list of bootstraped trees ls *.boot.fast.trees > bs-files.txt fi if [[ $cp =~ "yes" ]]; then #Removing '_cpDNA' from gene trees in trees.newick if [ -d "boot" ]; then sed -i.bak 's/_cpDNA//g' * fi fi # Modify files with bootstrap trees - write as NEXUS and make them compatible with BUCKy for file in $(cat bs-files.txt); do #read newick file and write nexus R -e "library(ape); args <- commandArgs(); name <- args[4]; trees<-read.tree(name); write.nexus(trees, file=\"trees.nex\")" $file > /dev/null #R --slave -f readWriteTrees.R $file #add increasing number after 'TREE' perl -pe 's/\bTREE\b/$& . ++$count/ge' trees.nex > trees_modif.nex #remove ' * UNTITLED' sed -i 's/ \* UNTITLED//' trees_modif.nex #remove ' [&U]' sed -i 's/ \[\&U\]//' trees_modif.nex #change case in 'BEGIN TREES' (to avoid modification in next step) sed -i s'/BEGIN TREES/begin trees/' trees_modif.nex #change 'TREE' to 'tree rep.' sed -i 's/TREE/tree rep\./' trees_modif.nex rm trees.nex rm $file mv trees_modif.nex $file #prepare input file for BUCKy mbsum -n 0 -o $file.in $file done # Run BUCKy ls *.in > bucky_input.txt #Select only the last part of the $data (i.e., after the last '/') datamodif=$(echo $data | awk -F "/" '{ print $NF}') #a=alpha, n=number of chain steps, k=number of runs, c=number of chains bucky -i bucky_input.txt -o $datamodif -a $alpha -n $nrbucky -k $nrruns -c $nrchains #Modify BUCKy output: extract trees in NEXUS format echo -e "#NEXUS\nbegin trees;" > tree.tre #Copy 'translate' block everything from 'translate' to ';' sed -n '/translate/,/;/p' ${datamodif}.concordance >> tree.tre cat tree.tre > BUCKy_popultree.newick cat tree.tre > BUCKy_popultreeBL.newick cat tree.tre > BUCKy_conctree.newick cat tree.tre > BUCKy_conctreeCF.newick #Extract 'Population Tree' (the line matching and one following line), change EOL to space and change name to conform NEXUS standards grep -a1 "^Population Tree:" ${datamodif}.concordance | tr '\n' ' ' | sed 's/ Population Tree:/tree PopulationTree =/' >> BUCKy_popultree.newick echo -e "\nEND;" >> BUCKy_popultree.newick #Modify to NEWICK R -e "library(ape); args <- commandArgs(); name <- args[4]; trees<-read.nexus(name); write.tree(trees, file=\"BUCKy_popultree.tre\")" BUCKy_popultree.newick > /dev/null #Extract 'Population Tree, With Branch Lengths' (the line matching and one following line), change EOL to space and change name to conform NEXUS standards grep -a1 "^Population Tree, With Branch Lengths" ${datamodif}.concordance | tr '\n' ' ' | sed 's/ Population Tree, With Branch Lengths In Estimated Coalescent Units:/tree PopulationTreeWithBranchLengthsInEstimatedCoalescentUnits =/' >> BUCKy_popultreeBL.newick echo -e "\nEND;" >> BUCKy_popultreeBL.newick #Modify to NEWICK R -e "library(ape); args <- commandArgs(); name <- args[4]; trees<-read.nexus(name); write.tree(trees, file=\"BUCKy_popultreeBL.tre\")" BUCKy_popultreeBL.newick > /dev/null #Extract 'Primary Concordance Tree Topology' (the line matching and one following line), change EOL to space and change name to conform NEXUS standards grep -a1 "^Primary Concordance Tree Topology" ${datamodif}.concordance | tr '\n' ' ' | sed 's/ Primary Concordance Tree Topology:/tree PrimaryConcordanceTreeTopology =/' >> BUCKy_conctree.newick echo -e "\nEND;" >> BUCKy_conctree.newick #Modify to NEWICK R -e "library(ape); args <- commandArgs(); name <- args[4]; trees<-read.nexus(name); write.tree(trees, file=\"BUCKy_conctree.tre\")" BUCKy_conctree.newick > /dev/null #Extract 'Primary Concordance Tree with' (the line matching and one following line), change EOL to space and change name to conform NEXUS standards grep -a1 "^Primary Concordance Tree with" ${datamodif}.concordance | tr '\n' ' ' | sed 's/ Primary Concordance Tree with Sample Concordance Factors:/tree PrimaryConcordanceTreewithSampleConcordanceFactors =/' >> BUCKy_conctreeCF.newick echo -e "\nEND;" >> BUCKy_conctreeCF.newick #Modify to NEWICK R -e "library(ape); args <- commandArgs(); name <- args[4]; trees<-read.nexus(name); write.tree(trees, file=\"BUCKy_conctreeCF.tre\")" BUCKy_conctreeCF.newick > /dev/null rm tree.tre # Copy results to home if [[ $update =~ "yes" ]]; then cp ${datamodif}* $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/update/species_trees/BUCKy/output cp BUCKy*.tre $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/update/species_trees/BUCKy cp *.in $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/update/species_trees/BUCKy/input_files else cp ${datamodif}* $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/species_trees/BUCKy/output cp BUCKy*.tre $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/species_trees/BUCKy cp *.in $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/species_trees/BUCKy/input_files fi #Copy log to home echo -e "\nEnd:" `date '+%A %d-%m-%Y %X'` >> ${logname}.log if [[ $update =~ "yes" ]]; then cp ${logname}.log $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/update/species_trees/BUCKy else cp ${logname}.log $path/${treepath}${MISSINGPERCENT}_${SPECIESPRESENCE}/${tree}/species_trees/BUCKy fi #Clean scratch/work directory if [[ $PBS_O_HOST == *".cz" ]]; then #delete scratch if [[ ! $SCRATCHDIR == "" ]]; then rm -rf $SCRATCHDIR/* fi else cd .. rm -r workdir08g fi echo -e "HybPhyloMaker 8g finished...\n"
tomas-fer/HybPhyloMaker
HybPhyloMaker8g_BUCKy.sh
Shell
gpl-3.0
15,317
\hypertarget{classns3_1_1PLC__Phy}{\section{ns3\-:\-:\-P\-L\-C\-\_\-\-Phy \-Class \-Reference} \label{classns3_1_1PLC__Phy}\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} } {\ttfamily \#include $<$plc-\/phy.\-h$>$} \-Inheritance diagram for ns3\-:\-:\-P\-L\-C\-\_\-\-Phy\-:\begin{figure}[H] \begin{center} \leavevmode \includegraphics[height=4.000000cm]{classns3_1_1PLC__Phy} \end{center} \end{figure} \subsection*{\-Public \-Member \-Functions} \begin{DoxyCompactItemize} \item bool \hyperlink{classns3_1_1PLC__Phy_a4087fbae09bdb778285c0e7cdc307d2e}{\-Start\-Tx} (\-Ptr$<$ \-Packet $>$ p) \item void \hyperlink{classns3_1_1PLC__Phy_abe32cc0f1c2e7c9de36a37812423df8e}{\-Start\-Rx} (\-Ptr$<$ const \-Packet $>$ p, uint32\-\_\-t tx\-Id, \-Ptr$<$ \-Spectrum\-Value $>$ \&rx\-Psd, \-Time duration, \-Ptr$<$ const \hyperlink{classns3_1_1PLC__TrxMetaInfo}{\-P\-L\-C\-\_\-\-Trx\-Meta\-Info} $>$ meta\-Info) \item void \hyperlink{classns3_1_1PLC__Phy_a37c13147b5d5cb71843be91c1654fc18}{\-Rx\-Psd\-Changed} (uint32\-\_\-t tx\-Id, \-Ptr$<$ \-Spectrum\-Value $>$ new\-Rx\-Psd) \item \-Ptr$<$ \hyperlink{classns3_1_1PLC__Node}{\-P\-L\-C\-\_\-\-Node} $>$ \hyperlink{classns3_1_1PLC__Phy_ac671d3c0e8fbe3792f4ee16e7f8998a2}{\-Get\-Node} (void) \item void \hyperlink{classns3_1_1PLC__Phy_a970811df6124983c58f6b578a986f336}{\-Set\-Data\-Frame\-Sent\-Callback} (\-P\-L\-C\-\_\-\-Phy\-Data\-Frame\-Sent\-Callback c) \item void \hyperlink{classns3_1_1PLC__Phy_abd23f344001a334bc6b2981e1f9e096d}{\-Set\-Receive\-Success\-Callback} (\-Phy\-Rx\-End\-Ok\-Callback c) \item void \hyperlink{classns3_1_1PLC__Phy_a67ae8c7bf4a78a5788408f507b179bcc}{\-Set\-Receive\-Error\-Callback} (\-Phy\-Rx\-End\-Error\-Callback c) \item \hyperlink{classns3_1_1PLC__ChannelTransferImpl}{\-P\-L\-C\-\_\-\-Channel\-Transfer\-Impl} $\ast$ \hyperlink{classns3_1_1PLC__Phy_a2901b7bc2979a2637c665c5501ef6d4a}{\-Get\-Channel\-Transfer\-Impl} (\-Ptr$<$ \hyperlink{classns3_1_1PLC__Phy}{\-P\-L\-C\-\_\-\-Phy} $>$ rx\-Phy) \item \-Ptr$<$ \hyperlink{classns3_1_1PLC__ValueBase}{\-P\-L\-C\-\_\-\-Transfer\-Base} $>$ \hyperlink{classns3_1_1PLC__Phy_a5c9c1582a62bd748c8b09b294eb95a83}{\-Get\-Channel\-Transfer\-Vector} (\-Ptr$<$ \hyperlink{classns3_1_1PLC__Phy}{\-P\-L\-C\-\_\-\-Phy} $>$ rx\-Phy) \item void \hyperlink{classns3_1_1PLC__Phy_a51e432fe0945a6b810e0f5d240b2ff55}{\-Notify\-Data\-Frame\-Sent} (void) \end{DoxyCompactItemize} \subsection*{\-Static \-Public \-Member \-Functions} \begin{DoxyCompactItemize} \item \hypertarget{classns3_1_1PLC__Phy_af2c0f72bd84e27254b7cabc6ad06e3ed}{static \-Type\-Id {\bfseries \-Get\-Type\-Id} (void)}\label{classns3_1_1PLC__Phy_af2c0f72bd84e27254b7cabc6ad06e3ed} \item static void \hyperlink{classns3_1_1PLC__Phy_a5d5a1f64272f35b2355750e77c0d2868}{\-Set\-Symbol\-Duration} (\-Time t\-Symbol) \begin{DoxyCompactList}\small\item\em \-Set the global symbol duration value for all \-P\-H\-Ys. \end{DoxyCompactList}\item static \-Time \hyperlink{classns3_1_1PLC__Phy_a407d28e0eaa83475f931038c94cd4381}{\-Get\-Symbol\-Duration} (void) \end{DoxyCompactItemize} \subsection*{\-Protected \-Member \-Functions} \begin{DoxyCompactItemize} \item \hypertarget{classns3_1_1PLC__Phy_a614fcc21473fed15ea0a56f86a0e3628}{virtual void {\bfseries \-Do\-Start} (void)}\label{classns3_1_1PLC__Phy_a614fcc21473fed15ea0a56f86a0e3628} \item \hypertarget{classns3_1_1PLC__Phy_a5654398d73868f256bd338a5bd64229f}{virtual void {\bfseries \-Do\-Dispose} (void)}\label{classns3_1_1PLC__Phy_a5654398d73868f256bd338a5bd64229f} \item \hypertarget{classns3_1_1PLC__Phy_a29adea495ce0dfd3299766982ed5b0fe}{virtual bool {\bfseries \-Do\-Start\-Tx} (\-Ptr$<$ \-Packet $>$ p)=0}\label{classns3_1_1PLC__Phy_a29adea495ce0dfd3299766982ed5b0fe} \item \hypertarget{classns3_1_1PLC__Phy_a46b98bd3de07f51cfa53af58fa20f1cd}{virtual void {\bfseries \-Do\-Start\-Rx} (\-Ptr$<$ const \-Packet $>$ p, uint32\-\_\-t tx\-Id, \-Ptr$<$ \-Spectrum\-Value $>$ \&rx\-Psd, \-Time duration, \-Ptr$<$ const \hyperlink{classns3_1_1PLC__TrxMetaInfo}{\-P\-L\-C\-\_\-\-Trx\-Meta\-Info} $>$ meta\-Info)=0}\label{classns3_1_1PLC__Phy_a46b98bd3de07f51cfa53af58fa20f1cd} \item \hypertarget{classns3_1_1PLC__Phy_ad2137025b97803e834683d9a1eed897e}{virtual void {\bfseries \-Do\-Update\-Rx\-Psd} (uint32\-\_\-t tx\-Id, \-Ptr$<$ \-Spectrum\-Value $>$ new\-Rx\-Psd)=0}\label{classns3_1_1PLC__Phy_ad2137025b97803e834683d9a1eed897e} \item \hypertarget{classns3_1_1PLC__Phy_ac539a2e014f1ed6a532ee79e7e4f1ea0}{virtual \hyperlink{classns3_1_1PLC__ChannelTransferImpl}{\-P\-L\-C\-\_\-\-Channel\-Transfer\-Impl} $\ast$ {\bfseries \-Do\-Get\-Channel\-Transfer\-Impl} (\-Ptr$<$ \hyperlink{classns3_1_1PLC__Phy}{\-P\-L\-C\-\_\-\-Phy} $>$ rx\-Phy)=0}\label{classns3_1_1PLC__Phy_ac539a2e014f1ed6a532ee79e7e4f1ea0} \end{DoxyCompactItemize} \subsection*{\-Protected \-Attributes} \begin{DoxyCompactItemize} \item \hypertarget{classns3_1_1PLC__Phy_a1bc49688d4ac54538439e1a39a595be0}{\-Ptr$<$ \hyperlink{classns3_1_1PLC__Node}{\-P\-L\-C\-\_\-\-Node} $>$ {\bfseries m\-\_\-node}}\label{classns3_1_1PLC__Phy_a1bc49688d4ac54538439e1a39a595be0} \item \hypertarget{classns3_1_1PLC__Phy_afc2005e3f6427922206d8a7255b985df}{\-P\-L\-C\-\_\-\-Phy\-Data\-Frame\-Sent\-Callback {\bfseries m\-\_\-data\-\_\-frame\-\_\-sent\-\_\-callback}}\label{classns3_1_1PLC__Phy_afc2005e3f6427922206d8a7255b985df} \item \hypertarget{classns3_1_1PLC__Phy_a3cb312c1f9c2adb0f5565a3c7fa619a3}{\-Phy\-Rx\-End\-Ok\-Callback {\bfseries m\-\_\-receive\-\_\-success\-\_\-cb}}\label{classns3_1_1PLC__Phy_a3cb312c1f9c2adb0f5565a3c7fa619a3} \item \hypertarget{classns3_1_1PLC__Phy_a199024edfc1cb1242e1b66ec56239d44}{\-Phy\-Rx\-End\-Error\-Callback {\bfseries m\-\_\-receive\-\_\-error\-\_\-cb}}\label{classns3_1_1PLC__Phy_a199024edfc1cb1242e1b66ec56239d44} \end{DoxyCompactItemize} \subsection*{\-Static \-Protected \-Attributes} \begin{DoxyCompactItemize} \item \hypertarget{classns3_1_1PLC__Phy_ac75ba543faa54de93f57144070b4e420}{static \-Time {\bfseries symbol\-\_\-duration} = \-Micro\-Seconds(2240)}\label{classns3_1_1PLC__Phy_ac75ba543faa54de93f57144070b4e420} \end{DoxyCompactItemize} \subsection{\-Detailed \-Description} \-Abstract base class for \-P\-L\-C \-P\-H\-Ys \subsection{\-Member \-Function \-Documentation} \hypertarget{classns3_1_1PLC__Phy_a2901b7bc2979a2637c665c5501ef6d4a}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Get\-Channel\-Transfer\-Impl@{\-Get\-Channel\-Transfer\-Impl}} \index{\-Get\-Channel\-Transfer\-Impl@{\-Get\-Channel\-Transfer\-Impl}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Get\-Channel\-Transfer\-Impl}]{\setlength{\rightskip}{0pt plus 5cm}{\bf \-P\-L\-C\-\_\-\-Channel\-Transfer\-Impl} $\ast$ {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Get\-Channel\-Transfer\-Impl} ( \begin{DoxyParamCaption} \item[{\-Ptr$<$ {\bf \-P\-L\-C\-\_\-\-Phy} $>$}]{rx\-Phy} \end{DoxyParamCaption} )}}\label{classns3_1_1PLC__Phy_a2901b7bc2979a2637c665c5501ef6d4a} \begin{DoxyReturn}{\-Returns} \-Channel transfer implementation to rx\-Phy \end{DoxyReturn} \hypertarget{classns3_1_1PLC__Phy_a5c9c1582a62bd748c8b09b294eb95a83}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Get\-Channel\-Transfer\-Vector@{\-Get\-Channel\-Transfer\-Vector}} \index{\-Get\-Channel\-Transfer\-Vector@{\-Get\-Channel\-Transfer\-Vector}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Get\-Channel\-Transfer\-Vector}]{\setlength{\rightskip}{0pt plus 5cm}\-Ptr$<$ {\bf \-P\-L\-C\-\_\-\-Transfer\-Base} $>$ {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Get\-Channel\-Transfer\-Vector} ( \begin{DoxyParamCaption} \item[{\-Ptr$<$ {\bf \-P\-L\-C\-\_\-\-Phy} $>$}]{rx\-Phy} \end{DoxyParamCaption} )}}\label{classns3_1_1PLC__Phy_a5c9c1582a62bd748c8b09b294eb95a83} \begin{DoxyReturn}{\-Returns} \-Channel transfer vector to rx\-Phy \end{DoxyReturn} \hypertarget{classns3_1_1PLC__Phy_ac671d3c0e8fbe3792f4ee16e7f8998a2}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Get\-Node@{\-Get\-Node}} \index{\-Get\-Node@{\-Get\-Node}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Get\-Node}]{\setlength{\rightskip}{0pt plus 5cm}\-Ptr$<${\bf \-P\-L\-C\-\_\-\-Node}$>$ {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Get\-Node} ( \begin{DoxyParamCaption} \item[{void}]{} \end{DoxyParamCaption} )\hspace{0.3cm}{\ttfamily \mbox{[}inline\mbox{]}}}}\label{classns3_1_1PLC__Phy_ac671d3c0e8fbe3792f4ee16e7f8998a2} \begin{DoxyReturn}{\-Returns} \hyperlink{classns3_1_1PLC__Node}{\-P\-L\-C\-\_\-\-Node} the \-P\-H\-Y is attached to \end{DoxyReturn} \hypertarget{classns3_1_1PLC__Phy_a407d28e0eaa83475f931038c94cd4381}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Get\-Symbol\-Duration@{\-Get\-Symbol\-Duration}} \index{\-Get\-Symbol\-Duration@{\-Get\-Symbol\-Duration}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Get\-Symbol\-Duration}]{\setlength{\rightskip}{0pt plus 5cm}\-Time {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Get\-Symbol\-Duration} ( \begin{DoxyParamCaption} \item[{void}]{} \end{DoxyParamCaption} )\hspace{0.3cm}{\ttfamily \mbox{[}static\mbox{]}}}}\label{classns3_1_1PLC__Phy_a407d28e0eaa83475f931038c94cd4381} \begin{DoxyReturn}{\-Returns} \-The global modulation symbol duration \end{DoxyReturn} \hypertarget{classns3_1_1PLC__Phy_a51e432fe0945a6b810e0f5d240b2ff55}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Notify\-Data\-Frame\-Sent@{\-Notify\-Data\-Frame\-Sent}} \index{\-Notify\-Data\-Frame\-Sent@{\-Notify\-Data\-Frame\-Sent}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Notify\-Data\-Frame\-Sent}]{\setlength{\rightskip}{0pt plus 5cm}void {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Notify\-Data\-Frame\-Sent} ( \begin{DoxyParamCaption} \item[{void}]{} \end{DoxyParamCaption} )}}\label{classns3_1_1PLC__Phy_a51e432fe0945a6b810e0f5d240b2ff55} \-Notify subclasses that data frame has been sent \hypertarget{classns3_1_1PLC__Phy_a37c13147b5d5cb71843be91c1654fc18}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Rx\-Psd\-Changed@{\-Rx\-Psd\-Changed}} \index{\-Rx\-Psd\-Changed@{\-Rx\-Psd\-Changed}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Rx\-Psd\-Changed}]{\setlength{\rightskip}{0pt plus 5cm}void {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Rx\-Psd\-Changed} ( \begin{DoxyParamCaption} \item[{uint32\-\_\-t}]{tx\-Id, } \item[{\-Ptr$<$ \-Spectrum\-Value $>$}]{new\-Rx\-Psd} \end{DoxyParamCaption} )}}\label{classns3_1_1PLC__Phy_a37c13147b5d5cb71843be91c1654fc18} \-Notify the \hyperlink{classns3_1_1PLC__Phy}{\-P\-L\-C\-\_\-\-Phy} instance that the \-Power \-Spectral \-Density of the incoming waveform transmitted by interface tx\-Id has changed to new\-Rx\-Psd \begin{DoxyParams}{\-Parameters} {\em tx\-Id} & \\ \hline {\em new\-Rx\-Psd} & \\ \hline \end{DoxyParams} \hypertarget{classns3_1_1PLC__Phy_a970811df6124983c58f6b578a986f336}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Set\-Data\-Frame\-Sent\-Callback@{\-Set\-Data\-Frame\-Sent\-Callback}} \index{\-Set\-Data\-Frame\-Sent\-Callback@{\-Set\-Data\-Frame\-Sent\-Callback}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Set\-Data\-Frame\-Sent\-Callback}]{\setlength{\rightskip}{0pt plus 5cm}void {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Set\-Data\-Frame\-Sent\-Callback} ( \begin{DoxyParamCaption} \item[{\-P\-L\-C\-\_\-\-Phy\-Data\-Frame\-Sent\-Callback}]{c} \end{DoxyParamCaption} )}}\label{classns3_1_1PLC__Phy_a970811df6124983c58f6b578a986f336} \-Callback after a successful frame transmission \begin{DoxyParams}{\-Parameters} {\em c} & \\ \hline \end{DoxyParams} \hypertarget{classns3_1_1PLC__Phy_a67ae8c7bf4a78a5788408f507b179bcc}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Set\-Receive\-Error\-Callback@{\-Set\-Receive\-Error\-Callback}} \index{\-Set\-Receive\-Error\-Callback@{\-Set\-Receive\-Error\-Callback}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Set\-Receive\-Error\-Callback}]{\setlength{\rightskip}{0pt plus 5cm}void {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Set\-Receive\-Error\-Callback} ( \begin{DoxyParamCaption} \item[{\-Phy\-Rx\-End\-Error\-Callback}]{c} \end{DoxyParamCaption} )}}\label{classns3_1_1PLC__Phy_a67ae8c7bf4a78a5788408f507b179bcc} \-Callback for a failed datagram/message reception \begin{DoxyParams}{\-Parameters} {\em c} & \\ \hline \end{DoxyParams} \hypertarget{classns3_1_1PLC__Phy_abd23f344001a334bc6b2981e1f9e096d}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Set\-Receive\-Success\-Callback@{\-Set\-Receive\-Success\-Callback}} \index{\-Set\-Receive\-Success\-Callback@{\-Set\-Receive\-Success\-Callback}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Set\-Receive\-Success\-Callback}]{\setlength{\rightskip}{0pt plus 5cm}void {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Set\-Receive\-Success\-Callback} ( \begin{DoxyParamCaption} \item[{\-Phy\-Rx\-End\-Ok\-Callback}]{c} \end{DoxyParamCaption} )}}\label{classns3_1_1PLC__Phy_abd23f344001a334bc6b2981e1f9e096d} \-Callback for a successful datagram/message reception \begin{DoxyParams}{\-Parameters} {\em c} & \\ \hline \end{DoxyParams} \hypertarget{classns3_1_1PLC__Phy_a5d5a1f64272f35b2355750e77c0d2868}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Set\-Symbol\-Duration@{\-Set\-Symbol\-Duration}} \index{\-Set\-Symbol\-Duration@{\-Set\-Symbol\-Duration}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Set\-Symbol\-Duration}]{\setlength{\rightskip}{0pt plus 5cm}void {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Set\-Symbol\-Duration} ( \begin{DoxyParamCaption} \item[{\-Time}]{t\-Symbol} \end{DoxyParamCaption} )\hspace{0.3cm}{\ttfamily \mbox{[}static\mbox{]}}}}\label{classns3_1_1PLC__Phy_a5d5a1f64272f35b2355750e77c0d2868} \-Set the global symbol duration value for all \-P\-H\-Ys. \-This method should not be called directly, but by calling \-P\-L\-C\-\_\-\-Time\-Model\-::\-Set\-Periodicity\-Model, as the simulations time resolution will be adapted to symbol granularity \begin{DoxyParams}{\-Parameters} {\em t\-Symbol} & \-Duration of a modulation symbol \\ \hline \end{DoxyParams} \hypertarget{classns3_1_1PLC__Phy_abe32cc0f1c2e7c9de36a37812423df8e}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Start\-Rx@{\-Start\-Rx}} \index{\-Start\-Rx@{\-Start\-Rx}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Start\-Rx}]{\setlength{\rightskip}{0pt plus 5cm}void {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Start\-Rx} ( \begin{DoxyParamCaption} \item[{\-Ptr$<$ const \-Packet $>$}]{p, } \item[{uint32\-\_\-t}]{tx\-Id, } \item[{\-Ptr$<$ \-Spectrum\-Value $>$ \&}]{rx\-Psd, } \item[{\-Time}]{duration, } \item[{\-Ptr$<$ const {\bf \-P\-L\-C\-\_\-\-Trx\-Meta\-Info} $>$}]{meta\-Info} \end{DoxyParamCaption} )}}\label{classns3_1_1PLC__Phy_abe32cc0f1c2e7c9de36a37812423df8e} \-Notify the \hyperlink{classns3_1_1PLC__Phy}{\-P\-L\-C\-\_\-\-Phy} instance of an incoming waveform \begin{DoxyParams}{\-Parameters} {\em p} & the \-Packet associated with the incoming waveform \\ \hline {\em rx\-Psd} & the \-Power \-Spectral \-Density of the incoming \\ \hline {\em duration} & the duration of the incoming waveform \\ \hline {\em meta\-Info} & meta information for link performance emulation \\ \hline \end{DoxyParams} \hypertarget{classns3_1_1PLC__Phy_a4087fbae09bdb778285c0e7cdc307d2e}{\index{ns3\-::\-P\-L\-C\-\_\-\-Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}!\-Start\-Tx@{\-Start\-Tx}} \index{\-Start\-Tx@{\-Start\-Tx}!ns3::PLC_Phy@{ns3\-::\-P\-L\-C\-\_\-\-Phy}} \subsubsection[{\-Start\-Tx}]{\setlength{\rightskip}{0pt plus 5cm}bool {\bf ns3\-::\-P\-L\-C\-\_\-\-Phy\-::\-Start\-Tx} ( \begin{DoxyParamCaption} \item[{\-Ptr$<$ \-Packet $>$}]{p} \end{DoxyParamCaption} )}}\label{classns3_1_1PLC__Phy_a4087fbae09bdb778285c0e7cdc307d2e} \-Start transmitting a packet \begin{DoxyParams}{\-Parameters} {\em p} & \-Packet \\ \hline {\em tx\-Psd} & \-Power \-Spectral \-Density of the waveform to be transmitted \\ \hline {\em duration} & \-Time the packet needs for transmission \\ \hline \end{DoxyParams} \begin{DoxyReturn}{\-Returns} \-True if \-P\-H\-Y started transmission \end{DoxyReturn} \-The documentation for this class was generated from the following files\-:\begin{DoxyCompactItemize} \item model/plc-\/phy.\-h\item model/plc-\/phy.\-cc\end{DoxyCompactItemize}
SabaFar/plc
doc/latex/classns3_1_1PLC__Phy.tex
TeX
gpl-3.0
16,293
namespace Shared.Network.GameServer { public class GameCharInfoPacket { public readonly string CharacterName; public GameCharInfoPacket(Packet packet) { CharacterName = packet.Reader.ReadUnicodeStatic(21); } } }
exmex/DCNC
src/Shared/Network/Packets/GameServer/Info/GameCharInfoPacket.cs
C#
gpl-3.0
279
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_29) on Sat Mar 17 18:05:25 MSK 2012 --> <TITLE> org.apache.poi.ss.formula.atp Class Hierarchy (POI API Documentation) </TITLE> <META NAME="date" CONTENT="2012-03-17"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.poi.ss.formula.atp Class Hierarchy (POI API Documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/apache/poi/ss/formula/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/poi/ss/formula/constant/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/poi/ss/formula/atp/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package org.apache.poi.ss.formula.atp </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.Object<UL> <LI TYPE="circle">org.apache.poi.ss.formula.atp.<A HREF="../../../../../../org/apache/poi/ss/formula/atp/AnalysisToolPak.html" title="class in org.apache.poi.ss.formula.atp"><B>AnalysisToolPak</B></A> (implements org.apache.poi.ss.formula.udf.<A HREF="../../../../../../org/apache/poi/ss/formula/udf/UDFFinder.html" title="interface in org.apache.poi.ss.formula.udf">UDFFinder</A>) <LI TYPE="circle">org.apache.poi.ss.formula.atp.<A HREF="../../../../../../org/apache/poi/ss/formula/atp/DateParser.html" title="class in org.apache.poi.ss.formula.atp"><B>DateParser</B></A><LI TYPE="circle">org.apache.poi.ss.formula.atp.<A HREF="../../../../../../org/apache/poi/ss/formula/atp/WorkdayCalculator.html" title="class in org.apache.poi.ss.formula.atp"><B>WorkdayCalculator</B></A></UL> </UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/apache/poi/ss/formula/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/apache/poi/ss/formula/constant/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/poi/ss/formula/atp/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2012 The Apache Software Foundation or its licensors, as applicable.</i> </BODY> </HTML>
gmchen/MosquitoSimulation
poi-3.8/docs/apidocs/org/apache/poi/ss/formula/atp/package-tree.html
HTML
gpl-3.0
7,170
#!/usr/bin/python # -*- coding: windows-1252 -*- import wxversion wxversion.select('2.8') import wx import wx.aui from id import * from model import * from graphic import * from sql import * from django import * import sqlite3 from xml.dom import minidom class MainFrame(wx.aui.AuiMDIParentFrame): def __init__(self, app, posx, posy, sizex, sizey): self.data = {} self.locale = wx.Locale() self.locale.AddCatalogLookupPathPrefix('./locale') if app.config.Read("language"): if app.config.Read("language") != 'English': idioma = app.config.Read("language") else: idioma = '' else: idioma = 'es_ES' app.config.Write("language", idioma) app.config.Flush() self.locale.AddCatalog(idioma) for key, value in language.iteritems(): if value == idioma: self.data["idioma"] = key self.translation = wx.GetTranslation self.app = app #--Iniciar el padre con las posiciones y titulo del Frame--# wx.aui.AuiMDIParentFrame.__init__(self, None, -1, self.translation(archivo[TITULO]), pos = (posx, posy), size = (sizex, sizey)) #--Imbuir el logo del CUC en la caja de control de la ventana--# ico = wx.Icon('images/mini_logo_cuc_trans.ico', wx.BITMAP_TYPE_ICO) self.SetIcon(ico) #--Inicializamos la libreria OGL de wxPython--# ogl.OGLInitialize() #--MENU--# #Menu de Archivo self.menuFile = wx.Menu() self.menuFile.Append(ID_CREAR_MODELO, self.translation(archivo[ID_CREAR_MODELO]), self.translation(archivoHelp[ID_CREAR_MODELO])) self.menuFile.Append(ID_ABRIR_MODELO, self.translation(archivo[ID_ABRIR_MODELO]), self.translation(archivoHelp[ID_ABRIR_MODELO])) self.menuFile.AppendSeparator() self.menuFile.Append(ID_GUARDAR_MODELO, self.translation(archivo[ID_GUARDAR_MODELO]), self.translation(archivoHelp[ID_GUARDAR_MODELO])) self.menuFile.Enable(ID_GUARDAR_MODELO, False) self.menuFile.Append(ID_GUARDAR_COMO_MODELO, self.translation(archivo[ID_GUARDAR_COMO_MODELO]), self.translation(archivoHelp[ID_GUARDAR_COMO_MODELO])) self.menuFile.Enable(ID_GUARDAR_COMO_MODELO, False) self.menuFile.Append(ID_EXPORTAR_MODELO, self.translation(archivo[ID_EXPORTAR_MODELO]), self.translation(archivoHelp[ID_EXPORTAR_MODELO])) self.menuFile.Enable(ID_EXPORTAR_MODELO, False) self.menuFile.AppendSeparator() self.menuFile.Append(ID_CERRAR_APLICACION, self.translation(archivo[ID_CERRAR_APLICACION]), self.translation(archivoHelp[ID_CERRAR_APLICACION])) #Menu Ver self.menuVer = wx.Menu() self.refrescar = self.menuVer.Append(ID_MENU_VER_REFRESCAR, self.translation(archivo[ID_MENU_VER_REFRESCAR]), self.translation(archivoHelp[ID_MENU_VER_REFRESCAR])) wx.EVT_MENU(self, ID_MENU_VER_REFRESCAR, self.Actualizar) self.menuVer.AppendSeparator() self.menuVerStandard = self.menuVer.Append(ID_MENU_VER_STANDARD, self.translation(archivo[ID_MENU_VER_STANDARD]), self.translation(archivoHelp[ID_MENU_VER_STANDARD]), kind=wx.ITEM_CHECK) self.menuVerIdef1x = self.menuVer.Append(ID_MENU_VER_IDF1X, self.translation(archivo[ID_MENU_VER_IDF1X]), self.translation(archivoHelp[ID_MENU_VER_IDF1X]), kind=wx.ITEM_CHECK) self.menuVer.AppendSeparator() self.menuVerNav = self.menuVer.Append(ID_MENU_VER_NAV, self.translation(archivo[ID_MENU_VER_NAV]), self.translation(archivoHelp[ID_MENU_VER_NAV]), kind=wx.ITEM_CHECK) self.menuVerCard = self.menuVer.Append(ID_MENU_VER_CARD, self.translation(archivo[ID_MENU_VER_CARD]), self.translation(archivoHelp[ID_MENU_VER_CARD]), kind=wx.ITEM_CHECK) self.menuVer.AppendSeparator() self.barraStatus = self.menuVer.Append(ID_MENU_VER_BARRA_ESTADO, self.translation(archivo[ID_MENU_VER_BARRA_ESTADO]), self.translation(archivoHelp[ID_MENU_VER_BARRA_ESTADO]), kind=wx.ITEM_CHECK) if app.tool: idf1x, standard, navegador = eval(app.tool) else: idf1x, standard, navegador = (True, True, True) app.config.Write("tool", str( (True, True, True) )) app.config.Flush() self.menuVer.Check(ID_MENU_VER_STANDARD, standard) self.menuVer.Check(ID_MENU_VER_IDF1X, idf1x) self.menuVer.Check(ID_MENU_VER_BARRA_ESTADO, True) self.menuVer.Enable(ID_MENU_VER_REFRESCAR, False) self.menuVer.Enable(ID_MENU_VER_NAV, False) self.menuVer.Enable(ID_MENU_VER_CARD, False) #Menu Herramientas self.menuTool = wx.Menu() self.menuTool.Append(ID_CREAR_ENTIDAD, self.translation(archivo[ID_CREAR_ENTIDAD]), self.translation(archivoHelp[ID_CREAR_ENTIDAD])) self.menuTool.Enable(ID_CREAR_ENTIDAD, False) self.menuTool.AppendSeparator() self.menuTool.Append(ID_RELACION_IDENTIF, self.translation(archivo[ID_RELACION_IDENTIF]), self.translation(archivoHelp[ID_RELACION_IDENTIF])) self.menuTool.Enable(ID_RELACION_IDENTIF, False) self.menuTool.Append(ID_RELACION_NO_IDENTIF, self.translation(archivo[ID_RELACION_NO_IDENTIF]), self.translation(archivoHelp[ID_RELACION_IDENTIF])) self.menuTool.Enable(ID_RELACION_NO_IDENTIF, False) self.menuTool.AppendSeparator() self.menuTool.Append(ID_GENERAR_SCRIPT, self.translation(archivo[ID_GENERAR_SCRIPT]), self.translation(archivoHelp[ID_GENERAR_SCRIPT])) self.menuTool.Enable(ID_GENERAR_SCRIPT, False) self.menuTool.Append(ID_GENERAR_SCRIPT_DJANGO, archivo[ID_GENERAR_SCRIPT_DJANGO], archivoHelp[ID_GENERAR_SCRIPT_DJANGO]) self.menuTool.Enable(ID_GENERAR_SCRIPT_DJANGO, False) #self.menuTool.Append(ID_GUARDAR_SCRIPT, "Guardar Script SQL", "Guarda el Script SQL del modelo para PostgreSQL") #Menu de Ayuda self.menuHelp = wx.Menu() #self.menuLanguage = wx.Menu() #self.menuLanguage.Append(ID_MENU_HELP_us_US, self.translation(archivo[ID_MENU_HELP_us_US]), self.translation(archivoHelp[ID_MENU_HELP_us_US]), kind=wx.ITEM_RADIO) #self.menuLanguage.Append(ID_MENU_HELP_es_ES, self.translation(archivo[ID_MENU_HELP_es_ES]), self.translation(archivoHelp[ID_MENU_HELP_es_ES]), kind=wx.ITEM_RADIO).Check(True) #self.menuLanguage.Append(ID_MENU_HELP_fr_FR, self.translation("frances"), kind=wx.ITEM_RADIO) #self.menuHelp.AppendMenu(ID_MENU_HELP_LANGUAGE, self.translation(archivo[ID_MENU_HELP_LANGUAGE]), self.menuLanguage) self.menuHelp.Append(ID_MENU_HELP_LANGUAGE, self.translation(archivo[ID_MENU_HELP_LANGUAGE]), self.translation(archivoHelp[ID_MENU_HELP_LANGUAGE])) self.menuHelp.Append(ID_MENU_HELP_AYUDA, self.translation(archivo[ID_MENU_HELP_AYUDA]), self.translation(archivoHelp[ID_MENU_HELP_AYUDA])) self.menuHelp.AppendSeparator() self.menuHelp.Append(ID_MENU_HELP_LOG, self.translation(archivo[ID_MENU_HELP_LOG]), self.translation(archivoHelp[ID_MENU_HELP_LOG])) self.menuHelp.Enable(ID_MENU_HELP_LOG, False) self.menuHelp.AppendSeparator() self.menuHelp.Append(ID_MENU_HELP_ACERCA_DE, self.translation(archivo[ID_MENU_HELP_ACERCA_DE]), self.translation(archivoHelp[ID_MENU_HELP_ACERCA_DE])) #--Se adicionan los menues a la barra de menu--# self.menuBar = wx.MenuBar() self.menuBar.Append(self.menuFile, self.translation(menuBar[0])) self.menuBar.Append(self.menuVer, self.translation(menuBar[1])) self.menuBar.Append(self.menuTool, self.translation(menuBar[2])) self.menuBar.Append(self.menuHelp, self.translation(menuBar[3])) #--Se adiciona la barra de menu al frame--# self.SetMenuBar(self.menuBar) if not posx: self.Centre() #--MENU ToolBar--# self._mgr = wx.aui.AuiManager() self._mgr.SetManagedWindow(self) #self.translationperspectives = [] self.n = 0 self.x = 0 self.toolBarIdef1x = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER) self.toolBarIdef1x.SetToolBitmapSize((8, 8)) self.toolBarIdef1x.AddLabelTool(ID_PUNTERO_MOUSE, self.translation(archivo[ID_PUNTERO_MOUSE]), wx.Bitmap('images/Puntero.png')) self.toolBarIdef1x.AddLabelTool(ID_CREAR_ENTIDAD, self.translation(archivo[ID_CREAR_ENTIDAD]), wx.Bitmap('images/Entidad.png')) self.toolBarIdef1x.EnableTool(ID_CREAR_ENTIDAD, False) self.toolBarIdef1x.AddLabelTool(ID_RELACION_IDENTIF, self.translation(archivo[ID_RELACION_IDENTIF]), wx.Bitmap('images/R-identificadora.png')) self.toolBarIdef1x.EnableTool(ID_RELACION_IDENTIF, False) self.toolBarIdef1x.AddLabelTool(ID_RELACION_NO_IDENTIF, self.translation(archivo[ID_RELACION_NO_IDENTIF]), wx.Bitmap('images/R-No-identificadora.png')) self.toolBarIdef1x.EnableTool(ID_RELACION_NO_IDENTIF, False) self.toolBarIdef1x.Realize() self._mgr.AddPane(self.toolBarIdef1x, wx.aui.AuiPaneInfo(). Name("toolBarIdef1x").Caption("IDEF1X-Kit"). ToolbarPane().Top().Row(1). LeftDockable(True).RightDockable(True).CloseButton(False)) if not idf1x: panelIdef1x = self._mgr.GetPane("toolBarIdef1x"); panelIdef1x.Hide() self.toolBarStandard = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER) self.toolBarStandard.SetToolBitmapSize(wx.Size(32, 32)) self.toolBarStandard.AddLabelTool(ID_CREAR_MODELO, self.translation(archivo[ID_CREAR_MODELO]), wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_TOOLBAR)) self.toolBarStandard.AddLabelTool(ID_ABRIR_MODELO, self.translation(archivo[ID_ABRIR_MODELO]), wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR)) self.toolBarStandard.AddSeparator() self.toolBarStandard.AddLabelTool(ID_GUARDAR_MODELO, self.translation(archivo[ID_GUARDAR_MODELO]), wx.ArtProvider.GetBitmap(wx.ART_FLOPPY, wx.ART_TOOLBAR)) self.toolBarStandard.EnableTool(ID_GUARDAR_MODELO, False) self.toolBarStandard.AddSeparator() self.toolBarStandard.AddLabelTool(ID_GENERAR_SCRIPT, self.translation(archivo[ID_GENERAR_SCRIPT]), wx.Bitmap('images/2_sqlLogo.png') ) self.toolBarStandard.EnableTool(ID_GENERAR_SCRIPT, False) self.toolBarStandard.AddLabelTool(ID_GENERAR_SCRIPT_DJANGO, archivo[ID_GENERAR_SCRIPT_DJANGO], wx.Bitmap('images/django.png') ) self.toolBarStandard.EnableTool(ID_GENERAR_SCRIPT_DJANGO, False) self.toolBarStandard.Realize() self._mgr.AddPane(self.toolBarStandard, wx.aui.AuiPaneInfo(). Name("toolBarStandard").Caption("Estandar"). ToolbarPane().Top().Row(1). LeftDockable(True).RightDockable(True).CloseButton(False)) if not standard: panelStandard = self._mgr.GetPane("toolBarStandard"); panelStandard.Hide() self._mgr.Update() #--Barra de Estado--# self.statusBar = self.CreateStatusBar() self.SetStatusText("Listo!") #--MENU click derecho en el Tree --# self.menu_tree_entidad = wx.Menu() self.menu_tree_entidad.Append(ID_CREAR_ENTIDAD, self.translation(archivo[ID_CREAR_ENTIDAD])) self.menu_tree_atributo = wx.Menu() self.menu_tree_atributo.Append(ID_TREE_MODIFICAR_ATRIBUTO, self.translation(archivo[ID_TREE_MODIFICAR_ATRIBUTO])) self.menu_tree_atributo.Append(ID_TREE_ELIMINAR_ATRIBUTO, self.translation(archivo[ID_TREE_ELIMINAR_ATRIBUTO])) self.menu_tree_relacion = wx.Menu() self.menu_tree_relacion.Append(ID_CREAR_RELACION, self.translation(archivo[ID_CREAR_RELACION])) #--MENU click derecho en las formas--# self.menu_entidad = wx.Menu() self.menu_entidad.Append(ID_MODIFICAR_ENTIDAD, self.translation(archivo[ID_MODIFICAR_ENTIDAD])) self.menu_entidad.Append(ID_ELIMINAR_ENTIDAD, self.translation(archivo[ID_ELIMINAR_ENTIDAD])) self.menu_atributo = wx.Menu() self.menu_atributo.Append(ID_CREAR_ATRIBUTO, self.translation(archivo[ID_CREAR_ATRIBUTO])) self.menu_atributo.Append(ID_MODIFICAR_ATRIBUTO, self.translation(archivo[ID_MODIFICAR_ATRIBUTO])) self.menu_atributo.Append(ID_ELIMINAR_ATRIBUTO, self.translation(archivo[ID_ELIMINAR_ATRIBUTO])) self.menu_relacion = wx.Menu() self.menu_relacion.Append(ID_MODIFICAR_RELACION, self.translation(archivo[ID_MODIFICAR_RELACION])) self.menu_relacion.Append(ID_ELIMINAR_RELACION, self.translation(archivo[ID_ELIMINAR_RELACION])) self.menu_relacionIdentificadora = wx.Menu() self.menu_relacionIdentificadora.Append(ID_MODIFICAR_RELACION, self.translation(archivo[ID_MODIFICAR_RELACION])) self.menu_relacionIdentificadora.Append(ID_ELIMINAR_RELACION, self.translation(archivo[ID_ELIMINAR_RELACION])) self.menu_relacionNoIdentificadora = wx.Menu() self.menu_relacionNoIdentificadora.Append(ID_MODIFICAR_RELACION, self.translation(archivo[ID_MODIFICAR_RELACION])) self.menu_relacionNoIdentificadora.Append(ID_ELIMINAR_RELACION, self.translation(archivo[ID_ELIMINAR_RELACION])) #--Eventos para todos los botones segun su ID--# self.Bind(wx.EVT_MENU, self.CrearModelo, id=ID_CREAR_MODELO) self.Bind(wx.EVT_MENU, self.GuardarModelo, id=ID_GUARDAR_MODELO) self.Bind(wx.EVT_MENU, self.GuardarModeloComo, id=ID_GUARDAR_COMO_MODELO) self.Bind(wx.EVT_MENU, self.AbrirModelo, id=ID_ABRIR_MODELO) self.Bind(wx.EVT_MENU, self.ExportarModelo, id=ID_EXPORTAR_MODELO) self.Bind(wx.EVT_MENU, self.OnExit, id=ID_CERRAR_APLICACION ) self.Bind(wx.EVT_MENU, self.ToolBarIdef1xVer, id=ID_MENU_VER_IDF1X) self.Bind(wx.EVT_MENU, self.NavVer, id=ID_MENU_VER_NAV) self.Bind(wx.EVT_MENU, self.NavCard, id=ID_MENU_VER_CARD) self.Bind(wx.EVT_MENU, self.ToolBarStandardVer, id=ID_MENU_VER_STANDARD) self.Bind(wx.EVT_MENU, self.ToggleStatusBar, id=ID_MENU_VER_BARRA_ESTADO) self.Bind(wx.EVT_MENU, self.Puntero, id = ID_PUNTERO_MOUSE) self.Bind(wx.EVT_MENU, self.CrearEntidad, id = ID_CREAR_ENTIDAD) self.Bind(wx.EVT_MENU, self.ModificarEntidad, id= ID_MODIFICAR_ENTIDAD) self.Bind(wx.EVT_MENU, self.EliminarEntidad, id= ID_ELIMINAR_ENTIDAD) self.Bind(wx.EVT_MENU, self.CrearAtributo, id = ID_CREAR_ATRIBUTO) self.Bind(wx.EVT_MENU, self.ModificarAtributo, id = ID_MODIFICAR_ATRIBUTO) self.Bind(wx.EVT_MENU, self.EliminarAtributo, id = ID_ELIMINAR_ATRIBUTO) self.Bind(wx.EVT_MENU, self.TreeModificarAtributo, id = ID_TREE_MODIFICAR_ATRIBUTO) self.Bind(wx.EVT_MENU, self.TreeEliminarAtributo, id = ID_TREE_ELIMINAR_ATRIBUTO) self.Bind(wx.EVT_MENU, self.CrearRelacion, id = ID_CREAR_RELACION) self.Bind(wx.EVT_MENU, self.RelacionIdentificadora, id = ID_RELACION_IDENTIF) self.Bind(wx.EVT_MENU, self.RelacionNoIdentificadora, id = ID_RELACION_NO_IDENTIF) self.Bind(wx.EVT_MENU, self.ModificarRelacion, id = ID_MODIFICAR_RELACION) self.Bind(wx.EVT_MENU, self.EliminarRelacion, id = ID_ELIMINAR_RELACION) self.Bind(wx.EVT_MENU, self.GenerarScriptSql, id = ID_GENERAR_SCRIPT) self.Bind(wx.EVT_MENU, self.GenerarScriptDjango, id = ID_GENERAR_SCRIPT_DJANGO) #self.Bind(wx.EVT_MENU, self.GuardarScriptSql, id = ID_GUARDAR_SCRIPT) #self.Bind(wx.EVT_MENU, self.ActualizarIdioma, id=ID_MENU_HELP_us_US ) #self.Bind(wx.EVT_MENU, self.ActualizarIdioma, id=ID_MENU_HELP_es_ES ) #self.Bind(wx.EVT_MENU, self.ActualizarIdioma, id=ID_MENU_HELP_fr_FR ) self.Bind(wx.EVT_MENU, self.ActualizarIdioma, id=ID_MENU_HELP_LANGUAGE ) self.Bind(wx.EVT_MENU, self.VerLog, id=ID_MENU_HELP_LOG ) self.Bind(wx.EVT_MENU, self.OnAboutBox, id=ID_MENU_HELP_ACERCA_DE ) #--Hilo para verificar y guardar la posicion del Frame--# self.time = wx.Timer(self) self.Bind(wx.EVT_TIMER, app.SaveConfig, self.time) self.time.Start(5000) self.GetMenuBar().Remove(self.GetMenuBar().FindMenu('&Window')) def CrearModelo(self, evt): ejecute = Modelo(self) ejecute.CrearModelo(self) if ejecute.num == 1: ejecute.Close(True) self.GetMenuBar().Remove(self.GetMenuBar().FindMenu('&Window')) def GuardarModelo(self, evt): self.GetActiveChild().GuardarModelo() def GuardarModeloComo(self, evt): self.GetActiveChild().GuardarModelo(1) def AbrirModelo(self, evt): file = wx.FileDialog(self, message=self.Idioma(archivo[ID_MODELO_ABRIR_TITULO]), defaultDir=os.path.expanduser("~"), wildcard=self.Idioma(archivo[ID_MODELO_ABRIR_ARCHIVO]), style=0) if file.ShowModal() == wx.ID_OK: ejecute = Modelo(self) ejecute.AbrirModelo(self, file.GetPath(), file.GetFilename()) if ejecute.num == 1: dial = wx.MessageDialog(self, self.Idioma(archivo[ID_MODELO_ABRIR_ERROR]), self.Idioma(archivo[ID_MODELO_ABRIR_ERROR_TITULO]), wx.OK | wx.ICON_ERROR) dial.ShowModal() ejecute.Close(True) self.GetMenuBar().Remove(self.GetMenuBar().FindMenu('&Window')) def AbrirModeloDirecto(self, file): ejecute = Modelo(self) ejecute.AbrirModelo(self, file.strip(), "") if ejecute.num == 1: dial = wx.MessageDialog(self, self.Idioma(archivo[ID_MODELO_ABRIR_ERROR]), self.Idioma(archivo[ID_MODELO_ABRIR_ERROR_TITULO]), wx.OK | wx.ICON_ERROR) dial.ShowModal() ejecute.Close(True) self.GetMenuBar().Remove(self.GetMenuBar().FindMenu('&Window')) def ExportarModelo(self, evt): self.GetActiveChild().ExportarModelo() #--Permite salir de la aplicacion--# def OnExit(self, evt): self.Close(True) def Actualizar(self, evt): dc = wx.ClientDC(self.GetActiveChild().canvas) self.GetActiveChild().canvas.PrepareDC(dc) self.GetActiveChild().canvas.Redraw(dc) self.GetActiveChild().canvas.Refresh() self.Refresh() def ToolBarIdef1xVer(self, event): panelIdef1x = self._mgr.GetPane("toolBarIdef1x"); if self.menuVerIdef1x.IsChecked(): panelIdef1x.Show() mos = True else: panelIdef1x.Hide() mos = False self.app.config.Write("tool", str((mos, self.menuVerStandard.IsChecked(), self.menuVerNav.IsChecked()))) self.app.config.Flush() self._mgr.Update() def NavVer(self, event): panelNav = self.GetActiveChild().nav; if self.menuVerNav.IsChecked() and not panelNav.IsShown(): panelNav.Show() mos = True else: panelNav.Hide() mos = False self.menuVer.Check(ID_MENU_VER_NAV, mos) self.app.config.Write("tool", str((self.menuVerIdef1x.IsChecked(), self.menuVerStandard.IsChecked() , mos))) self.app.config.Flush() self.GetActiveChild()._mgr.Update() def NavCard(self, event): if self.menuVerCard.IsChecked(): mos = True else: mos = False self.menuVer.Check(ID_MENU_VER_CARD, mos) for relacion in self.GetActiveChild().relaciones: relacion.OnCardinalidad() self.GetActiveChild().canvas.Refresh() def ToolBarStandardVer(self, event): panelStandard = self._mgr.GetPane("toolBarStandard"); if self.menuVerStandard.IsChecked(): panelStandard.Show() mos = True else: panelStandard.Hide() mos = False self.app.config.Write("tool", str((self.menuVerIdef1x.IsChecked(), mos, self.menuVerNav.IsChecked()))) self.app.config.Flush() self._mgr.Update() def ToggleStatusBar(self, event): if self.barraStatus.IsChecked(): self.statusBar.Show() else: self.statusBar.Hide() def CrearEntidad(self, evt): ejecute = Entidad() #validar = ejecute.CrearEntidad(self, self.GetActiveChild().canvas, self.GetActiveChild().contadorEntidad) dlg = Dialogos(self, self.Idioma(archivo[ENTIDAD_TITULO])) dlg.Entidad(ejecute.data) if dlg.ShowModal() == wx.ID_OK: for elemento in self.GetActiveChild().entidades: if elemento.nombre == ejecute.data.get("nombre"): validar = ejecute.ValidarNombreEntidad(self.GetActiveChild().entidades) if validar == False: return 0 else: return 0 ejecute.CrearEntidad(self, self.GetActiveChild().canvas, self.GetActiveChild().contadorEntidad) self.GetActiveChild().contadorEntidad += 1 self.GetActiveChild().entidades.append(ejecute) self.GetActiveChild().canvas.Refresh() def ModificarEntidad(self, evt): ejecute = Entidad() for elemento in self.GetActiveChild().entidades: if elemento.nombreForma.Selected(): ejecute.editar = 1 ejecute.elemento = elemento if ejecute.editar == 1: ejecute.ModificarEntidad(self.GetActiveChild().canvas, ejecute.elemento, self.GetActiveChild().entidades) """else: dlg = wx.TextEntryDialog(None, "cual entidad quiere modificar?", 'Modificar Entidad', '') if dlg.ShowModal() == wx.ID_OK: response = dlg.GetValue() for elemento in self.GetActiveChild().entidades: if elemento.nombre == response: ejecute.ModificarEntidad(self.GetActiveChild().canvas, elemento, self.GetActiveChild().entidades)""" self.GetActiveChild().canvas.Refresh() def EliminarEntidad(self, evt): ejecute = Entidad() for elemento in self.GetActiveChild().entidades: if elemento.nombreForma.Selected(): ejecute.editar = 1 ejecute.elemento = elemento if ejecute.editar == 1: respuesta = ejecute.EliminarEntidad(self.GetActiveChild().canvas, ejecute.elemento, self.GetActiveChild().entidades, self.GetActiveChild()) if respuesta == 1: self.GetActiveChild().entidades.remove(ejecute.elemento) """else: dlg = wx.TextEntryDialog(None, "cual entidad quiere eliminar?", 'Eliminar Entidad', '') dlg.SetIcon=(icon) if dlg.ShowModal() == wx.ID_OK: response = dlg.GetValue() for elemento in self.GetActiveChild().entidades: if elemento.nombre == response: respuesta = ejecute.EliminarEntidad(self.GetActiveChild().canvas, elemento, self.GetActiveChild().entidades, self.GetActiveChild()) if respuesta == 1: self.GetActiveChild().entidades.remove(elemento)""" self.GetActiveChild().canvas.Refresh() def CrearAtributo(self, evt): ejecute = Atributo() for elemento in self.GetActiveChild().entidades: if elemento.atributosForma.Selected(): ejecute.editar = 1 ejecute.elemento = elemento if ejecute.editar == 1: dlg = Dialogos(self.GetActiveChild().canvas.frame, self.Idioma(archivo[ATRIBUTO_TITULO])) dlg.Atributo(ejecute.data) if dlg.ShowModal() == wx.ID_OK: for elemento in ejecute.elemento.atributos: if elemento.nombre == ejecute.data.get("nombreAtributo"): validar = ejecute.ValidarNombreAtributo(self.GetActiveChild().canvas.frame, ejecute.elemento.atributos) if validar == False: return 0 else: return 0 ejecute.CrearAtributo(self.GetActiveChild().canvas, ejecute.elemento, self.GetActiveChild().contadorAtributo) self.GetActiveChild().contadorAtributo += 1 for entidadHija in ejecute.elemento.entidadesHijas: entidadHija.HeredarAtributos(ejecute.elemento, 1) """else: dlg = wx.TextEntryDialog(None, "cual entidad agregar un atributo?", 'Agregar Atributo', '') if dlg.ShowModal() == wx.ID_OK: response = dlg.GetValue() for elemento in self.GetActiveChild().entidades: if elemento.nombre == response: ejecute.CrearAtributo(self.GetActiveChild().canvas, elemento, self.GetActiveChild().contadorAtributo)""" self.GetActiveChild().canvas.Refresh() def ModificarAtributo(self, evt): ejecute = Atributo() for elemento in self.GetActiveChild().entidades: if elemento.atributosForma.Selected(): ejecute.editar = 1 ejecute.elemento = elemento if ejecute.editar == 1: ejecute.DlgModificarAtributo(self.GetActiveChild().canvas, ejecute.elemento) """else: dlg = wx.TextEntryDialog(None, "cuall entidad agregar un atributo?", 'Agregar Atributo', '') if dlg.ShowModal() == wx.ID_OK: response = dlg.GetValue() for elemento in self.GetActiveChild().entidades: if elemento.nombre == response: ejecute.ModificarAtributo(self.GetActiveChild().canvas, elemento)""" dc = wx.ClientDC(self.GetActiveChild().canvas) for elemento in self.GetActiveChild().entidades: ejecute.ModificarAtributosForma(dc, elemento) self.GetActiveChild().canvas.Refresh() def EliminarAtributo(self, evt): ejecute = Atributo() for elemento in self.GetActiveChild().entidades: if elemento.atributosForma.Selected(): ejecute.editar = 1 ejecute.elemento = elemento if ejecute.editar == 1: ejecute.DlgEliminarAtributo(self.GetActiveChild().canvas, ejecute.elemento) """else: dlg = wx.TextEntryDialog(None, "cual entidad remover un atributo?", 'Eliminar Atributo', '') if dlg.ShowModal() == wx.ID_OK: response = dlg.GetValue() for elemento in self.GetActiveChild().entidades: if elemento.nombre == response: ejecute.DlgEliminarAtributo(self.GetActiveChild().canvas, elemento)""" self.GetActiveChild().canvas.Refresh() def CrearRelacion(self, evt): ejecute = Relacion() ejecute.DlgCrearRelacion(self, self.GetActiveChild().canvas, self.GetActiveChild().entidades) self.GetActiveChild().contadorRelacion += 1 self.GetActiveChild().canvas.Refresh() def TreeModificarAtributo(self, evt): ejecute = Atributo() ejecute.ModificarAtributo(self.GetActiveChild().canvas, self.atributoAcc.entidad, self.atributoAcc) self.GetActiveChild().canvas.Refresh() def TreeEliminarAtributo(self, evt): if self.atributoAcc.claveForanea == True: dial = wx.MessageDialog(self, self.Idioma(archivo[ATRIBUTO_ELIMINAR_ERROR]) % self.atributoAcc.nombre, 'Error', wx.OK | wx.ICON_ERROR) dial.ShowModal() return dlg = wx.MessageDialog(self.GetActiveChild().canvas, self.Idioma('Want to remove the attribute %s') % self.atributoAcc.nombre, self.Idioma('Delete Attribute %s') % self.atributoAcc.nombre, wx.YES_NO | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: ejecute = Atributo() ejecute.EliminarAtributo(self.GetActiveChild().canvas, self.atributoAcc.entidad, self.atributoAcc) self.GetActiveChild().canvas.Refresh() def RelacionIdentificadora(self, evt): self.GetActiveChild().canvas.SetCursor(wx.CROSS_CURSOR) self.GetActiveChild().relacion = 1 def RelacionNoIdentificadora(self, evt): self.GetActiveChild().canvas.SetCursor(wx.CROSS_CURSOR) self.GetActiveChild().relacion = 2 def ModificarRelacion(self, evt): ejecute = Relacion() for elemento in self.GetActiveChild().relaciones: if elemento.Selected(): ejecute.DlgModificarRelacion(elemento, self, self.GetActiveChild().canvas, self.GetActiveChild().entidades) def EliminarRelacion(self, evt): ejecute = Relacion() for elemento in self.GetActiveChild().relaciones: if elemento.Selected(): ejecute.EliminarRelacion(elemento, self.GetActiveChild().canvas, self.GetActiveChild(), self.GetActiveChild().entidades) def GenerarScriptSql(self, evt): script = SQL().ScriptPostgreSQL(self.GetActiveChild()) dlg = Dialogos(self, "Script SQL") dlg.ScriptSql(script) dlg.ShowModal() def GenerarScriptDjango(self, evt): script = Django().ScriptDjango(self.GetActiveChild()) dlg = Dialogos(self, "Script Django") dlg.ScriptSql(script) dlg.ShowModal() def GuardarScriptSql(self, evt): script = SQL().ScriptPostgreSQL(self.GetActiveChild()) tempFile = wx.FileDialog(self, message="Guardar SQL", defaultDir=os.path.expanduser("~"), defaultFile="sofiaSQL", wildcard="Archivos SQL (*.sql)|*.sql", style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) if tempFile.ShowModal() == wx.ID_OK: fileSQL = "%s.sql" % tempFile.GetPath() #nombreArchivoTemporal = tempFile.GetFilename() file = codecs.open(fileSQL, encoding='UTF-8', mode = 'w+') file.write(script) file.close() def Idioma(self, texto): if language[self.data["idioma"]] != '': return self.translation(texto) else: return texto def ActualizarIdioma(self, evt): dlg = Dialogos(self, self.Idioma("Configuration")) dlg.Configuracion(self.data) if dlg.ShowModal() == wx.ID_OK: countMenuBar = 0 if language[self.data["idioma"]] != '': self.locale.AddCatalog(language[self.data["idioma"]]) idioma = language[self.data["idioma"]] for menu in self.menuFile.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menuVer.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menuTool.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menuHelp.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menuBar.GetMenus(): try: menu[0].SetTitle(self.translation(menuBar[countMenuBar])) self.menuBar.Replace(countMenuBar, menu[0], self.translation(menuBar[countMenuBar])) countMenuBar = countMenuBar + 1 except: countMenuBar = countMenuBar + 1 for menu in self.menu_tree_entidad.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menu_tree_atributo.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menu_tree_relacion.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menu_entidad.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menu_atributo.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menu_relacion.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menu_relacionIdentificadora.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) for menu in self.menu_relacionNoIdentificadora.GetMenuItems(): if menu.GetId() != -2: menu.SetText(self.translation(archivo[menu.GetId()])) menu.SetHelp(self.translation(archivoHelp[menu.GetId()])) try: self.SetTitle(self.translation(archivo[TITULO])) self.GetActiveChild().lienzo.Caption(self.translation("Canvas")) self.GetActiveChild().nav.Caption(self.translation("Object Browser")) except: pass else: idioma = 'English' for menu in self.menuFile.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menuVer.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menuTool.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menuHelp.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menuBar.GetMenus(): try: menu[0].SetTitle(menuBar[countMenuBar]) self.menuBar.Replace(countMenuBar, menu[0], menuBar[countMenuBar]) countMenuBar = countMenuBar + 1 except: countMenuBar = countMenuBar + 1 for menu in self.menu_tree_entidad.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menu_tree_atributo.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menu_tree_relacion.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menu_entidad.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menu_atributo.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menu_relacion.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menu_relacionIdentificadora.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) for menu in self.menu_relacionNoIdentificadora.GetMenuItems(): if menu.GetId() != -2: menu.SetText(archivo[menu.GetId()]) menu.SetHelp(archivoHelp[menu.GetId()]) self.SetTitle(archivo[TITULO]) try: self.GetActiveChild().lienzo.Caption("Canvas") self.GetActiveChild().nav.Caption("Object Browser") except: pass self.app.config.Write("language", idioma) self.app.config.Flush() self.Refresh() def VerLog(self, event): dlg = Dialogos(self, "Eventos") dlg.VerLog(self.GetActiveChild().log.VerEventos()) dlg.ShowModal() #--Permite desplegar el cuadro de About--# def OnAboutBox(self, event): description = """Sofia es una herramienta desarrollada con el lenguaje de programación Python para la modelación de datos, genera el Script SQL para PostgreSQL en esta versión. Es un proyecto de Investigación y Desarrollo del Centro de Investigación en Informatica Aplicada (CENIIA) del Colegio Universitario de Caracas. Creado y dirigido por el Prof. Alejandro Amaro con la colaboración de los estudiantes.""" licence = """Aplicacion liberada bajo la licencia GPLv3, para el uso.""" info = wx.AboutDialogInfo() info.SetIcon(wx.Icon("images/sofia.png", wx.BITMAP_TYPE_PNG)) info.SetName('Sofia') info.SetVersion('0.072') info.SetDescription(description) info.SetCopyright('(C) 2011 Colegio Universitario de Caracas') info.SetWebSite('http://www.cuc.edu.ve') info.SetLicence(licence) info.AddDeveloper('Prof. Alejandro Amaro - Autor - Tutor') info.AddDeveloper("Estudiantes de Proyecto Socio-Tecnológico:") info.AddDeveloper(' Junio 2011 Mayo 2012 - Versión 0.0.7') info.AddDeveloper(' T.S.U. Arturo Delgado ') info.AddDeveloper(' T.S.U. Maximo Gonzales ') info.AddDeveloper(' T.S.U. Alexis Canchica ') info.AddDeveloper(' Mayo 2010 Mayo 2011 - Versión 0.0.4') info.AddDeveloper(' Br. Arturo Delgado ') info.AddDeveloper(' Br. Ruben Rosas ') info.AddDeveloper(' Br. Carolina Machado') info.AddDeveloper(' Br. Erik Mejias ') info.AddDeveloper('Estudiantes Tesistas:') info.AddDeveloper(' Abril 2009 Junio 2009 - Versión 0.0.1') info.AddDeveloper(' Br. Dorian Machado ') info.AddDeveloper(' Br. Daglis Campos ') info.AddDeveloper(' Br. Felix Rodriguez ') info.AddDocWriter('Estudiantes de Proyecto Socio-Tecnológico:') info.AddDocWriter(' Junio 2011 Mayo 2012 - Versión 0.0.7') info.AddDocWriter(' T.S.U. Arturo Delgado ') info.AddDocWriter(' T.S.U. Maximo Gonzales ') info.AddDocWriter(' T.S.U. Alexis Canchica ') info.AddDocWriter(' Mayo 2010 Mayo 2011 - Versión 0.0.4') info.AddDocWriter(' Br. Arturo Delgado ') info.AddDocWriter(' Br. Ruben Rosas ') info.AddDocWriter(' Br. Carolina Machado') info.AddDocWriter(' Br. Erik Mejias ') info.AddArtist('Alumnos del Colegio Universitario de Caracas') info.AddTranslator('Anonimo') wx.AboutBox(info) #dlg = Dialogos(self, "Script SQL") #dlg.AboutBox() #dlg.ShowModal() def Puntero(self, evt): self.GetActiveChild().canvas.SetCursor(wx.STANDARD_CURSOR) self.GetActiveChild().click = 0 self.GetActiveChild().relacion = 0
ajdelgados/Sofia
modules/main.py
Python
gpl-3.0
37,233
/*************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Qt Software Information (qt-info@nokia.com) ** ** ** Non-Open Source Usage ** ** Licensees may use this file in accordance with the Qt Beta Version ** License Agreement, Agreement version 2.2 provided with the Software or, ** alternatively, in accordance with the terms contained in a written ** agreement between you and Nokia. ** ** GNU General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU General ** Public License versions 2.0 or 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 GNU ** General Public Licensing requirements will be met: ** ** http://www.fsf.org/licensing/licenses/info/GPLv2.html and ** http://www.gnu.org/copyleft/gpl.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt GPL Exception ** version 1.3, included in the file GPL_EXCEPTION.txt in this package. ** ***************************************************************************/ #ifndef MODULESPAGE_H #define MODULESPAGE_H #include <QtCore/QMap> #include <QtGui/QWizard> QT_BEGIN_NAMESPACE class QCheckBox; QT_END_NAMESPACE namespace Qt4ProjectManager { namespace Internal { class ModulesPage : public QWizardPage { Q_OBJECT public: explicit ModulesPage(QWidget* parent = 0); QString selectedModules() const; QString deselectedModules() const; void setModuleSelected(const QString &module, bool selected = true) const; void setModuleEnabled(const QString &module, bool enabled = true) const; // Return the key that goes into the Qt config line for a module static QString idOfModule(const QString &module); private: QMap<QString, QCheckBox*> m_moduleCheckBoxMap; QString modules(bool selected = true) const; }; } // namespace Internal } // namespace Qt4ProjectManager #endif // MODULESPAGE_H
mblsha/qt-creator
src/plugins/qt4projectmanager/wizards/modulespage.h
C
gpl-3.0
2,191
<?php namespace Glorpen\Propel\PropelBundle\Dispatcher; use Symfony\Component\EventDispatcher\Event; /** * Simple proxy class, stores callable to dispatcher getter for later usage * * @author Arkadiusz Dzięgiel <arkadiusz.dziegiel@glorpen.pl> */ class EventDispatcherProxy { private static $dispatcher = null; private static $dispatcher_args = array(); /** * Sets dispatcher getter * @param callable $callback * @param array $args */ public static function setDispatcherGetter($callback, $args = array()) { self::$dispatcher = $callback; self::$dispatcher_args = $args; } /** * Triggers event. * @param string $name * @param Event $data one of Glorpen\Propel\PropelBundle\Events */ public static function trigger($name, Event $data) { if (self::$dispatcher) { if (!is_array($name)) { $name=array($name); } foreach ($name as $n) { call_user_func_array(self::$dispatcher, self::$dispatcher_args)->dispatch($n, $data); } } } }
glorpen/GlorpenPropelBundle
src/Dispatcher/EventDispatcherProxy.php
PHP
gpl-3.0
1,138
struct bonk { }; void test(bonk X) { X = X; } // RUN: c-index-test -test-annotate-tokens=%s:1:1:5:5 %s // CHECK: Keyword: "struct" [1:1 - 1:7] StructDecl=bonk:1:8 (Definition) // CHECK: Identifier: "bonk" [1:8 - 1:12] StructDecl=bonk:1:8 (Definition) // CHECK: Punctuation: "{" [1:13 - 1:14] StructDecl=bonk:1:8 (Definition) // CHECK: Punctuation: "}" [1:15 - 1:16] StructDecl=bonk:1:8 (Definition) // CHECK: Punctuation: ";" [1:16 - 1:17] // CHECK: Keyword: "void" [2:1 - 2:5] FunctionDecl=test:2:6 (Definition) // CHECK: Identifier: "test" [2:6 - 2:10] FunctionDecl=test:2:6 (Definition) // CHECK: Punctuation: "(" [2:10 - 2:11] FunctionDecl=test:2:6 (Definition) // CHECK: Identifier: "bonk" [2:11 - 2:15] TypeRef=struct bonk:1:8 // CHECK: Identifier: "X" [2:16 - 2:17] ParmDecl=X:2:16 (Definition) // CHECK: Punctuation: ")" [2:17 - 2:18] FunctionDecl=test:2:6 (Definition) // CHECK: Punctuation: "{" [2:19 - 2:20] UnexposedStmt= // CHECK: Identifier: "X" [3:5 - 3:6] DeclRefExpr=X:2:16 // CHECK: Punctuation: "=" [3:7 - 3:8] DeclRefExpr=operator=:1:8 // CHECK: Identifier: "X" [3:9 - 3:10] DeclRefExpr=X:2:16 // CHECK: Punctuation: ";" [3:10 - 3:11] UnexposedStmt= // CHECK: Punctuation: "}" [4:1 - 4:2] UnexposedStmt=
chriskmanx/qmole
QMOLEDEV/llvm-2.8/tools/clang-2.8/test/Index/annotate-tokens.cpp
C++
gpl-3.0
1,229
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>TinyXml: Class Members</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.5.6 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul> </div> <div class="tabs"> <ul> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> <li><a href="functions_rela.html"><span>Related&nbsp;Functions</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="functions.html#index_a"><span>a</span></a></li> <li><a href="functions_0x62.html#index_b"><span>b</span></a></li> <li><a href="functions_0x63.html#index_c"><span>c</span></a></li> <li><a href="functions_0x64.html#index_d"><span>d</span></a></li> <li><a href="functions_0x65.html#index_e"><span>e</span></a></li> <li><a href="functions_0x66.html#index_f"><span>f</span></a></li> <li><a href="functions_0x67.html#index_g"><span>g</span></a></li> <li><a href="functions_0x68.html#index_h"><span>h</span></a></li> <li><a href="functions_0x69.html#index_i"><span>i</span></a></li> <li><a href="functions_0x6c.html#index_l"><span>l</span></a></li> <li class="current"><a href="functions_0x6d.html#index_m"><span>m</span></a></li> <li><a href="functions_0x6e.html#index_n"><span>n</span></a></li> <li><a href="functions_0x6f.html#index_o"><span>o</span></a></li> <li><a href="functions_0x70.html#index_p"><span>p</span></a></li> <li><a href="functions_0x71.html#index_q"><span>q</span></a></li> <li><a href="functions_0x72.html#index_r"><span>r</span></a></li> <li><a href="functions_0x73.html#index_s"><span>s</span></a></li> <li><a href="functions_0x74.html#index_t"><span>t</span></a></li> <li><a href="functions_0x75.html#index_u"><span>u</span></a></li> <li><a href="functions_0x76.html#index_v"><span>v</span></a></li> <li><a href="functions_0x77.html#index_w"><span>w</span></a></li> <li><a href="functions_0x7e.html#index_~"><span>~</span></a></li> </ul> </div> </div> <div class="contents"> Here is a list of all documented class members with links to the class documentation for each member: <p> <h3><a class="anchor" name="index_m">- m -</a></h3><ul> <li>m_details : <a class="el" href="classticpp_1_1Exception.html#0057429c19a0a4a1a9b71b406c3ac148">ticpp::Exception</a> <li>m_impRC : <a class="el" href="classticpp_1_1Base.html#86fe14ac3de56a64ba09148c5c5c352d">ticpp::Base</a> <li>m_spawnedWrappers : <a class="el" href="classTiCppRC.html#ca23455c46db995375ce4157fce51aec">TiCppRC</a> <li>m_tiXmlPointer : <a class="el" href="classticpp_1_1NodeImp.html#d7fe0c608ade8e6fead0fa560d2278d2">ticpp::NodeImp&lt; T &gt;</a> </ul> </div> <hr size="1"><address style="text-align: right;"><small>Generated on Sun Feb 15 23:12:13 2009 for TinyXml by&nbsp; <a href="http://www.doxygen.org/index.html"> <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.6 </small></address> </body> </html>
cppisfun/GameEngine
foreign/TinyXML++/docs/functions_0x6d.html
HTML
gpl-3.0
4,086
using System; using System.ComponentModel; using System.Dynamic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Media; using Artemis.DAL; using Artemis.DeviceProviders; using Artemis.Events; using Artemis.InjectionFactories; using Artemis.Managers; using Artemis.Models; using Artemis.Profiles; using Artemis.Profiles.Layers.Models; using Artemis.Profiles.Layers.Types.Folder; using Artemis.Services; using Artemis.Styles.DropTargetAdorners; using Artemis.Utilities; using Caliburn.Micro; using GongSolutions.Wpf.DragDrop; using MahApps.Metro.Controls.Dialogs; using Ninject; using DragDropEffects = System.Windows.DragDropEffects; using IDropTarget = GongSolutions.Wpf.DragDrop.IDropTarget; using MouseEventArgs = System.Windows.Input.MouseEventArgs; using Screen = Caliburn.Micro.Screen; using Timer = System.Timers.Timer; namespace Artemis.ViewModels.Profiles { public sealed class ProfileEditorViewModel : Screen, IDropTarget { private readonly EffectModel _gameModel; private readonly ILayerEditorVmFactory _layerEditorVmFactory; private readonly MainManager _mainManager; private readonly Timer _saveTimer; private ImageSource _keyboardPreview; private BindableCollection<LayerModel> _layers; private BindableCollection<ProfileModel> _profiles; private bool _saving; private ProfileModel _selectedProfile; public ProfileEditorViewModel(MainManager mainManager, EffectModel gameModel, ProfileViewModel profileViewModel, MetroDialogService dialogService, string lastProfile, ILayerEditorVmFactory layerEditorVmFactory) { _mainManager = mainManager; _gameModel = gameModel; _layerEditorVmFactory = layerEditorVmFactory; Profiles = new BindableCollection<ProfileModel>(); Layers = new BindableCollection<LayerModel>(); ProfileViewModel = profileViewModel; DialogService = dialogService; LastProfile = lastProfile; PropertyChanged += EditorStateHandler; ProfileViewModel.PropertyChanged += LayerSelectedHandler; mainManager.DeviceManager.OnKeyboardChangedEvent += DeviceManagerOnOnKeyboardChangedEvent; _saveTimer = new Timer(5000); _saveTimer.Elapsed += ProfileSaveHandler; LoadProfiles(); } [Inject] public MetroDialogService DialogService { get; set; } public string LastProfile { get; set; } public ProfileViewModel ProfileViewModel { get; set; } public bool EditorEnabled => SelectedProfile != null && !SelectedProfile.IsDefault && _mainManager.DeviceManager.ActiveKeyboard != null; public BindableCollection<ProfileModel> Profiles { get { return _profiles; } set { if (Equals(value, _profiles)) return; _profiles = value; NotifyOfPropertyChange(() => Profiles); } } public BindableCollection<LayerModel> Layers { get { return _layers; } set { if (Equals(value, _layers)) return; _layers = value; NotifyOfPropertyChange(() => Layers); } } public ProfileModel SelectedProfile { get { return _selectedProfile; } set { if (Equals(value, _selectedProfile)) return; _selectedProfile = value; NotifyOfPropertyChange(() => SelectedProfile); } } public ImageSource KeyboardPreview { get { return _keyboardPreview; } set { if (Equals(value, _keyboardPreview)) return; _keyboardPreview = value; NotifyOfPropertyChange(() => KeyboardPreview); } } public PreviewSettings? PreviewSettings => _mainManager.DeviceManager.ActiveKeyboard?.PreviewSettings; public bool ProfileSelected => SelectedProfile != null; public bool LayerSelected => SelectedProfile != null && ProfileViewModel.SelectedLayer != null; public void DragOver(IDropInfo dropInfo) { var source = dropInfo.Data as LayerModel; var target = dropInfo.TargetItem as LayerModel; if (source == null || target == null || source == target) return; if (dropInfo.InsertPosition == RelativeInsertPosition.TargetItemCenter && target.LayerType is FolderType) { dropInfo.DropTargetAdorner = typeof(DropTargetMetroHighlightAdorner); dropInfo.Effects = DragDropEffects.Copy; } else { dropInfo.DropTargetAdorner = typeof(DropTargetMetroInsertionAdorner); dropInfo.Effects = DragDropEffects.Move; } } public void Drop(IDropInfo dropInfo) { var source = dropInfo.Data as LayerModel; var target = dropInfo.TargetItem as LayerModel; if (source == null || target == null || source == target) return; // Don't allow a folder to become it's own child, that's just weird if (target.Parent == source) return; // Remove the source from it's old profile/parent if (source.Parent == null) { var profile = source.Profile; source.Profile.Layers.Remove(source); profile.FixOrder(); } else { var parent = source.Parent; source.Parent.Children.Remove(source); parent.FixOrder(); } if (dropInfo.InsertPosition == RelativeInsertPosition.TargetItemCenter && target.LayerType is FolderType) { // Insert into folder source.Order = -1; target.Children.Add(source); target.FixOrder(); target.Expanded = true; } else { // Insert the source into it's new profile/parent and update the order if (dropInfo.InsertPosition == RelativeInsertPosition.AfterTargetItem || dropInfo.InsertPosition == (RelativeInsertPosition.TargetItemCenter | RelativeInsertPosition.AfterTargetItem)) target.InsertAfter(source); else target.InsertBefore(source); } UpdateLayerList(source); } /// <summary> /// Handles chaning the active keyboard, updating the preview image and profiles collection /// </summary> private void DeviceManagerOnOnKeyboardChangedEvent(object sender, KeyboardChangedEventArgs e) { NotifyOfPropertyChange(() => PreviewSettings); LoadProfiles(); } public void Activate() { ProfileViewModel.Activate(); _saveTimer.Start(); } public void Deactivate() { ProfileViewModel.Deactivate(); _saveTimer.Stop(); } /// <summary> /// Loads all profiles for the current game and keyboard /// </summary> private void LoadProfiles() { Profiles.Clear(); if (_gameModel == null || _mainManager.DeviceManager.ActiveKeyboard == null) return; Profiles.AddRange(ProfileProvider.GetAll(_gameModel, _mainManager.DeviceManager.ActiveKeyboard)); // If a profile name was provided, try to load it ProfileModel lastProfileModel = null; if (!string.IsNullOrEmpty(LastProfile)) lastProfileModel = Profiles.FirstOrDefault(p => p.Name == LastProfile); SelectedProfile = lastProfileModel ?? Profiles.FirstOrDefault(); } public void EditLayerFromDoubleClick() { if (ProfileViewModel.SelectedLayer?.LayerType is FolderType) return; EditLayer(); } public void EditLayer() { if (ProfileViewModel.SelectedLayer == null) return; var selectedLayer = ProfileViewModel.SelectedLayer; EditLayer(selectedLayer); } /// <summary> /// Opens a new LayerEditorView for the given layer /// </summary> /// <param name="layer">The layer to open the view for</param> public void EditLayer(LayerModel layer) { if (layer == null) return; IWindowManager manager = new WindowManager(); var editorVm = _layerEditorVmFactory.CreateLayerEditorVm(_gameModel.DataModel, layer); dynamic settings = new ExpandoObject(); var icon = ImageUtilities.GenerateWindowIcon(); settings.Title = "Artemis | Edit " + layer.Name; settings.Icon = icon; manager.ShowDialog(editorVm, null, settings); //// The layer editor VM may have created a new instance of the layer, reapply it to the list //layer.Replace(editorVm.Layer); //layer = editorVm.Layer; // If the layer was a folder, but isn't anymore, assign it's children to it's parent. if (!(layer.LayerType is FolderType) && layer.Children.Any()) { while (layer.Children.Any()) { var child = layer.Children[0]; layer.Children.Remove(child); if (layer.Parent != null) { layer.Parent.Children.Add(child); layer.Parent.FixOrder(); } else { layer.Profile.Layers.Add(child); layer.Profile.FixOrder(); } } } UpdateLayerList(layer); } /// <summary> /// Adds a new layer to the profile and selects it /// </summary> public LayerModel AddLayer() { if (SelectedProfile == null) return null; // Create a new layer var layer = LayerModel.CreateLayer(); if (ProfileViewModel.SelectedLayer != null) ProfileViewModel.SelectedLayer.InsertAfter(layer); else { SelectedProfile.Layers.Add(layer); SelectedProfile.FixOrder(); } UpdateLayerList(layer); return layer; } public LayerModel AddFolder() { var layer = AddLayer(); if (layer == null) return null; layer.Name = "New folder"; layer.LayerType = new FolderType(); layer.LayerType.SetupProperties(layer); return layer; } /// <summary> /// Removes the currently selected layer from the profile /// </summary> public void RemoveLayer() { RemoveLayer(ProfileViewModel.SelectedLayer); } /// <summary> /// Removes the given layer from the profile /// </summary> /// <param name="layer"></param> public void RemoveLayer(LayerModel layer) { if (layer == null) return; if (layer.Parent != null) { var parent = layer.Parent; layer.Parent.Children.Remove(layer); parent.FixOrder(); } else if (layer.Profile != null) { var profile = layer.Profile; layer.Profile.Layers.Remove(layer); profile.FixOrder(); } // Extra cleanup in case of a wonky layer that has no parent if (SelectedProfile.Layers.Contains(layer)) SelectedProfile.Layers.Remove(layer); UpdateLayerList(null); } public async void RenameLayer(LayerModel layer) { if (layer == null) return; var newName = await DialogService.ShowInputDialog("Rename layer", "Please enter a name for the layer", new MetroDialogSettings {DefaultText = layer.Name}); // Null when the user cancelled if (string.IsNullOrEmpty(newName)) return; layer.Name = newName; UpdateLayerList(layer); } /// <summary> /// Clones the currently selected layer and adds it to the profile, after the original /// </summary> public void CloneLayer() { if (ProfileViewModel.SelectedLayer == null) return; CloneLayer(ProfileViewModel.SelectedLayer); } /// <summary> /// Clones the given layer and adds it to the profile, after the original /// </summary> /// <param name="layer"></param> public void CloneLayer(LayerModel layer) { var clone = GeneralHelpers.Clone(layer); layer.InsertAfter(clone); UpdateLayerList(clone); } private void UpdateLayerList(LayerModel selectModel) { // Update the UI Layers.Clear(); ProfileViewModel.SelectedLayer = null; if (SelectedProfile != null) Layers.AddRange(SelectedProfile.Layers); if (selectModel == null) return; // A small delay to allow the profile list to rebuild Task.Factory.StartNew(() => { Thread.Sleep(100); ProfileViewModel.SelectedLayer = selectModel; }); } /// <summary> /// Handler for clicking /// </summary> /// <param name="e"></param> public void MouseDownKeyboardPreview(MouseButtonEventArgs e) { ProfileViewModel.MouseDownKeyboardPreview(e); } /// <summary> /// Second handler for clicking, selects a the layer the user clicked on /// if the used clicked on an empty spot, deselects the current layer /// </summary> /// <param name="e"></param> public void MouseUpKeyboardPreview(MouseButtonEventArgs e) { ProfileViewModel.MouseUpKeyboardPreview(e); } /// <summary> /// Handler for resizing and moving the currently selected layer /// </summary> /// <param name="e"></param> public void MouseMoveKeyboardPreview(MouseEventArgs e) { ProfileViewModel.MouseMoveKeyboardPreview(e); } /// <summary> /// Adds a new profile to the current game and keyboard /// </summary> public async void AddProfile() { if (_mainManager.DeviceManager.ActiveKeyboard == null) { DialogService.ShowMessageBox("Cannot add profile.", "To add a profile, please select a keyboard in the options menu first."); return; } var name = await DialogService.ShowInputDialog("Add new profile", "Please provide a profile name unique to this game and keyboard."); // Null when the user cancelled if (name == null) return; if (name.Length < 2) { DialogService.ShowMessageBox("Invalid profile name", "Please provide a valid profile name"); return; } var profile = new ProfileModel { Name = name, KeyboardSlug = _mainManager.DeviceManager.ActiveKeyboard.Slug, Width = _mainManager.DeviceManager.ActiveKeyboard.Width, Height = _mainManager.DeviceManager.ActiveKeyboard.Height, GameName = _gameModel.Name }; if (ProfileProvider.GetAll().Contains(profile)) { var overwrite = await DialogService.ShowQuestionMessageBox("Overwrite existing profile", "A profile with this name already exists for this game. Would you like to overwrite it?"); if (!overwrite.Value) return; } ProfileProvider.AddOrUpdate(profile); LoadProfiles(); SelectedProfile = profile; } public async void RenameProfile() { if (SelectedProfile == null) return; var name = await DialogService.ShowInputDialog("Rename profile", "Please enter a unique new profile name"); // Null when the user cancelled if (string.IsNullOrEmpty(name) || name.Length < 2) return; // Verify the name while (ProfileProvider.GetAll().Any(p => p.Name == name && p.GameName == SelectedProfile.GameName && p.KeyboardSlug == SelectedProfile.KeyboardSlug)) { name = await DialogService.ShowInputDialog("Name already in use", "Please enter a unique new profile name"); // Null when the user cancelled if (string.IsNullOrEmpty(name) || name.Length < 2) return; } var profile = SelectedProfile; SelectedProfile = null; ProfileProvider.RenameProfile(profile, name); LastProfile = name; LoadProfiles(); } public async void DuplicateProfile() { if (SelectedProfile == null) return; var newProfile = GeneralHelpers.Clone(SelectedProfile); newProfile.Name = await DialogService .ShowInputDialog("Duplicate profile", "Please enter a unique profile name"); // Null when the user cancelled if (string.IsNullOrEmpty(newProfile.Name)) return; // Verify the name while (ProfileProvider.GetAll().Contains(newProfile)) { newProfile.Name = await DialogService.ShowInputDialog("Name already in use", "Please enter a unique profile name"); // Null when the user cancelled if (string.IsNullOrEmpty(newProfile.Name)) return; } newProfile.IsDefault = false; ProfileProvider.AddOrUpdate(newProfile); LoadProfiles(); SelectedProfile = Profiles.FirstOrDefault(p => p.Name == newProfile.Name); } public async void DeleteProfile() { if (SelectedProfile == null) return; var confirm = await DialogService.ShowQuestionMessageBox("Delete profile", $"Are you sure you want to delete the profile named: {SelectedProfile.Name}?\n\n" + "This cannot be undone."); if (!confirm.Value) return; ProfileProvider.DeleteProfile(SelectedProfile); LoadProfiles(); } public async void ImportProfile() { if (_mainManager.DeviceManager.ActiveKeyboard == null) { DialogService.ShowMessageBox("Cannot import profile.", "To import a profile, please select a keyboard in the options menu first."); return; } var dialog = new OpenFileDialog {Filter = "Artemis profile (*.json)|*.json"}; var result = dialog.ShowDialog(); if (result != DialogResult.OK) return; var profile = ProfileProvider.LoadProfileIfValid(dialog.FileName); if (profile == null) { DialogService.ShowErrorMessageBox("Oh noes, the profile you provided is invalid. " + "If this keeps happening, please make an issue on GitHub and provide the profile."); return; } // Verify the game if (profile.GameName != _gameModel.Name) { DialogService.ShowErrorMessageBox( $"Oh oops! This profile is ment for {profile.GameName}, not {_gameModel.Name} :c"); return; } // Verify the keyboard var deviceManager = _mainManager.DeviceManager; if (profile.KeyboardSlug != deviceManager.ActiveKeyboard.Slug) { var adjustKeyboard = await DialogService.ShowQuestionMessageBox("Profile not inteded for this keyboard", $"Watch out, this profile wasn't ment for this keyboard, but for the {profile.KeyboardSlug}. " + "You can still import it but you'll probably have to do some adjusting\n\n" + "Continue?"); if (!adjustKeyboard.Value) return; // Resize layers that are on the full keyboard width profile.ResizeLayers(deviceManager.ActiveKeyboard); // Put layers back into the canvas if they fell outside it profile.FixBoundaries(deviceManager.ActiveKeyboard.KeyboardRectangle(1)); // Setup profile metadata to match the new keyboard profile.KeyboardSlug = deviceManager.ActiveKeyboard.Slug; profile.Width = deviceManager.ActiveKeyboard.Width; profile.Height = deviceManager.ActiveKeyboard.Height; } profile.IsDefault = false; // Verify the name while (ProfileProvider.GetAll().Contains(profile)) { profile.Name = await DialogService.ShowInputDialog("Rename imported profile", "A profile with this name already exists for this game. Please enter a new name"); // Null when the user cancelled if (string.IsNullOrEmpty(profile.Name)) return; } ProfileProvider.AddOrUpdate(profile); LoadProfiles(); SelectedProfile = Profiles.FirstOrDefault(p => p.Name == profile.Name); } public void ExportProfile() { if (SelectedProfile == null) return; var dialog = new SaveFileDialog {Filter = "Artemis profile (*.json)|*.json"}; var result = dialog.ShowDialog(); if (result != DialogResult.OK) return; ProfileProvider.ExportProfile(SelectedProfile, dialog.FileName); } private void EditorStateHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName != "SelectedProfile") return; // Update editor enabled state NotifyOfPropertyChange(() => EditorEnabled); // Update ProfileViewModel ProfileViewModel.SelectedProfile = SelectedProfile; // Update interface Layers.Clear(); if (SelectedProfile != null) Layers.AddRange(SelectedProfile.Layers); NotifyOfPropertyChange(() => ProfileSelected); } private void LayerSelectedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName != "SelectedLayer") return; NotifyOfPropertyChange(() => LayerSelected); } private void ProfileSaveHandler(object sender, ElapsedEventArgs e) { if (_saving || SelectedProfile == null) return; _saving = true; try { ProfileProvider.AddOrUpdate(SelectedProfile); } catch (Exception) { // ignored } _saving = false; } } }
DarthAffe/Artemis
Artemis/Artemis/ViewModels/Profiles/ProfileEditorViewModel.cs
C#
gpl-3.0
24,667
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CAICombatTree : CAIMainTree { public CAICombatTree(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAICombatTree(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
Traderain/Wolven-kit
WolvenKit.CR2W/Types/W3/RTTIConvert/CAICombatTree.cs
C#
gpl-3.0
653
import React, { Component } from 'react'; import { connect } from 'react-redux'; export class Footer extends Component { render() { return ( <footer className="opendata-footer footer"> <nav className="navbar bottom navbar-expand-lg navbar-dark bg-primary"> <div> <span style={{ color: "#fff" }}>{this.props.text}:</span> <a href="http://www.vectr.consulting"><img src="logos/VectrConsulting.svg" height={30} /></a> <a href="http://www.vereenvoudiging.be/" ><img src="logos/DAV.png" height={30} /></a> <a href="http://www.dekamer.be/" ><img src="logos/dekamer.jpg" height={30} /></a> <a href="https://neo4j.com/" ><img src="logos/Neo4j.png" height={30} /></a> </div> </nav> </footer> ); } } export default connect( state => ({ text: state.locale.translation.footer }) )(Footer)
vectrconsulting/OpenParliament
src/main/javascript/dashboard/components/opendata.footer.js
JavaScript
gpl-3.0
1,022
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (1.8.0_65) on Mon Mar 27 21:15:04 CEST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=utf8"> <title>O-Index</title> <meta name="date" content="2017-03-27"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="O-Index"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-11.html">Prev Letter</a></li> <li><a href="index-13.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-12.html" target="_top">Frames</a></li> <li><a href="index-12.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">C</a>&nbsp;<a href="index-3.html">D</a>&nbsp;<a href="index-4.html">E</a>&nbsp;<a href="index-5.html">F</a>&nbsp;<a href="index-6.html">G</a>&nbsp;<a href="index-7.html">H</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">L</a>&nbsp;<a href="index-10.html">M</a>&nbsp;<a href="index-11.html">N</a>&nbsp;<a href="index-12.html">O</a>&nbsp;<a href="index-13.html">P</a>&nbsp;<a href="index-14.html">R</a>&nbsp;<a href="index-15.html">S</a>&nbsp;<a href="index-16.html">T</a>&nbsp;<a href="index-17.html">U</a>&nbsp;<a href="index-18.html">W</a>&nbsp;<a href="index-19.html">X</a>&nbsp;<a name="I:O"> <!-- --> </a> <h2 class="title">O</h2> <dl> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/activities/NavigateActivity.html#onBackPressed--">onBackPressed()</a></span> - Method in class com.edt.velizy.edtvelizy.activities.<a href="../com/edt/velizy/edtvelizy/activities/NavigateActivity.html" title="class in com.edt.velizy.edtvelizy.activities">NavigateActivity</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/activities/AboutActivity.html#onCreate-Bundle-">onCreate(Bundle)</a></span> - Method in class com.edt.velizy.edtvelizy.activities.<a href="../com/edt/velizy/edtvelizy/activities/AboutActivity.html" title="class in com.edt.velizy.edtvelizy.activities">AboutActivity</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/activities/ChooseGroupActivity.html#onCreate-Bundle-">onCreate(Bundle)</a></span> - Method in class com.edt.velizy.edtvelizy.activities.<a href="../com/edt/velizy/edtvelizy/activities/ChooseGroupActivity.html" title="class in com.edt.velizy.edtvelizy.activities">ChooseGroupActivity</a></dt> <dd> <div class="block">Fonction appelée lors de la création de l'activité</div> </dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/activities/LoginActivity.html#onCreate-Bundle-">onCreate(Bundle)</a></span> - Method in class com.edt.velizy.edtvelizy.activities.<a href="../com/edt/velizy/edtvelizy/activities/LoginActivity.html" title="class in com.edt.velizy.edtvelizy.activities">LoginActivity</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/activities/NavigateActivity.html#onCreate-Bundle-">onCreate(Bundle)</a></span> - Method in class com.edt.velizy.edtvelizy.activities.<a href="../com/edt/velizy/edtvelizy/activities/NavigateActivity.html" title="class in com.edt.velizy.edtvelizy.activities">NavigateActivity</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html#onCreate-Bundle-">onCreate(Bundle)</a></span> - Method in class com.edt.velizy.edtvelizy.fragments.<a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html" title="class in com.edt.velizy.edtvelizy.fragments">EDTFragment</a></dt> <dd> <div class="block">Réécriture de la fonction onCreate qui va récupéré les informations donnés</div> </dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html#onCreateOptionsMenu-Menu-MenuInflater-">onCreateOptionsMenu(Menu, MenuInflater)</a></span> - Method in class com.edt.velizy.edtvelizy.fragments.<a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html" title="class in com.edt.velizy.edtvelizy.fragments">EDTFragment</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html#onCreateView-LayoutInflater-ViewGroup-Bundle-">onCreateView(LayoutInflater, ViewGroup, Bundle)</a></span> - Method in class com.edt.velizy.edtvelizy.fragments.<a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html" title="class in com.edt.velizy.edtvelizy.fragments">EDTFragment</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/activities/NavigateActivity.html#onDestroy--">onDestroy()</a></span> - Method in class com.edt.velizy.edtvelizy.activities.<a href="../com/edt/velizy/edtvelizy/activities/NavigateActivity.html" title="class in com.edt.velizy.edtvelizy.activities">NavigateActivity</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html#onEventClick-com.alamkanak.weekview.WeekViewEvent-RectF-">onEventClick(WeekViewEvent, RectF)</a></span> - Method in class com.edt.velizy.edtvelizy.fragments.<a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html" title="class in com.edt.velizy.edtvelizy.fragments">EDTFragment</a></dt> <dd> <div class="block">Fonction appelée lors d'un clic sur un cours</div> </dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/services/SuiviService.html#onHandleIntent-Intent-">onHandleIntent(Intent)</a></span> - Method in class com.edt.velizy.edtvelizy.services.<a href="../com/edt/velizy/edtvelizy/services/SuiviService.html" title="class in com.edt.velizy.edtvelizy.services">SuiviService</a></dt> <dd> <div class="block">Fonction qui est appelée à chaque appel de notre service</div> </dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html#onMonthChange-int-int-">onMonthChange(int, int)</a></span> - Method in class com.edt.velizy.edtvelizy.fragments.<a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html" title="class in com.edt.velizy.edtvelizy.fragments">EDTFragment</a></dt> <dd> <div class="block">Fonction qui charge nos cours dans l'emploi du temps</div> </dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/activities/NavigateActivity.html#onNavigationItemSelected-MenuItem-">onNavigationItemSelected(MenuItem)</a></span> - Method in class com.edt.velizy.edtvelizy.activities.<a href="../com/edt/velizy/edtvelizy/activities/NavigateActivity.html" title="class in com.edt.velizy.edtvelizy.activities">NavigateActivity</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/activities/AboutActivity.html#onOptionsItemSelected-MenuItem-">onOptionsItemSelected(MenuItem)</a></span> - Method in class com.edt.velizy.edtvelizy.activities.<a href="../com/edt/velizy/edtvelizy/activities/AboutActivity.html" title="class in com.edt.velizy.edtvelizy.activities">AboutActivity</a></dt> <dd> <div class="block">Cette fonction est appelée quand un item du menu est appuyé</div> </dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html#onOptionsItemSelected-MenuItem-">onOptionsItemSelected(MenuItem)</a></span> - Method in class com.edt.velizy.edtvelizy.fragments.<a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html" title="class in com.edt.velizy.edtvelizy.fragments">EDTFragment</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/activities/ChooseGroupActivity.DownloadEDTTask.html#onPostExecute-java.lang.String-">onPostExecute(String)</a></span> - Method in class com.edt.velizy.edtvelizy.activities.<a href="../com/edt/velizy/edtvelizy/activities/ChooseGroupActivity.DownloadEDTTask.html" title="class in com.edt.velizy.edtvelizy.activities">ChooseGroupActivity.DownloadEDTTask</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/activities/LoginActivity.DownloadWebpageTask.html#onPostExecute-java.lang.String-">onPostExecute(String)</a></span> - Method in class com.edt.velizy.edtvelizy.activities.<a href="../com/edt/velizy/edtvelizy/activities/LoginActivity.DownloadWebpageTask.html" title="class in com.edt.velizy.edtvelizy.activities">LoginActivity.DownloadWebpageTask</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html#onPrepareOptionsMenu-Menu-">onPrepareOptionsMenu(Menu)</a></span> - Method in class com.edt.velizy.edtvelizy.fragments.<a href="../com/edt/velizy/edtvelizy/fragments/EDTFragment.html" title="class in com.edt.velizy.edtvelizy.fragments">EDTFragment</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/services/MyAlarmReceiver.html#onReceive-Context-Intent-">onReceive(Context, Intent)</a></span> - Method in class com.edt.velizy.edtvelizy.services.<a href="../com/edt/velizy/edtvelizy/services/MyAlarmReceiver.html" title="class in com.edt.velizy.edtvelizy.services">MyAlarmReceiver</a></dt> <dd> <div class="block">Réécriture de la fonction onReceive pour lancer notre service Cette fonction est appelée automatique donc on ne se préoccupe pas des arguments</div> </dd> <dt><span class="memberNameLink"><a href="../com/edt/velizy/edtvelizy/timetable/timetable.html#option">option</a></span> - Variable in class com.edt.velizy.edtvelizy.timetable.<a href="../com/edt/velizy/edtvelizy/timetable/timetable.html" title="class in com.edt.velizy.edtvelizy.timetable">timetable</a></dt> <dd> <div class="block">Le titre de l'emploi du temps</div> </dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">C</a>&nbsp;<a href="index-3.html">D</a>&nbsp;<a href="index-4.html">E</a>&nbsp;<a href="index-5.html">F</a>&nbsp;<a href="index-6.html">G</a>&nbsp;<a href="index-7.html">H</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">L</a>&nbsp;<a href="index-10.html">M</a>&nbsp;<a href="index-11.html">N</a>&nbsp;<a href="index-12.html">O</a>&nbsp;<a href="index-13.html">P</a>&nbsp;<a href="index-14.html">R</a>&nbsp;<a href="index-15.html">S</a>&nbsp;<a href="index-16.html">T</a>&nbsp;<a href="index-17.html">U</a>&nbsp;<a href="index-18.html">W</a>&nbsp;<a href="index-19.html">X</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-11.html">Prev Letter</a></li> <li><a href="index-13.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-12.html" target="_top">Frames</a></li> <li><a href="index-12.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Astropilot/EDTVelizy
app/doc/index-files/index-12.html
HTML
gpl-3.0
13,338
package ch.cyberduck.core.local; /* * Copyright (c) 2002-2018 iterate GmbH. All rights reserved. * https://cyberduck.io/ * * 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. */ import ch.cyberduck.core.Local; import ch.cyberduck.core.LocaleFactory; import ch.cyberduck.core.exception.AccessDeniedException; import ch.cyberduck.core.local.features.Symlink; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class DefaultSymlinkFeature implements Symlink { @Override public void symlink(final Local file, final String target) throws AccessDeniedException { try { Files.createSymbolicLink(Paths.get(file.getAbsolute()), Paths.get(target)); } catch(IOException | UnsupportedOperationException e) { throw new AccessDeniedException(String.format("%s %s", LocaleFactory.localizedString("Cannot create file", "Error"), file.getAbsolute()), e); } } }
iterate-ch/cyberduck
core/src/main/java/ch/cyberduck/core/local/DefaultSymlinkFeature.java
Java
gpl-3.0
1,430
package smps.stuffmyprofessorsays; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; import java.util.HashMap; import java.util.List; /** * Created by tricianemiroff on 1/26/16. */ public class ExpandableListAdapter extends BaseExpandableListAdapter { private Context context; private List<String> listHeader; private HashMap<String, List<String>> listChild; public ExpandableListAdapter(Context context1, List<String> listHeader1, HashMap<String, List<String>> listChild1){ this.context = context1; this.listHeader = listHeader1; this.listChild = listChild1; } /** * Gets the number of groups. * * @return the number of groups */ @Override public int getGroupCount() { return this.listHeader.size(); } /** * Gets the number of children in a specified group. * * @param groupPosition the position of the group for which the children * count should be returned * @return the children count in the specified group */ @Override public int getChildrenCount(int groupPosition) { return this.listChild.get(this.listHeader.get(groupPosition)).size(); } /** * Gets the data associated with the given group. * * @param groupPosition the position of the group * @return the data child for the specified group */ @Override public Object getGroup(int groupPosition) { return this.listHeader.get(groupPosition); } /** * Gets the data associated with the given child within the given group. * * @param groupPosition the position of the group that the child resides in * @param childPosition the position of the child with respect to other * children in the group * @return the data of the child */ @Override public Object getChild(int groupPosition, int childPosition) { return this.listChild.get(this.listHeader.get(groupPosition)).get(childPosition); } /** * Gets the ID for the group at the given position. This group ID must be * unique across groups. The combined ID (see * {@link #getCombinedGroupId(long)}) must be unique across ALL items * (groups and all children). * * @param groupPosition the position of the group for which the ID is wanted * @return the ID associated with the group */ @Override public long getGroupId(int groupPosition) { return groupPosition; } /** * Gets the ID for the given child within the given group. This ID must be * unique across all children within the group. The combined ID (see * {@link #getCombinedChildId(long, long)}) must be unique across ALL items * (groups and all children). * * @param groupPosition the position of the group that contains the child * @param childPosition the position of the child within the group for which * the ID is wanted * @return the ID associated with the child */ @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } /** * Indicates whether the child and group IDs are stable across changes to the * underlying data. * * @return whether or not the same ID always refers to the same object * @see */ @Override public boolean hasStableIds() { return false; } /** * Gets a View that displays the given group. This View is only for the * group--the Views for the group's children will be fetched using * {@link #getChildView(int, int, boolean, View, ViewGroup)}. * * @param groupPosition the position of the group for which the View is * returned * @param isExpanded whether the group is expanded or collapsed * @param convertView the old view to reuse, if possible. You should check * that this view is non-null and of an appropriate type before * using. If it is not possible to convert this view to display * the correct data, this method can create a new view. It is not * guaranteed that the convertView will have been previously * created by * {@link #getGroupView(int, boolean, View, ViewGroup)}. * @param parent the parent that this view will eventually be attached to * @return the View corresponding to the group at the specified position */ @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String headerTitle = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.list_header, null); } TextView lblListHeader = (TextView) convertView .findViewById(R.id.lblListHeader); lblListHeader.setTypeface(null, Typeface.BOLD); lblListHeader.setText(headerTitle); return convertView; } /** * Gets a View that displays the data for the given child within the given * group. * * @param groupPosition the position of the group that contains the child * @param childPosition the position of the child (for which the View is * returned) within the group * @param isLastChild Whether the child is the last child within the group * @param convertView the old view to reuse, if possible. You should check * that this view is non-null and of an appropriate type before * using. If it is not possible to convert this view to display * the correct data, this method can create a new view. It is not * guaranteed that the convertView will have been previously * created by * {@link #getChildView(int, int, boolean, View, ViewGroup)}. * @param parent the parent that this view will eventually be attached to * @return the View corresponding to the child at the specified position */ @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final String childText = (String) getChild(groupPosition, childPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.list_item, null); } TextView txtListChild = (TextView) convertView .findViewById(R.id.lblListItem); txtListChild.setText(childText); return convertView; } /** * Whether the child at the specified position is selectable. * * @param groupPosition the position of the group that contains the child * @param childPosition the position of the child within the group * @return whether the child is selectable. */ @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }
SMPSays/Android
app/src/main/java/smps/stuffmyprofessorsays/ExpandableListAdapter.java
Java
gpl-3.0
7,717
package org.latency4j.configuration; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.latency4j.AlertHandler; import org.latency4j.LatencyRequirement; /* * Schemagen options * schemagen -cp target\classes src\main\java\com\obixlabs\epsilon\configuration\Latency4JConfiguration.java -d src\main\resources\doctype */ /** * <p> * Bean-implementation which represents a Latency4J runtime configuration. It * consists of one or more {@link LatencyRequirementConfiguration latency * requirement templates}, and one or more {@link AlertHandlerConfiguration * alert handler templates}. * </p> * <p> * Put differently, a configuration consists of one * {@link AlertHandlerGroupConfig} and a {@link LatencyRequirementGroupConfig}, * where the {@link AlertHandlerGroupConfig} instance contains configuration for * the {@link AlertHandler receptors of the alerts} generated in relation * to the {@link LatencyRequirement requirements} configured via the * {@link LatencyRequirementGroupConfig} instance. * </p> */ @XmlRootElement(name = "latency4j", namespace = "www.github.com/latency4j") public class Latency4JConfiguration { /** * <p> * The {@link AlertHandlerConfiguration alert handler configurations}. * </p> */ private AlertHandlerGroupConfig alertHandlersConfiguration; /** * <p> * The {@link LatencyRequirementConfiguration latency requirement * configurations}. * </p> */ private LatencyRequirementGroupConfig latencyRequirementsConfiguration; /** * <p> * Default constructor. * </p> */ public Latency4JConfiguration() {} /** * <p> * Accessor to the {@link AlertHandlerConfiguration alert handler * configurations/templates}. * </p> * * @return The {@link AlertHandlerConfiguration alert handler * configurations}. */ @XmlElement(name = "alertHandlers") public AlertHandlerGroupConfig getAlertHandlersConfiguration() { return alertHandlersConfiguration; } /** * <p> * Mutator for the {@link AlertHandlerConfiguration alert handler * configurations/templates}. * </p> * * @param handlers * The {@link AlertHandlerConfiguration alert handler * configurations}. */ public void setAlertHandlersConfiguration(final AlertHandlerGroupConfig handlers) { this.alertHandlersConfiguration = handlers; } /** * <p> * Returns a reference to the {@link LatencyRequirementConfiguration latency * requirement configuration entries}. * </p> * * @return A reference to the {@link LatencyRequirementConfiguration latency * requirement configuration entries}. */ @XmlElement(name = "latencyRequirements") public LatencyRequirementGroupConfig getLatencyRequirementsConfiguration() { return latencyRequirementsConfiguration; } /** * <p> * Mutator for {@link LatencyRequirementConfiguration latency requirement * configurations}. * </p> * * @param latencyRequirements * The {@link LatencyRequirementConfiguration latency requirement * configuration entries}. */ public void setLatencyRequirementsConfiguration(final LatencyRequirementGroupConfig latencyRequirements) { this.latencyRequirementsConfiguration = latencyRequirements; } @Override public String toString() { StringBuffer result = new StringBuffer(); result.append("Latency4J Configuration: \n"); if (alertHandlersConfiguration != null) result.append(alertHandlersConfiguration.toString()); if (latencyRequirementsConfiguration != null) result.append(latencyRequirementsConfiguration.toString()); return result.toString(); } }// end class def
latency4j/repo
core/src/main/java/org/latency4j/configuration/Latency4JConfiguration.java
Java
gpl-3.0
3,775
using System; using UnityEngine; public class BLEController : MonoBehaviour { private const int framesPerSecond = 10; public BluetoothLE BLE; //public EyeColor eyeColor; public bool debugOutput; private float updateInterval = 0.1f; private float lastInterval; private float commandTimer; private bool[] motors; private bool available = true; private static int[] servoIndex; private byte[] servo_ch1 = new byte[] { 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0 }; private byte[] button_ch1; static BLEController() { BLEController.servoIndex = new int[] { 2, 1, 0, -1, 6, 7, -1, -1, 3, 4, 5, -1, -1, -1, -1, -1 }; } public BLEController() { this.updateInterval = 0.1f; this.available = true; this.servo_ch1 = new byte[] { 12, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0 }; byte[] numArray = new byte[20]; numArray[0] = 28; this.button_ch1 = numArray; } public bool Available() { return this.available; } private int colorFloatToInt(float color) { return (int)Mathf.Clamp(color * 8f, 0f, 7f); } public Color getColor() { return new Color(0f, 0f, 0f); } public int getServoIndex(int module, int slot) { if (null == this.BLE || !this.BLE.getConnectState() || !this.BLE.IsDrone()) { return BLEController.servoIndex[Mathf.Clamp(module * 4 + slot, 0, 15)]; } byte num = (byte)((module & 15) << 4 | slot & 15); for (int i = 0; i < 16; i++) { if (num == this.BLE.mapping[i]) { return i; } } return -1; } public void getSound(float time, Action callback) { if (this.debugOutput) { Debug.Log("ScriptControl.getSound called"); } } public bool getTouch() { return false; } private void OnDisable() { this.setMotors(false); } private void OnEnable() { this.motors = new bool[4]; } public void resetLEDs() { for (int i = 1; i <= 16; i++) { this.servo_ch1[i] = 4; } if (null != this.BLE) { this.BLE.SendCommand(this.servo_ch1); } } public void ServosReset() { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { this.setServo(i, j, 0f); } } } public void setColor(int source, Color color) { this.setColor(source, color, 0); } public void setColor(int source, Color color, int time) { if (this.debugOutput) { Debug.Log("ScriptControl.setColor called"); } int num = source & 7; int num1 = this.colorFloatToInt(color.g) << 3 | this.colorFloatToInt(color.r); int num2 = (time & 7) << 3 | this.colorFloatToInt(color.b); byte[] numArray = new byte[20]; numArray[0] = 17; numArray[1 + num * 2] = (byte)num1; numArray[2 + num * 2] = (byte)num2; if (null != this.BLE) { this.BLE.SendCommand(numArray); } //if (null != this.eyeColor) //{ // this.eyeColor.setColor(num, color, time); //} if (this.debugOutput) { Debug.Log(string.Concat("int1: ", Convert.ToString(num1, 2).PadLeft(8, '0'), " - int2: ", Convert.ToString(num2, 2).PadLeft(8, '0'))); } } private void setMotors() { this.setMotors(true); } private void setMotors(bool existing) { if (!existing) { this.motors = new bool[4]; } if (null != this.BLE) { this.BLE.setMotors(this.motors); } } public void setMove(bool forward, float distance, float speed) { bool flag; if (this.debugOutput) { Debug.Log(string.Concat(new object[] { "ScriptControl.setMove called: ", forward, " - distance: ", distance, " - speed: ", speed })); } if (!forward) { this.motors[3] = true; this.motors[1] = true; } else { this.motors[2] = true; this.motors[0] = true; } this.commandTimer = Time.realtimeSinceStartup + distance; this.available = false; this.setMotors(); } public void setMoveLeft(bool front, bool rear) { if (this.motors[0] == front && this.motors[1] == rear) { return; } this.motors[0] = front; this.motors[1] = rear; this.setMotors(); if (this.debugOutput) { Debug.Log(string.Concat(new object[] { "setMoveLeft: ", front, ", ", rear })); } } public void setMoveRight(bool front, bool rear) { if (this.motors[2] == front && this.motors[3] == rear) { return; } this.motors[2] = front; this.motors[3] = rear; this.setMotors(); if (this.debugOutput) { Debug.Log(string.Concat(new object[] { "setMoveRight: ", front, ", ", rear })); } } public void setPCBLEDs(bool led0_Blue, bool led1_Red, bool led2_Green, bool led3_Yellow) { object obj; object obj1; object obj2; object obj3; byte[] numArray = (byte[])this.button_ch1.Clone(); byte[] buttonCh1 = this.button_ch1; if (!led0_Blue) { obj = null; } else { obj = 1; } buttonCh1[1] = (byte)obj; byte[] buttonCh11 = this.button_ch1; if (!led1_Red) { obj1 = null; } else { obj1 = 1; } buttonCh11[2] = (byte)obj1; byte[] numArray1 = this.button_ch1; if (!led2_Green) { obj2 = null; } else { obj2 = 1; } numArray1[3] = (byte)obj2; byte[] buttonCh12 = this.button_ch1; if (!led3_Yellow) { obj3 = null; } else { obj3 = 1; } buttonCh12[4] = (byte)obj3; if (numArray[1] == this.button_ch1[1] && numArray[2] == this.button_ch1[2] && numArray[3] == this.button_ch1[3] && numArray[4] == this.button_ch1[4]) { return; } if (null != this.BLE) { this.BLE.SendCommand(this.button_ch1); } //if (null != this.eyeColor) //{ // this.eyeColor.setButtons(led1_Red, led2_Green, led0_Blue, led3_Yellow); //} if (this.debugOutput) { Debug.Log(string.Concat(new object[] { "setPCBLEDs called (", led0_Blue, ", ", led1_Red, ", ", led2_Green, ", ", led3_Yellow, ")" })); } } public void setPCBLEDs(int slot, bool on) { object obj; byte[] numArray = (byte[])this.button_ch1.Clone(); slot = Mathf.Clamp(slot, 0, 3) + 1; byte[] buttonCh1 = this.button_ch1; int num = slot; if (!on) { obj = null; } else { obj = 1; } buttonCh1[num] = (byte)obj; bool flag = this.button_ch1[1] != 0; bool buttonCh11 = this.button_ch1[2] != 0; bool flag1 = this.button_ch1[3] != 0; bool buttonCh12 = this.button_ch1[4] != 0; if (numArray[1] == this.button_ch1[1] && numArray[2] == this.button_ch1[2] && numArray[3] == this.button_ch1[3] && numArray[4] == this.button_ch1[4]) { return; } if (null != this.BLE) { this.BLE.SendCommand(this.button_ch1); } //if (null != this.eyeColor) //{ // this.eyeColor.setButtons(flag, buttonCh11, flag1, buttonCh12); //} if (this.debugOutput) { Debug.Log(string.Concat(new object[] { "setPCBLEDs called (", slot, ", ", on, ")" })); } } public void setPose(byte[] servos) { this.setPose(servos, 0f); } public void setPose(byte[] servos, float time) { if (this.debugOutput) { Debug.Log(string.Concat(new object[] { "ScriptControl.setPose called: ", (int)servos.Length, " - time: ", time })); } } public void setRagdoll(bool enable) { if (this.debugOutput) { Debug.Log(string.Concat("ScriptControl.setRagdoll called:", enable)); } } public void setRotate(bool clockwise, float angle, float speed) { if (this.debugOutput) { Debug.Log(string.Concat(new object[] { "ScriptControl.setRotate called: ", clockwise, " - angle: ", angle, " - speed: ", speed })); } if (!clockwise) { this.motors[2] = true; } else { this.motors[0] = true; } this.commandTimer = Time.realtimeSinceStartup + angle; this.available = false; this.setMotors(); } public void setServo(int module, int slot, float angle) { bool flag = (this.BLE.robotType == 1 ? true : this.BLE.robotType == 4); int servoIndex = this.getServoIndex(module, slot); if (servoIndex < 0) { Debug.LogWarning(string.Concat(new object[] { "rejected setServo: ", module, ", ", slot })); return; } angle = -angle; angle = (90f + angle) / 180f; angle = Mathf.Clamp(angle, 0f, 1f); byte num = (byte)(24f + (float)((byte)(angle * 208f))); this.BLE.settargetPos(servoIndex, num); } public void setServoColor(int source, int color) { color = Mathf.Clamp(color, 0, 7); for (int i = 0; i < 8; i++) { if ((source & 1 << (i & 31)) != 0) { if (this.servo_ch1[i + 1] == (byte)color) { return; } this.servo_ch1[i + 1] = (byte)color; } } if (null != this.BLE) { this.BLE.SendCommand(this.servo_ch1); } //if (null != this.eyeColor) //{ // this.eyeColor.setServos(source, color); //} if (this.debugOutput) { Debug.Log(string.Concat(new object[] { "setServoColor(", source, ", ", color, ")" })); } } public void setServoColor(int source, Color color) { this.setServoColor(source, Mathf.RoundToInt(color.r) + Mathf.RoundToInt(color.g) * 2 + Mathf.RoundToInt(color.b) * 4); } public void setServoColor(int module, int slot, Color color) { if (module < 0) { return; } int servoIndex = this.getServoIndex(module, slot); if (servoIndex >= 0) { this.setServoColor(1 << (servoIndex & 31), color); return; } Debug.LogWarning(string.Concat(new object[] { "rejected setServoColor: ", module, ", ", slot })); } public void setServoIndex() { if (null == this.BLE || !this.BLE.getConnectState() || !this.BLE.IsDrone()) { return; } Array.Clear(this.BLE.mapping, 255, (int)this.BLE.mapping.Length); int num = 0; for (int i = 0; i < 8 && num < 16; i++) { for (int j = 0; j < 4 && num < 16; j++) { if (this.BLE.config[i * 4 + j] == 1) { int num1 = num; num = num1 + 1; this.BLE.mapping[num1] = (byte)((i & 15) << 4 | j & 15); Debug.Log(string.Concat(new object[] { "MAPPING : ", num - 1, " : ", this.BLE.mapping[num - 1] })); } } } if (num > 0) { Debug.Log("INDEX GOOD, SET MAPPING VIA BLE"); this.BLE.setMapping(); } } public void setSound(string effect) { if (this.debugOutput) { Debug.Log(string.Concat("ScriptControl.setSound called: ", effect)); } } public void stopMotors() { this.setMotors(false); } private void Update() { float _realtimeSinceStartup = Time.realtimeSinceStartup; //_realtimeSinceStartup <= lastInterval + updateInterval; if (_realtimeSinceStartup < this.commandTimer) { return; } this.available = true; this.lastInterval = _realtimeSinceStartup; } }
dzmen/Meccanoid-opensource-android
Meccanoid-android/Assets/Scripts/BLEController.cs
C#
gpl-3.0
12,826
/** */ package br.ufpe.ines.decode.taskDescription.impl; import br.ufpe.ines.decode.taskDescription.Measurement; import br.ufpe.ines.decode.taskDescription.TaskDescriptionPackage; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Measurement</b></em>'. * <!-- end-user-doc --> * * @generated */ public abstract class MeasurementImpl extends MinimalEObjectImpl.Container implements Measurement { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MeasurementImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return TaskDescriptionPackage.Literals.MEASUREMENT; } } //MeasurementImpl
netuh/DecodePlatformPlugin
br.edu.ufpe.ines.decode.model/src/br/ufpe/ines/decode/taskDescription/impl/MeasurementImpl.java
Java
gpl-3.0
853
<?php namespace Components; /** * Log_Appender_Log4cxx_File * * @api * @package net.evalcode.components.log * @subpackage appender.log4cxx * * @author evalcode.net */ class Log_Appender_Log4cxx_Syslog extends Log_Appender_Log4cxx { // OVERRIDES /** * @see \Components\Object::__toString() \Components\Object::__toString() */ public function __toString() { return sprintf('%s@%s{initialized: %s}', __CLASS__, $this->hashCode(), Boolean::valueOf($this->m_initialized) ); } //-------------------------------------------------------------------------- } ?>
evalcodenet/net.evalcode.components.runtime
source/log/appender/log4cxx/syslog.php
PHP
gpl-3.0
659
/******************************************************************************** Copyright (C) Binod Nepal, Mix Open Foundation (http://mixof.org). This file is part of MixERP. MixERP 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. MixERP 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 MixERP. If not, see <http://www.gnu.org/licenses/>. ***********************************************************************************/ using MixERP.Net.ApplicationState.Cache; using MixERP.Net.Common; using MixERP.Net.Common.Extensions; using MixERP.Net.Common.Helpers; using MixERP.Net.Core.Modules.Finance.Data.Helpers; using MixERP.Net.Entities; using MixERP.Net.Entities.Core; using MixERP.Net.FrontEnd.Base; using MixERP.Net.i18n.Resources; using MixERP.Net.TransactionGovernor; using MixERP.Net.WebControls.Common; using MixERP.Net.WebControls.Flag; using System; using System.Collections.ObjectModel; using System.Globalization; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace MixERP.Net.Core.Modules.Finance.Reports { public partial class AccountStatement : MixERPUserControl { public override void OnControlLoad(object sender, EventArgs e) { this.CreateHeader(this.Placeholder1); this.CreateTopPanel(this.Placeholder1); this.CreateTabs(this.Placeholder1); this.CreateFlagPanel(this.Placeholder1); this.CreateReconcileModal(this.Placeholder1); this.AutoInitialize(); } private void AutoInitialize() { string accountNumber = this.Request.QueryString["AccountNumber"]; long accountId = Conversion.TryCastLong(this.Request.QueryString["AccountId"]); DateTime from = Conversion.TryCastDate(this.Request.QueryString["From"]); DateTime to = Conversion.TryCastDate(this.Request.QueryString["To"]); if (!string.IsNullOrWhiteSpace(accountNumber)) { this.accountNumberInputText.Value = accountNumber; } else { if (accountId > 0) { accountNumber = AccountHelper.GetAccountNumberByAccountId(AppUsers.GetCurrentUserDB(), accountId); this.accountNumberInputText.Value = accountNumber; } else { return; } } if (from != DateTime.MinValue) { this.fromDateTextBox.Text = from.Date.ToShortDateString(); } if (to != DateTime.MinValue) { this.toDateTextBox.Text = to.Date.ToShortDateString(); } this.BindGridView(); this.CreateAccountOverviewPanel(this.accountOverviewTab); } private void CreateFlagPanel(Control container) { using (FlagControl flag = new FlagControl()) { flag.ID = "FlagPopUnder"; flag.AssociatedControlId = "FlagButton"; flag.OnClientClick = "return getSelectedItems();"; flag.CssClass = "ui form segment initially hidden"; flag.Updated += this.Flag_Updated; flag.Catalog = AppUsers.GetCurrentUserDB(); container.Controls.Add(flag); } } private void CreateHeader(Control container) { using (HtmlGenericControl header = new HtmlGenericControl("h2")) { header.InnerText = Titles.AccountStatement; container.Controls.Add(header); } } private void Flag_Updated(object sender, FlagUpdatedEventArgs e) { int flagTypeId = e.FlagId; const string resource = "account_statement"; const string resourceKey = "transaction_code"; int userId = AppUsers.GetCurrent().View.UserId.ToInt(); Flags.CreateFlag(AppUsers.GetCurrentUserDB(), userId, flagTypeId, resource, resourceKey, this.GetSelectedValues()); this.BindGridView(); this.CreateAccountOverviewPanel(this.accountOverviewTab); } private Collection<string> GetSelectedValues() { string selectedValues = this.selectedValuesHidden.Value; if (string.IsNullOrWhiteSpace(selectedValues)) { return new Collection<string>(); } Collection<string> values = new Collection<string>(); foreach (string value in selectedValues.Split(',')) { values.Add(value); } return values; } #region Tabs private void CreateTabs(Control container) { using (HtmlGenericControl tabMenu = new HtmlGenericControl("div")) { tabMenu.Attributes.Add("class", "ui top attached tabular menu"); using (HtmlAnchor transactionStatementTabMenu = new HtmlAnchor()) { transactionStatementTabMenu.Attributes.Add("class", "active item"); transactionStatementTabMenu.Attributes.Add("data-tab", "first"); transactionStatementTabMenu.InnerText = Titles.TransactionStatement; tabMenu.Controls.Add(transactionStatementTabMenu); } using (HtmlAnchor accountOverviewTabMenu = new HtmlAnchor()) { accountOverviewTabMenu.Attributes.Add("class", "item"); accountOverviewTabMenu.Attributes.Add("data-tab", "second"); accountOverviewTabMenu.InnerText = Titles.AccountOverview; tabMenu.Controls.Add(accountOverviewTabMenu); } container.Controls.Add(tabMenu); } using (HtmlGenericControl transactionStatementTab = new HtmlGenericControl("div")) { transactionStatementTab.Attributes.Add("class", "ui bottom attached active form tab segment"); transactionStatementTab.Attributes.Add("data-tab", "first"); this.CreateFormPanel(transactionStatementTab); this.CreateGridPanel(transactionStatementTab); container.Controls.Add(transactionStatementTab); } this.accountOverviewTab = new HtmlGenericControl("div"); this.accountOverviewTab.Attributes.Add("class", "ui bottom attached tab segment"); this.accountOverviewTab.Attributes.Add("data-tab", "second"); container.Controls.Add(this.accountOverviewTab); } #endregion Tabs #region IDisposable private HtmlInputText accountNumberInputText; private HtmlSelect accountNumberSelect; private Literal descriptionLiteral; private DateTextBox fromDateTextBox; private Literal headerLiteral; private HtmlGenericControl accountOverviewTab; private HiddenField selectedValuesHidden; private Button showButton; private GridView statementGridView; private DateTextBox toDateTextBox; private bool disposed; public override void Dispose() { if (!this.disposed) { this.Dispose(true); base.Dispose(); } } private void Dispose(bool disposing) { if (!disposing) { return; } if (this.accountNumberInputText != null) { this.accountNumberInputText.Dispose(); this.accountNumberInputText = null; } if (this.accountOverviewTab != null) { this.accountOverviewTab.Dispose(); this.accountOverviewTab = null; } if (this.accountNumberSelect != null) { this.accountNumberSelect.Dispose(); this.accountNumberSelect = null; } if (this.descriptionLiteral != null) { this.descriptionLiteral.Dispose(); this.descriptionLiteral = null; } if (this.fromDateTextBox != null) { this.fromDateTextBox.Dispose(); this.fromDateTextBox = null; } if (this.headerLiteral != null) { this.headerLiteral.Dispose(); this.headerLiteral = null; } if (this.selectedValuesHidden != null) { this.selectedValuesHidden.Dispose(); this.selectedValuesHidden = null; } if (this.showButton != null) { this.showButton.Dispose(); this.showButton = null; } if (this.statementGridView != null) { this.statementGridView.Dispose(); this.statementGridView = null; } if (this.toDateTextBox != null) { this.toDateTextBox.Dispose(); this.toDateTextBox = null; } this.disposed = true; } #endregion IDisposable #region Account Overview Panel private void AddBodyRow(Table table, string text, string definition) { using (TableRow row = new TableRow()) { row.TableSection = TableRowSection.TableBody; using (TableCell definitionCell = new TableCell()) { definitionCell.Text = text; row.Cells.Add(definitionCell); } using (TableCell controlCell = new TableCell()) { controlCell.Text = definition; row.Cells.Add(controlCell); } table.Rows.Add(row); } } private void CreateAccountOverviewHeader(Control container) { using (HtmlGenericControl header = new HtmlGenericControl("h2")) { this.headerLiteral = new Literal(); header.Controls.Add(this.headerLiteral); container.Controls.Add(header); } using (HtmlGenericControl description = new HtmlGenericControl("div")) { description.Attributes.Add("class", "description"); this.descriptionLiteral = new Literal(); description.Controls.Add(this.descriptionLiteral); container.Controls.Add(description); } } private void CreateAccountOverviewPanel(HtmlGenericControl container) { container.Controls.Clear(); this.CreateAccountOverviewHeader(container); this.CreateAccountOverviewTable(container); } private void CreateAccountOverviewTable(Control container) { using (Table table = new Table()) { table.ID = "AccountOverViewGrid"; table.CssClass = "ui definition table"; this.CreateTableHeader(table); this.CreateTableBody(table); container.Controls.Add(table); } } private void CreateTableBody(Table table) { if (this.accountNumberInputText == null) { return; } string accountNumber = this.accountNumberInputText.Value; AccountView view = Data.Reports.AccountStatement.GetAccountOverview(AppUsers.GetCurrentUserDB(), accountNumber); if (view == null) { return; } this.headerLiteral.Text = view.Account; this.AddBodyRow(table, Titles.AccountNumber, view.AccountNumber); this.AddBodyRow(table, Titles.ExternalCode, view.ExternalCode); this.AddBodyRow(table, Titles.BaseCurrency, view.CurrencyCode); this.AddBodyRow(table, Titles.AccountMaster, view.AccountMasterCode); this.AddBodyRow(table, Titles.Confidential, Conversion.TryCastString(view.Confidential)); this.AddBodyRow(table, Titles.IsSystemAccount, Conversion.TryCastString(view.SysType)); this.AddBodyRow(table, Titles.NormallyDebit, Conversion.TryCastString(view.NormallyDebit)); this.AddBodyRow(table, Titles.ParentAccount, view.ParentAccountNumber); } private void CreateTableHeader(Table table) { using (TableRow header = new TableRow()) { header.TableSection = TableRowSection.TableHeader; using (TableHeaderCell emptyCell = new TableHeaderCell()) { header.Cells.Add(emptyCell); } using (TableHeaderCell definitionCell = new TableHeaderCell()) { definitionCell.Text = Titles.Definition; header.Cells.Add(definitionCell); } table.Rows.Add(header); } } #endregion Account Overview Panel #region Form private void AddAccountNumberInputText(HtmlGenericControl container) { using (HtmlGenericControl field = HtmlControlHelper.GetField()) { using ( HtmlGenericControl label = HtmlControlHelper.GetLabel(Titles.AccountNumber, "AccountNumberInputText") ) { field.Controls.Add(label); } this.accountNumberInputText = new HtmlInputText(); this.accountNumberInputText.ID = "AccountNumberInputText"; field.Controls.Add(this.accountNumberInputText); container.Controls.Add(field); } } private void AddAccountNumberSelect(HtmlGenericControl container) { using (HtmlGenericControl field = HtmlControlHelper.GetField("four wide field")) { using (HtmlGenericControl label = HtmlControlHelper.GetLabel(Titles.Select, "AccountNumberSelect")) { field.Controls.Add(label); } this.accountNumberSelect = new HtmlSelect(); this.accountNumberSelect.ID = "AccountNumberSelect"; field.Controls.Add(this.accountNumberSelect); container.Controls.Add(field); } } private void AddFromDateTextBox(HtmlGenericControl container) { this.fromDateTextBox = new DateTextBox(); this.fromDateTextBox.ID = "FromDateTextBox"; this.fromDateTextBox.Mode = FrequencyType.FiscalYearStartDate; this.fromDateTextBox.Catalog = AppUsers.GetCurrentUserDB(); this.fromDateTextBox.OfficeId = AppUsers.GetCurrent().View.OfficeId.ToInt(); using (HtmlGenericControl field = this.GetDateField(Titles.From, this.fromDateTextBox)) { container.Controls.Add(field); } } private void AddShowButton(HtmlGenericControl container) { using (HtmlGenericControl field = HtmlControlHelper.GetField()) { using (HtmlGenericControl label = HtmlControlHelper.GetLabel(Titles.Prepare, "ShowButton")) { field.Controls.Add(label); } this.showButton = new Button(); this.showButton.ID = "ShowButton"; this.showButton.Attributes.Add("class", "ui positive button"); this.showButton.Text = Titles.Show; this.showButton.Click += this.ShowButton_Click; field.Controls.Add(this.showButton); container.Controls.Add(field); } } private void AddToDateTextBox(HtmlGenericControl container) { this.toDateTextBox = new DateTextBox(); this.toDateTextBox.ID = "ToDateTextBox"; this.toDateTextBox.Mode = FrequencyType.FiscalYearEndDate; this.toDateTextBox.Catalog = AppUsers.GetCurrentUserDB(); this.toDateTextBox.OfficeId = AppUsers.GetCurrent().View.OfficeId.ToInt(); using (HtmlGenericControl field = this.GetDateField(Titles.To, this.toDateTextBox)) { container.Controls.Add(field); } } private void BindGridView() { DateTime from = Conversion.TryCastDate(this.fromDateTextBox.Text); DateTime to = Conversion.TryCastDate(this.toDateTextBox.Text); int userId = AppUsers.GetCurrent().View.UserId.ToInt(); string accountNumber = this.accountNumberInputText.Value; int officeId = AppUsers.GetCurrent().View.OfficeId.ToInt(); this.statementGridView.DataSource = Data.Reports.AccountStatement.GetAccountStatement(AppUsers.GetCurrentUserDB(), from, to, userId, accountNumber, officeId); this.statementGridView.DataBound += this.StatementGridViewDataBound; this.statementGridView.DataBind(); } private void CreateFormPanel(HtmlGenericControl container) { using (HtmlGenericControl fields = new HtmlGenericControl("div")) { fields.Attributes.Add("class", "fields"); this.AddAccountNumberInputText(fields); this.AddAccountNumberSelect(fields); this.AddFromDateTextBox(fields); this.AddToDateTextBox(fields); this.AddShowButton(fields); container.Controls.Add(fields); } } private HtmlGenericControl GetDateField(string labelText, DateTextBox dateTextBox) { using (HtmlGenericControl field = HtmlControlHelper.GetField()) { using (HtmlGenericControl label = HtmlControlHelper.GetLabel(labelText, dateTextBox.ID)) { field.Controls.Add(label); } using (HtmlGenericControl iconInput = new HtmlGenericControl("div")) { iconInput.Attributes.Add("class", "ui icon input"); iconInput.Controls.Add(dateTextBox); using (HtmlGenericControl icon = new HtmlGenericControl("i")) { icon.Attributes.Add("class", "icon calendar pointer"); icon.Attributes.Add("onclick", string.Format(CultureInfo.InvariantCulture, "$('#{0}').datepicker('show');", dateTextBox.ID)); } field.Controls.Add(iconInput); } return field; } } private void ShowButton_Click(object sender, EventArgs e) { this.BindGridView(); this.CreateAccountOverviewPanel(this.accountOverviewTab); } private void StatementGridViewDataBound(object sender, EventArgs eventArgs) { using (GridView grid = sender as GridView) { if (grid != null && grid.HeaderRow != null) { grid.HeaderRow.TableSection = TableRowSection.TableHeader; } } } #endregion Form #region GridPanel #region Template Fields private void AddTemplateFields() { TemplateField actionTemplateField = new TemplateField(); actionTemplateField.HeaderText = string.Empty; actionTemplateField.ItemTemplate = new ActionTemplate(); this.statementGridView.Columns.Add(actionTemplateField); TemplateField checkBoxTemplateField = new TemplateField(); checkBoxTemplateField.HeaderText = Titles.Select; checkBoxTemplateField.ItemTemplate = new GridViewHelper.GridViewSelectTemplate(); this.statementGridView.Columns.Add(checkBoxTemplateField); } internal class ActionTemplate : ITemplate { public void InstantiateIn(Control container) { using (HtmlGenericControl previewIcon = new HtmlGenericControl("i")) { previewIcon.Attributes.Add("class", "icon print"); previewIcon.Attributes.Add("onclick", "showPreview(this);"); container.Controls.Add(previewIcon); } } } #endregion Template Fields private void CreateColumns() { this.AddTemplateFields(); GridViewHelper.AddDataBoundControl(this.statementGridView, "TranCode", Titles.TranCode); GridViewHelper.AddDataBoundControl(this.statementGridView, "ValueDate", Titles.ValueDate, "{0:d}"); GridViewHelper.AddDataBoundControl(this.statementGridView, "BookDate", Titles.BookDate, "{0:d}"); GridViewHelper.AddDataBoundControl(this.statementGridView, "Debit", Titles.Debit, "{0:N}", true); GridViewHelper.AddDataBoundControl(this.statementGridView, "Credit", Titles.Credit, "{0:N}", true); GridViewHelper.AddDataBoundControl(this.statementGridView, "Balance", Titles.Balance, "{0:N}", true); GridViewHelper.AddDataBoundControl(this.statementGridView, "StatementReference", Titles.StatementReference); GridViewHelper.AddDataBoundControl(this.statementGridView, "Office", Titles.Office); GridViewHelper.AddDataBoundControl(this.statementGridView, "Book", Titles.Book); GridViewHelper.AddDataBoundControl(this.statementGridView, "AccountNumber", Titles.AccountNumber); GridViewHelper.AddDataBoundControl(this.statementGridView, "Account", Titles.Account); GridViewHelper.AddDataBoundControl(this.statementGridView, "FlagBg", string.Empty); GridViewHelper.AddDataBoundControl(this.statementGridView, "FlagFg", string.Empty); } private void CreateGridPanel(HtmlGenericControl container) { using (HtmlGenericControl autoOverflowPanel = new HtmlGenericControl("div")) { autoOverflowPanel.Attributes.Add("class", "auto-overflow-panel"); this.CreateGridView(autoOverflowPanel); container.Controls.Add(autoOverflowPanel); } } private void CreateGridView(HtmlGenericControl container) { this.statementGridView = new GridView(); this.statementGridView.ID = "StatementGridView"; this.statementGridView.CssClass = "ui celled table nowrap"; this.statementGridView.GridLines = GridLines.None; this.statementGridView.BorderStyle = BorderStyle.None; this.statementGridView.AutoGenerateColumns = false; this.CreateColumns(); container.Controls.Add(this.statementGridView); } #endregion GridPanel #region Top Panel private void AddReconcileButton(HtmlGenericControl container) { using (HtmlButton flagButton = new HtmlButton()) { flagButton.ID = "ReconcileButton"; flagButton.Attributes.Add("class", "ui button"); flagButton.Attributes.Add("onclick", "return showReconcileWindow();"); flagButton.InnerHtml = "<i class='circle notched icon'></i>" + Titles.Reconcile; container.Controls.Add(flagButton); } } private void AddFlagButton(HtmlGenericControl container) { using (HtmlButton flagButton = new HtmlButton()) { flagButton.ID = "FlagButton"; flagButton.Attributes.Add("class", "ui button"); flagButton.Attributes.Add("onclick", "return false;"); flagButton.InnerHtml = "<i class='icon flag'></i>" + Titles.Flag; container.Controls.Add(flagButton); } } private void AddHiddenFields(HtmlGenericControl container) { this.selectedValuesHidden = new HiddenField(); this.selectedValuesHidden.ID = "SelectedValuesHidden"; container.Controls.Add(this.selectedValuesHidden); } private void AddNewButton(HtmlGenericControl container) { using (HtmlButton newButton = new HtmlButton()) { newButton.ID = "AddNewButton"; newButton.Attributes.Add("class", "ui button"); newButton.Attributes.Add("onclick", "window.location='/Modules/Finance/Entry/JournalVoucher.mix';return false;"); newButton.InnerHtml = "<i class='icon plus'></i>" + Titles.NewJournalEntry; container.Controls.Add(newButton); } } private void AddPrintButton(HtmlGenericControl container) { using (HtmlButton printButton = new HtmlButton()) { printButton.ID = "PrintButton"; printButton.Attributes.Add("class", "ui button"); printButton.Attributes.Add("onclick", "return false;"); printButton.InnerHtml = "<i class='icon print'></i>" + Titles.Print; container.Controls.Add(printButton); } } private void CreateTopPanel(Control container) { using (HtmlGenericControl buttons = new HtmlGenericControl("div")) { buttons.Attributes.Add("class", "ui icon buttons bpad16"); this.AddNewButton(buttons); this.AddFlagButton(buttons); this.AddReconcileButton(buttons); this.AddPrintButton(buttons); this.AddHiddenFields(buttons); container.Controls.Add(buttons); } } #endregion Top Panel #region Reconcile Modal private void CreateReconcileModal(Control container) { using (HtmlGenericControl modal = HtmlControlHelper.GetModal("ui small modal", "ReconcileModal")) { using (HtmlGenericControl closeIcon = HtmlControlHelper.GetIcon("close icon")) { modal.Controls.Add(closeIcon); } using ( HtmlGenericControl header = HtmlControlHelper.GetModalHeader(Titles.Reconcile, "circle notched icon") ) { modal.Controls.Add(header); } this.CreateModalContent(modal); container.Controls.Add(modal); } } private void CreateModalContent(HtmlGenericControl container) { using (HtmlGenericControl content = new HtmlGenericControl("div")) { content.Attributes.Add("class", "content"); this.CreateModalForm(content); container.Controls.Add(content); } } private void CreateModalForm(HtmlGenericControl container) { using (HtmlGenericControl form = HtmlControlHelper.GetForm()) { this.CreateModalFormFields(form); this.CreateModalButtons(form); container.Controls.Add(form); } } private void CreateModalButtons(HtmlGenericControl container) { this.CreateButton(container, Titles.OK, "ui green button", "reconcile();"); this.CreateButton(container, Titles.Close, "ui red button", "$(\"#ReconcileModal\").modal(\"hide\");"); } private void CreateButton(HtmlGenericControl container, string text, string cssClass, string onclick) { using (HtmlInputButton button = new HtmlInputButton()) { button.Value = text; button.Attributes.Add("class", cssClass); button.Attributes.Add("onclick", onclick); container.Controls.Add(button); } } private void CreateModalFormFields(HtmlGenericControl container) { using (HtmlGenericControl twoFields = HtmlControlHelper.GetFields("two fields")) { this.CreateTranCodeField(twoFields); this.CreateCurrentBookDateField(twoFields); container.Controls.Add(twoFields); } using (HtmlGenericControl field = HtmlControlHelper.GetField()) { using (HtmlGenericControl label = HtmlControlHelper.GetLabel(Titles.NewBookDate)) { field.Controls.Add(label); } using (HtmlGenericControl threeFields = HtmlControlHelper.GetFields("three fields")) { this.CreateYearField(threeFields); this.CreateMonthField(threeFields); this.CreateDayField(threeFields); field.Controls.Add(threeFields); } container.Controls.Add(field); } } private void CreateTranCodeField(HtmlGenericControl container) { this.CreateField(container, Titles.TranCode, "TranCodeInputText"); } private void CreateCurrentBookDateField(HtmlGenericControl container) { this.CreateField(container, Titles.CurrentBookDate, "CurrentBookDateInputText"); } private void CreateYearField(HtmlGenericControl container) { this.CreateInlineField(container, "YearInputText", Titles.Year, "integer"); } private void CreateMonthField(HtmlGenericControl container) { this.CreateInlineField(container, "MonthInputText", Titles.Month, "integer"); } private void CreateDayField(HtmlGenericControl container) { this.CreateInlineField(container, "DayInputText", Titles.Day, "integer"); } private void CreateInlineField(HtmlGenericControl container, string id, string placeHolder, string cssClass) { using (HtmlGenericControl field = HtmlControlHelper.GetField()) { using (HtmlInputText inputText = new HtmlInputText()) { inputText.ID = id; inputText.Attributes.Add("placeholder", placeHolder); inputText.Attributes.Add("class", cssClass); field.Controls.Add(inputText); } container.Controls.Add(field); } } private void CreateField(HtmlGenericControl container, string label, string id) { using (HtmlGenericControl field = HtmlControlHelper.GetField()) { using (HtmlGenericControl fieldLabel = HtmlControlHelper.GetLabel(label, id)) { field.Controls.Add(fieldLabel); } using (HtmlInputText inputText = new HtmlInputText()) { inputText.ID = id; inputText.Disabled = true; field.Controls.Add(inputText); } container.Controls.Add(field); } } #endregion } }
flukehan/MixERP
src/FrontEnd/MixERP.Net.FrontEnd/Modules/Finance/Reports/AccountStatement.ascx.cs
C#
gpl-3.0
32,439
#pragma once #include "sqltablemodel.h" #include <QTimer> #include <QWidget> namespace Ui { class WidgetFinanceiroCompra; } class WidgetFinanceiroCompra final : public QWidget { Q_OBJECT public: explicit WidgetFinanceiroCompra(QWidget *parent); ~WidgetFinanceiroCompra(); auto resetTables() -> void; auto updateTables() -> void; private: // attributes bool isSet = false; SqlTableModel model; Ui::WidgetFinanceiroCompra *ui; // methods auto montaFiltro() -> void; auto on_lineEditBusca_textChanged() -> void; auto on_table_activated(const QModelIndex &index) -> void; auto setConnections() -> void; auto setupTables() -> void; };
darktorres/ERP-STACCATO
src/widgetfinanceirocompra.h
C
gpl-3.0
667
<?php /** * Date Option Class * * @author Ardalan Naghshineh (www.ardalan.me) * @package Titan Framework Core **/ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * Date Option Class * * @since 1.0 **/ class TitanFrameworkOptionDate extends TitanFrameworkOption { public static $default_jquery_date_format = 'yy-mm-dd'; public static $default_date_format = 'Y-m-d'; public static $default_date_placeholder = 'YYYY-MM-DD'; public static $default_time_format = 'H:i'; public static $default_time_placeholder = 'HH:MM'; // Default settings specific to this option public $defaultSecondarySettings = array( 'date' => true, 'time' => false, 'column_link' => false, 'autocomplete' => false, ); private static $date_epoch; private static $time_epoch; /** * Constructor * * @since 1.4 */ function __construct( $settings, $owner ) { parent::__construct( $settings, $owner ); tf_add_action_once( 'admin_enqueue_scripts', array( $this, 'enqueueDatepicker' ) ); tf_add_action_once( 'customize_controls_enqueue_scripts', array( $this, 'enqueueDatepicker' ) ); add_action( 'admin_head', array( __CLASS__, 'createCalendarScript' ) ); if ( empty( self::$date_epoch ) ) { self::$date_epoch = date( self::$default_date_format, 0 ); } if ( empty( self::$time_epoch ) ) { self::$time_epoch = date( self::$default_time_format, 0 ); } } public function getSQLOrderBy( $order, $type ) { global $wpdb; return ( 'user' == $type ? 'ORDER BY' : '' ) . ' CAST(amp_pm.meta_value as SIGNED) ' . ( strpos( $order, ' DESC' ) === false ? 'ASC' : 'DESC' ) . ", $wpdb->posts.post_title ASC"; } public function getSamplesForCSV( $arg = null ) { $fmt = self::$default_date_format . ' ' . self::$default_time_format; if ( $this->settings['time'] && ! $this->settings['date'] ) { $fmt = self::$default_time_format; } else if ( ! $this->settings['time'] && $this->settings['date'] ) { $fmt = self::$default_date_format; } return array( date_i18n( $fmt, time() ), ); } /** * Cleans up the serialized value before saving * * @param string $value The serialized value * * @return string The cleaned value * @since 1.4 */ public function cleanValueForSaving( $value ) { if ( $value == '' ) { return 0; } if ( ! $this->settings['date'] && $this->settings['time'] ) { self::$date_epoch = date( self::$default_date_format, 0 ); $value = self::$date_epoch . ' ' . $value; } if ( $this->settings['date'] && ! $this->settings['time'] ) { self::$time_epoch = date( self::$default_time_format, 0 ); $value = $value . ' ' . self::$time_epoch; } $dateTimeParsed = DateTime::createFromFormat( self::$default_date_format . ' ' . self::$default_time_format, $value ); if ( ! $dateTimeParsed ) { return 0; } return $dateTimeParsed->getTimestamp(); } /** * Cleans the value for getOption * * @param string $value The raw value of the option * * @return mixes The cleaned value * @since 1.4 */ public function cleanValueForGetting( $value ) { if ( $value == 0 ) { return ''; } return $value; } /** * Enqueues the jQuery UI scripts * * @return void * @since 1.4 */ public function enqueueDatepicker() { wp_enqueue_script( 'jquery-ui-core' ); wp_enqueue_script( 'jquery-ui-slider' ); wp_enqueue_script( 'jquery-ui-datepicker' ); wp_enqueue_script( 'tf-jquery-ui-timepicker-addon', TitanFramework::getURL( '../js/min/jquery-ui-timepicker-addon-min.js', __FILE__ ), array( 'jquery-ui-datepicker', 'jquery-ui-slider' ) ); } /** * Prints out the script the initializes the jQuery Datepicker * * @return void * @since 1.4 */ public static function createCalendarScript() { ?> <script> jQuery(document).ready(function ($) { "use strict"; jQuery.validator.addMethod("date", function (value, element) { // parseDate throws exception if the value is invalid try { jQuery.datepicker.parseDate('<?php echo self::$default_jquery_date_format ?>', value); return true; } catch (e) { return false; } }, "<?php echo esc_js( __( 'Merci de saisir une date valide', 'amapress' ) ); ?>" ); var datepickerSettings = { dateFormat: '<?php echo self::$default_jquery_date_format ?>', showMillisec: false, showSecond: false, showMicrosec: false, showTimezone: false, currentText: '<?php echo esc_js( __( 'Maintenant', 'amapress' ) ); ?>', closeText: 'OK', timeOnlyTitle: '<?php echo esc_js( __( 'Choisir une heure', 'amapress' ) ); ?>', timeText: '<?php echo esc_js( __( 'Temps', 'amapress' ) ); ?>', hourText: '<?php echo esc_js( __( 'Heure', 'amapress' ) ); ?>', minuteText: '<?php echo esc_js( __( 'Minute', 'amapress' ) ); ?>', beforeShow: function (input, inst) { $('#ui-datepicker-div').addClass('tf-date-datepicker'); // Fix the button styles setTimeout(function () { jQuery('#ui-datepicker-div') .find('[type=button]').addClass('button').end() .find('.ui-datepicker-close[type=button]').addClass('button-primary'); }, 0); }, // Fix the button styles onChangeMonthYear: function () { setTimeout(function () { jQuery('#ui-datepicker-div') .find('[type=button]').addClass('button').end() .find('.ui-datepicker-close[type=button]').addClass('button-primary'); }, 0); } }; $('.tf-date input[type=text]').each(function () { var $this = $(this); if ($this.hasClass('date') && !$this.hasClass('time')) { $this.datepicker(datepickerSettings); } else if (!$this.hasClass('date') && $this.hasClass('time')) { $this.timepicker(datepickerSettings); } else { $this.datetimepicker(datepickerSettings); } }); }); </script> <?php } /** * Displays the option for admin pages and meta boxes * * @return void * @since 1.0 */ public function display() { $this->echoOptionHeader(); $dateFormat = self::$default_date_format . ' ' . self::$default_time_format; $placeholder = self::$default_date_placeholder . ' ' . self::$default_time_placeholder; if ( $this->settings['date'] && ! $this->settings['time'] ) { $dateFormat = self::$default_date_format; $placeholder = self::$default_date_placeholder; } else if ( ! $this->settings['date'] && $this->settings['time'] ) { $dateFormat = self::$default_time_format; $placeholder = self::$default_time_placeholder; } printf( '<input class="input-date%s%s %s" name="%s" placeholder="%s" id="%s" type="text" value="%s" autocomplete="%s" /> <p class="description">%s</p>', ( $this->settings['date'] ? ' date dpDate' : '' ), ( $this->settings['time'] ? ' time' : '' ), $this->settings['required'] ? 'required' : '', $this->getInputName(), $placeholder, $this->getID(), esc_attr( ( $this->getValue() > 0 ) ? date( $dateFormat, $this->getValue() ) : '' ), isset( $this->settings['autocomplete'] ) && $this->settings['autocomplete'] ? 'on' : 'off', $this->getDesc() ); $this->echoOptionFooter( false ); } protected function wrapColumnLink( $display_html, $post_id ) { $column_link = $this->settings['column_link']; $href = null; if ( is_callable( $column_link, false ) ) { $href = call_user_func( $column_link, $this, $post_id ); } if ( ! empty( $href ) ) { return "<a class='option-link' href='$href' target='_blank'>$display_html</a>"; } else { return $display_html; } } public function columnDisplayValue( $post_id ) { $dateFormat = self::$default_date_format . ' ' . self::$default_time_format; if ( $this->settings['date'] && ! $this->settings['time'] ) { $dateFormat = self::$default_date_format; } else if ( ! $this->settings['date'] && $this->settings['time'] ) { $dateFormat = self::$default_time_format; } $date = intval( $this->getValue( $post_id ) ); echo $this->wrapColumnLink( sprintf( __( '<span class="input-date%s%s">%s</span>', 'amapress' ), ( $this->settings['date'] ? ' date' : '' ), ( $this->settings['time'] ? ' time' : '' ), ( $date > 0 ) ? date_i18n( $dateFormat, $date ) : '' ), $post_id ); } public function columnExportValue( $post_id ) { echo ( $this->getValue( $post_id ) > 0 ) ? $this->getValue( $post_id ) : ''; } /** * Registers the theme customizer control, for displaying the option * * @param WP_Customize $wp_enqueue_script The customize object * @param TitanFrameworkCustomizerSection $section The section where this option will be placed * @param int $priority The order of this control in the section * * @return void * @since 1.7 */ public function registerCustomizerControl( $wp_customize, $section, $priority = 1 ) { $wp_customize->add_control( new TitanFrameworkOptionDateControl( $wp_customize, $this->getID(), array( 'label' => $this->settings['name'], 'section' => $section->settings['id'], 'settings' => $this->getID(), 'description' => $this->settings['desc'], 'priority' => $priority, 'required' => $this->settings['required'], 'date' => $this->settings['date'], 'time' => $this->settings['time'], ) ) ); } } /* * We create a new control for the theme customizer */ add_action( 'customize_register', 'registerTitanFrameworkOptionDateControl', 1 ); /** * Creates the option for the theme customizer * * @return void * @since 1.3 */ function registerTitanFrameworkOptionDateControl() { class TitanFrameworkOptionDateControl extends WP_Customize_Control { public $description; public $date; public $time; public $required; public function render_content() { TitanFrameworkOptionDate::createCalendarScript(); $dateFormat = self::$default_date_format . ' ' . self::$default_time_format; $placeholder = self::$default_date_placeholder . ' ' . self::$default_time_placeholder; if ( $this->date && ! $this->time ) { $dateFormat = self::$default_date_format; $placeholder = self::$default_date_placeholder; } else if ( ! $this->date && $this->time ) { $dateFormat = self::$default_time_format; $placeholder = self::$default_time_placeholder; } $class = $this->date ? ' date' : ''; $class .= $this->time ? ' time' : '' ?> <label class='tf-date'> <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span> <input class="input-date<?php echo $class ?> <?php echo( $this->required ? 'required' : '' ) ?>" <?php $this->link(); ?> placeholder="<?php echo $placeholder ?>" type="text" value="<?php echo $this->value() ?>"/> <?php if ( ! empty( $this->description ) ) { echo "<p class='description'>{$this->description}</p>"; } ?> </label> <?php } } }
comptoirdesappli/amapress
titan-framework/lib/class-option-date.php
PHP
gpl-3.0
11,956
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <TITLE> XWPFSDTCell (POI API Documentation) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="XWPFSDTCell (POI API Documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/XWPFSDTCell.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/poi/xwpf/usermodel/XWPFSDT.html" title="class in org.apache.poi.xwpf.usermodel"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/poi/xwpf/usermodel/XWPFSDTContent.html" title="class in org.apache.poi.xwpf.usermodel"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/poi/xwpf/usermodel/XWPFSDTCell.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="XWPFSDTCell.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.apache.poi.xwpf.usermodel</FONT> <BR> Class XWPFSDTCell</H2> <PRE> java.lang.Object <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html" title="class in org.apache.poi.xwpf.usermodel">org.apache.poi.xwpf.usermodel.AbstractXWPFSDT</A> <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.poi.xwpf.usermodel.XWPFSDTCell</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../../../org/apache/poi/xwpf/usermodel/ICell.html" title="interface in org.apache.poi.xwpf.usermodel">ICell</A>, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/ISDTContents.html" title="interface in org.apache.poi.xwpf.usermodel">ISDTContents</A></DD> </DL> <HR> <DL> <DT><PRE>public class <B>XWPFSDTCell</B><DT>extends <A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html" title="class in org.apache.poi.xwpf.usermodel">AbstractXWPFSDT</A><DT>implements <A HREF="../../../../../org/apache/poi/xwpf/usermodel/ICell.html" title="interface in org.apache.poi.xwpf.usermodel">ICell</A></DL> </PRE> <P> Experimental class to offer rudimentary read-only processing of of StructuredDocumentTags/ContentControl that can appear in a table row as if a table cell. <p/> These can contain one or more cells or other SDTs within them. <p/> WARNING - APIs expected to change rapidly <P> <P> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/apache/poi/xwpf/usermodel/XWPFSDTCell.html#XWPFSDTCell(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell, org.apache.poi.xwpf.usermodel.XWPFTableRow, org.apache.poi.xwpf.usermodel.IBody)">XWPFSDTCell</A></B>(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell&nbsp;sdtCell, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/XWPFTableRow.html" title="class in org.apache.poi.xwpf.usermodel">XWPFTableRow</A>&nbsp;xwpfTableRow, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/IBody.html" title="interface in org.apache.poi.xwpf.usermodel">IBody</A>&nbsp;part)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/apache/poi/xwpf/usermodel/ISDTContent.html" title="interface in org.apache.poi.xwpf.usermodel">ISDTContent</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/poi/xwpf/usermodel/XWPFSDTCell.html#getContent()">getContent</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.apache.poi.xwpf.usermodel.AbstractXWPFSDT"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class org.apache.poi.xwpf.usermodel.<A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html" title="class in org.apache.poi.xwpf.usermodel">AbstractXWPFSDT</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html#getBody()">getBody</A>, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html#getDocument()">getDocument</A>, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html#getElementType()">getElementType</A>, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html#getPart()">getPart</A>, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html#getPartType()">getPartType</A>, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html#getTag()">getTag</A>, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html#getTitle()">getTitle</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="XWPFSDTCell(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell, org.apache.poi.xwpf.usermodel.XWPFTableRow, org.apache.poi.xwpf.usermodel.IBody)"><!-- --></A><H3> XWPFSDTCell</H3> <PRE> public <B>XWPFSDTCell</B>(org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell&nbsp;sdtCell, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/XWPFTableRow.html" title="class in org.apache.poi.xwpf.usermodel">XWPFTableRow</A>&nbsp;xwpfTableRow, <A HREF="../../../../../org/apache/poi/xwpf/usermodel/IBody.html" title="interface in org.apache.poi.xwpf.usermodel">IBody</A>&nbsp;part)</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getContent()"><!-- --></A><H3> getContent</H3> <PRE> public <A HREF="../../../../../org/apache/poi/xwpf/usermodel/ISDTContent.html" title="interface in org.apache.poi.xwpf.usermodel">ISDTContent</A> <B>getContent</B>()</PRE> <DL> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html#getContent()">getContent</A></CODE> in class <CODE><A HREF="../../../../../org/apache/poi/xwpf/usermodel/AbstractXWPFSDT.html" title="class in org.apache.poi.xwpf.usermodel">AbstractXWPFSDT</A></CODE></DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>the content object</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/XWPFSDTCell.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/poi/xwpf/usermodel/XWPFSDT.html" title="class in org.apache.poi.xwpf.usermodel"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/poi/xwpf/usermodel/XWPFSDTContent.html" title="class in org.apache.poi.xwpf.usermodel"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/poi/xwpf/usermodel/XWPFSDTCell.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="XWPFSDTCell.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2016 The Apache Software Foundation or its licensors, as applicable.</i> </BODY> </HTML>
jmemmons/university-assignments
CSC 445 WebCentric Programming/Final Project/poi-3.14/docs/apidocs/org/apache/poi/xwpf/usermodel/XWPFSDTCell.html
HTML
gpl-3.0
14,028
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - CUTCLIFFE, Elizabeth</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> <link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../families.html" title="Families">Families</a></li> <li><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="IndividualDetail"> <h3>CUTCLIFFE, Elizabeth<sup><small></small></sup></h3> <div id="summaryarea"> <table class="infolist"> <tr> <td class="ColumnAttribute">Birth Name</td> <td class="ColumnValue"> CUTCLIFFE, Elizabeth <a href="#sref1a">1a</a> </td> </tr> <tr> <td class="ColumnAttribute">Gramps&nbsp;ID</td> <td class="ColumnValue">I2513</td> </tr> <tr> <td class="ColumnAttribute">Gender</td> <td class="ColumnValue">female</td> </tr> </table> </div> <div class="subsection" id="events"> <h4>Events</h4> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> <a href="../../../evt/e/7/d15f5fd944d78ffce061c428c7e.html" title="Christening"> Christening <span class="grampsid"> [E2707]</span> </a> </td> <td class="ColumnDate">1750-03-30</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </div> <div class="subsection" id="parents"> <h4>Parents</h4> <table class="infolist"> <thead> <tr> <th class="ColumnAttribute">Relation to main person</th> <th class="ColumnValue">Name</th> <th class="ColumnValue">Relation within this family (if not by birth)</th> </tr> </thead> <tbody> </tbody> <tr> <td class="ColumnAttribute">Father</td> <td class="ColumnValue"> <a href="../../../ppl/1/4/d15f5fc8eda567acff716ed7741.html">CUTCLIFFE, Francis<span class="grampsid"> [I1190]</span></a> </td> </tr> <tr> <td class="ColumnAttribute">Mother</td> <td class="ColumnValue"> <a href="../../../ppl/5/f/d15f5fc8f6250dbe0bd8a15def5.html">GOULD, Joan (Jane)<span class="grampsid"> [I1192]</span></a> </td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/d/d/d15f5fd94007c952c326a1259dd.html">CUTCLIFFE, Francis<span class="grampsid"> [I2512]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/8/f/d15f5fd943874d96088823a10f8.html">CUTCLIFFE, Elizabeth<span class="grampsid"> [I2513]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/e/5/d15f5fd94a44779eae09199225e.html">CUTCLIFFE, Jane<span class="grampsid"> [I2515]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/f/b/d15f5fd950c5dd3d3d70c58a1bf.html">CUTCLIFFE, Ann<span class="grampsid"> [I2516]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/5/3/d15f5fd953d72274ad0641c2c35.html">CUTCLIFFE, John<span class="grampsid"> [I2517]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/7/3/d15f5fd95822281b0fb567e7a37.html">CUTCLIFFE, Henery<span class="grampsid"> [I2518]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td colspan="3">&nbsp;</td> </tr> <tr> <td class="ColumnAttribute">Father</td> <td class="ColumnValue"> <a href="../../../ppl/1/4/d15f5fc8eda567acff716ed7741.html">CUTCLIFFE, Francis<span class="grampsid"> [I1190]</span></a> </td> </tr> <tr> <td class="ColumnAttribute">Stepmother</td> <td class="ColumnValue"> <a href="../../../ppl/d/5/d15f5fc8f827f210039d47a915d.html">BARROWS, Hannah<span class="grampsid"> [I1193]</span></a> </td> </tr> </table> </div> <div class="subsection" id="attributes"> <h4>Attributes</h4> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">EF154C9EDCA7574688891125FCDB9C763EFF</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </div> <div class="subsection" id="pedigree"> <h4>Pedigree</h4> <ol class="pedigreegen"> <li> <a href="../../../ppl/1/4/d15f5fc8eda567acff716ed7741.html">CUTCLIFFE, Francis<span class="grampsid"> [I1190]</span></a> <ol> <li class="spouse"> <a href="../../../ppl/5/f/d15f5fc8f6250dbe0bd8a15def5.html">GOULD, Joan (Jane)<span class="grampsid"> [I1192]</span></a> <ol> <li> <a href="../../../ppl/d/d/d15f5fd94007c952c326a1259dd.html">CUTCLIFFE, Francis<span class="grampsid"> [I2512]</span></a> </li> <li class="thisperson"> CUTCLIFFE, Elizabeth </li> <li> <a href="../../../ppl/e/5/d15f5fd94a44779eae09199225e.html">CUTCLIFFE, Jane<span class="grampsid"> [I2515]</span></a> </li> <li> <a href="../../../ppl/f/b/d15f5fd950c5dd3d3d70c58a1bf.html">CUTCLIFFE, Ann<span class="grampsid"> [I2516]</span></a> </li> <li> <a href="../../../ppl/7/3/d15f5fd95822281b0fb567e7a37.html">CUTCLIFFE, Henery<span class="grampsid"> [I2518]</span></a> </li> <li> <a href="../../../ppl/5/3/d15f5fd953d72274ad0641c2c35.html">CUTCLIFFE, John<span class="grampsid"> [I2517]</span></a> </li> </ol> </li> </ol> </li> </ol> </div> <div class="subsection" id="tree"> <h4>Ancestors</h4> <div id="treeContainer" style="width:735px; height:602px;"> <div class="boxbg female AncCol0" style="top: 269px; left: 6px;"> <a class="noThumb" href="../../../ppl/8/f/d15f5fd943874d96088823a10f8.html"> CUTCLIFFE, Elizabeth </a> </div> <div class="shadow" style="top: 274px; left: 10px;"></div> <div class="bvline" style="top: 301px; left: 165px; width: 15px"></div> <div class="gvline" style="top: 306px; left: 165px; width: 20px"></div> <div class="boxbg male AncCol1" style="top: 119px; left: 196px;"> <a class="noThumb" href="../../../ppl/1/4/d15f5fc8eda567acff716ed7741.html"> CUTCLIFFE, Francis </a> </div> <div class="shadow" style="top: 124px; left: 200px;"></div> <div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div> <div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div> <div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div> <div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div> <div class="bvline" style="top: 151px; left: 355px; width: 15px"></div> <div class="gvline" style="top: 156px; left: 355px; width: 20px"></div> <div class="boxbg male AncCol2" style="top: 44px; left: 386px;"> <a class="noThumb" href="../../../ppl/5/c/d15f5fc8e3d1ba398a87f1324c5.html"> CUTCLIFFE, Francis </a> </div> <div class="shadow" style="top: 49px; left: 390px;"></div> <div class="bvline" style="top: 76px; left: 370px; width: 15px;"></div> <div class="gvline" style="top: 81px; left: 375px; width: 20px;"></div> <div class="bhline" style="top: 76px; left: 370px; height: 75px;"></div> <div class="gvline" style="top: 81px; left: 375px; height: 75px;"></div> <div class="bvline" style="top: 76px; left: 545px; width: 15px"></div> <div class="gvline" style="top: 81px; left: 545px; width: 20px"></div> <div class="boxbg male AncCol3" style="top: 7px; left: 576px;"> <a class="noThumb" href="../../../ppl/e/c/d15f5fc8dd65886ce042fe85dce.html"> CUTCLIFFE, John </a> </div> <div class="shadow" style="top: 12px; left: 580px;"></div> <div class="bvline" style="top: 39px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 44px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 39px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 44px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol3" style="top: 81px; left: 576px;"> <a class="noThumb" href="../../../ppl/b/e/d15f5fd91c721ab514b973713eb.html"> KINGDOM, Joan </a> </div> <div class="shadow" style="top: 86px; left: 580px;"></div> <div class="bvline" style="top: 113px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 118px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 76px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 81px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol2" style="top: 194px; left: 386px;"> <a class="noThumb" href="../../../ppl/0/c/d15f5fc8e713f215e3282be3dc0.html"> BEAVANS, Anne </a> </div> <div class="shadow" style="top: 199px; left: 390px;"></div> <div class="bvline" style="top: 226px; left: 370px; width: 15px;"></div> <div class="gvline" style="top: 231px; left: 375px; width: 20px;"></div> <div class="bhline" style="top: 151px; left: 370px; height: 75px;"></div> <div class="gvline" style="top: 156px; left: 375px; height: 75px;"></div> <div class="boxbg female AncCol1" style="top: 419px; left: 196px;"> <a class="noThumb" href="../../../ppl/5/f/d15f5fc8f6250dbe0bd8a15def5.html"> GOULD, Joan (Jane) </a> </div> <div class="shadow" style="top: 424px; left: 200px;"></div> <div class="bvline" style="top: 451px; left: 180px; width: 15px;"></div> <div class="gvline" style="top: 456px; left: 185px; width: 20px;"></div> <div class="bhline" style="top: 301px; left: 180px; height: 150px;"></div> <div class="gvline" style="top: 306px; left: 185px; height: 150px;"></div> </div> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/5/0/d15f5fb6d26ad69bdfd4fe2605.html" title="Cutcliffe-Willis marriage, 4 Nov 1811, Combe Martin, Devon , England" name ="sref1"> Cutcliffe-Willis marriage, 4 Nov 1811, Combe Martin, Devon , England <span class="grampsid"> [S0202]</span> </a> <ol> <li id="sref1a"> <ul> <li> Page: No. 284 </li> <li> Confidence: Very High </li> <li> Source text: <div class="grampsstylednote"><p>&nbsp;</p><p>[Entry Recording Date : 4 NOV 1811]</p></div> </li> <li> General: <p></p> </li> </ul> </li> </ol> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:11<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
RossGammon/the-gammons.net
RossFamilyTree/ppl/8/f/d15f5fd943874d96088823a10f8.html
HTML
gpl-3.0
13,742
using CP77.CR2W.Reflection; namespace CP77.CR2W.Types { [REDMeta] public class gameMuppetInputActionCrouch : gameIMuppetInputAction { public gameMuppetInputActionCrouch(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/gameMuppetInputActionCrouch.cs
C#
gpl-3.0
257
// -*- C++ -*- // // This file is part of YODA -- Yet more Objects for Data Analysis // Copyright (C) 2008-2017 The YODA collaboration (see AUTHORS for details) // #ifndef YODA_Writer_h #define YODA_Writer_h #include "YODA/AnalysisObject.h" #include "YODA/Counter.h" #include "YODA/Histo1D.h" #include "YODA/Histo2D.h" #include "YODA/Profile1D.h" #include "YODA/Profile2D.h" #include "YODA/Scatter1D.h" #include "YODA/Scatter2D.h" #include "YODA/Scatter3D.h" #include "YODA/Utils/Traits.h" #include <type_traits> #include <fstream> #include <ostream> #include <string> namespace YODA { /// Pure virtual base class for various output writers. class Writer { public: /// Virtual destructor virtual ~Writer() {} /// @name Writing a single analysis object. //@{ /// Write out object @a ao to file @a filename. void write(const std::string& filename, const AnalysisObject& ao); /// Write out object @a ao to output stream @a stream. void write(std::ostream& stream, const AnalysisObject& ao) { // std::vector<const AnalysisObject*> vec{&ao}; std::vector<const AnalysisObject*> vec; vec.push_back(&ao); std::cout << std::endl; write(stream, vec); std::cout << std::endl; } /// Write out pointer-like object @a ao to output stream @a stream. template <typename T> typename std::enable_if<DerefableToAO<T>::value>::type //< -> void if valid write(std::ostream& stream, const T& ao) { write(stream, *ao); } /// Write out pointer-like object @a ao to file @a filename. template <typename T> typename std::enable_if<DerefableToAO<T>::value>::type //< -> void if valid write(const std::string& filename, const T& ao) { write(filename, *ao); } //@} /// @name Writing multiple analysis objects by collection. //@{ /// Write out a vector of AO pointers (untemplated=exact type-match) to the given stream /// /// @note This is the canonical function for implementing AO writing: all /// others call this. Hence the specific AOs type. /// /// @note Among other reasons, this is non-inline to hide zstr from the public API void write(std::ostream& stream, const std::vector<const AnalysisObject*>& aos); /// Write out a collection of objects @a objs to output stream @a stream. /// /// @note The enable_if call checks whether RANGE is const_iterable, if yes the return /// type is void. If not, this template will not be a candidate in the lookup template <typename RANGE> typename std::enable_if<CIterable<RANGE>::value>::type write(std::ostream& stream, const RANGE& aos) { write(stream, std::begin(aos), std::end(aos)); } /// Write out a collection of objects @a objs to file @a filename. template <typename RANGE> typename std::enable_if<CIterable<RANGE>::value>::type write(const std::string& filename, const RANGE& aos) { write(filename, std::begin(aos), std::end(aos)); } //@} /// @name Writing multiple analysis objects by iterator range. //@{ /// Write out the objects specified by start iterator @a begin and end /// iterator @a end to output stream @a stream. /// /// @todo Add SFINAE trait checking for AOITER = DerefableToAO template <typename AOITER> void write(std::ostream& stream, const AOITER& begin, const AOITER& end) { std::vector<const AnalysisObject*> vec; // vec.reserve(std::distance(begin, end)); for (AOITER ipao = begin; ipao != end; ++ipao) vec.push_back(&(**ipao)); write(stream, vec); } /// Write out the objects specified by start iterator @a begin and end /// iterator @a end to file @a filename. /// /// @todo Add SFINAE trait checking for AOITER = DerefableToAO template <typename AOITER> void write(const std::string& filename, const AOITER& begin, const AOITER& end) { std::vector<const AnalysisObject*> vec; // vec.reserve(std::distance(begin, end)); for (AOITER ipao = begin; ipao != end; ++ipao) vec.push_back(&(**ipao)); if (filename != "-") { try { const size_t lastdot = filename.find_last_of("."); std::string fmt = Utils::toLower(lastdot == std::string::npos ? filename : filename.substr(lastdot+1)); const bool compress = (fmt == "gz"); useCompression(compress); // std::ofstream stream; stream.exceptions(std::ofstream::failbit | std::ofstream::badbit); stream.open(filename.c_str()); write(stream, vec); } catch (std::ofstream::failure& e) { throw WriteError("Writing to filename " + filename + " failed: " + e.what()); } } else { try { write(std::cout, vec); } catch (std::runtime_error& e) { throw WriteError("Writing to stdout failed: " + std::string(e.what())); } } } //@} /// Set precision of numerical quantities in this writer's output. void setPrecision(int precision) { _precision = precision; } /// Use libz compression? void useCompression(bool compress=true) { _compress = compress; } protected: /// @name Main writer elements //@{ /// Write any opening boilerplate required by the format to @a stream virtual void writeHead(std::ostream&) {} /// @brief Write the body elements corresponding to AnalysisObject @a ao to @a stream virtual void writeBody(std::ostream& stream, const AnalysisObject* ao); /// @brief Write the body elements corresponding to AnalysisObject pointer @a ao to @a stream virtual void writeBody(std::ostream& stream, const AnalysisObject& ao); /// @brief Write the body elements corresponding to AnalysisObject @a ao to @a stream /// @note Requires that @a ao is dereferenceable to an AnalysisObject, via the DerefableToAO<T> trait, template <typename T> typename std::enable_if<DerefableToAO<T>::value>::type //< -> void if valid writeBody(std::ostream& stream, const T& ao) { writeBody(stream, *ao); } /// Write any closing boilerplate required by the format to @a stream virtual void writeFoot(std::ostream& stream) { stream << std::flush; } //@} /// @name Specific AO type writer implementations, to be implemented in derived classes //@{ virtual void writeCounter(std::ostream& stream, const Counter& c) = 0; virtual void writeHisto1D(std::ostream& os, const Histo1D& h) = 0; virtual void writeHisto2D(std::ostream& os, const Histo2D& h) = 0; virtual void writeProfile1D(std::ostream& os, const Profile1D& p) = 0; virtual void writeProfile2D(std::ostream& os, const Profile2D& p) = 0; virtual void writeScatter1D(std::ostream& os, const Scatter1D& s) = 0; virtual void writeScatter2D(std::ostream& os, const Scatter2D& s) = 0; virtual void writeScatter3D(std::ostream& os, const Scatter3D& s) = 0; //@} /// Output precision int _precision; /// Compress the output? bool _compress; }; /// Factory function to make a writer object by format name or a filename Writer& mkWriter(const std::string& format_name); } #endif
hep-mirrors/yoda
include/YODA/Writer.h
C
gpl-3.0
7,249
using System; using System.Collections.Generic; using System.Linq; using System.Web; using LearnEnglishWords.Models; using MediatR; namespace LearnEnglishWords.Commands { public class AddUserCommand : IRequest<bool> { public UserModel UserModel { get; set; } } }
greshniksv/LearnEnglishWords
LearnEnglishWords/LearnEnglishWords/Commands/AddUserCommand.cs
C#
gpl-3.0
286
<?php /* * Copyright (C) 2010 Richard Kakaš. * All rights reserved. * Contact: Richard Kakaš <richard.kakas@gmail.com> * * @LICENSE_START@ * This file is part of CFD project and it is licensed * under license that is described in CFD project's LICENSE file. * See LICENSE file for information about how you can use this file. * @LICENSE_END@ */ namespace cfd\core; require_once("Object.php"); require_once("CoreInfo.php"); require_once("ClassLoader.php"); /** * @brief Used as default loader for classes. * * This class implements \\cfd\\core\\ClassLoader functionality. * It also provide default global loader for classes. This loader * can be returned by getLoader() function. If you want change class * loading process please try to change getLoader() object before you * create your own \\cfd\\core\\ClassLoader functionality implementation. * * @see \\cfd\\core\\ClassLoader */ class DefaultClassLoader extends Object implements ClassLoader { private static $sLoader; private $mPaths = array(); private function includeClassFile($path, $className) { if($path == "") $path = "./"; $fileName = $path; if($fileName[strlen($fileName) - 1] != "/") { $fileName .= "/"; } $fileName .= $className . ".php"; if( file_exists($fileName) ) { include_once($fileName); return true; } return false; } /** * Create new ClassLoader object. * * @param object $parent Parent of new object. */ public function __construct(Object $parent = NULL) { parent::__construct($parent); } /** * Destructs ClassLoader object. */ public function __destruct() { parent::__destruct(); } /** * @brief Static constructor for class. * * This function is called right after class definition. * Its purpose is to initialize static variables (signals etc). * Never call this function by hand! */ public static function __static() { if( is_object(self::$sLoader) ) return; // firstly initializing static variables self::$sLoader = new DefaultClassLoader(); // initializing default global ClassLoader object self::$sLoader->addPath( "cfd\\core\\", CoreInfo::getCoreDirectoryPath() ); } /** * Adds path for specific namespace. * * @param string $namespaceStr Namespace name for which path will be used. * @param string $pathStr Path that will be looked up for class files. */ public function addPath($namespaceStr, $pathStr) { if( !array_key_exists($namespaceStr, $this->mPaths) ) { $this->mPaths[$namespaceStr] = array(); } array_push($this->mPaths[$namespaceStr], $pathStr); } /** * Removes path for specific namespace. * * @param string $namespaceStr Namespace name for which path will be removed. * @param string $pathStr Path to remove. */ public function removePath($namespaceStr, $pathStr) { if( array_key_exists($namespaceStr, $this->mPaths) ) { unset( $this->mPaths[$namespaceStr][array_search($pathStr, $this->mPaths[$namespaceStr])] ); if(count($this->mPaths[$namespaceStr]) == 0) { unset( $this->mPaths[$namespaceStr] ); } } } /** * Tries to load specific class using paths added by addPath() function. * * @param string $className Full qualified name of class (i.e. "\namespaceName\className"). * @param boolean &$succeed Reference that is used to indicate signal if function * succeed in doing its job or not => if not signal will call early connected function. */ public function loadClass($className, &$succeed) { if( ($pos = strrpos($className, "\\")) !== false ) { $namespaceName = substr($className, 0, $pos + 1); $className = substr($className, $pos + 1, strlen($className) - strlen($namespaceName)); if( array_key_exists($namespaceName, $this->mPaths) ) { $included = false; foreach($this->mPaths[$namespaceName] as &$value) { if( $this->includeClassFile($value, $className) ) { $included = true; break; } } if($included == false) { $succeed = false; } } } } /** * @brief Returns global class loader. * * @return Global loader for classes. If you want change global * loader behaviour always use this function to get loader object. */ public static function getLoader() { return self::$sLoader; } } DefaultClassLoader::__static();
w0301/CFD
core/DefaultClassLoader.php
PHP
gpl-3.0
4,836
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.parts; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.part.DefaultPartComponentManager; import net.sf.jasperreports.engine.part.PartComponentXmlWriter; /** * @author Teodor Danciu (teodord@users.sourceforge.net) * @version $Id: ComponentsManager.java 5877 2013-01-07 19:51:14Z teodord $ */ public class PartComponentsManager extends DefaultPartComponentManager { public PartComponentXmlWriter getComponentXmlWriter(JasperReportsContext jasperReportsContext) { return new PartComponentsXmlWriter(jasperReportsContext); } }
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/parts/PartComponentsManager.java
Java
gpl-3.0
1,596
/* * VarDriver3D.cpp * samurai * * Copyright 2008 Michael Bell. All rights reserved. * */ #include <iterator> #include <fstream> #include <cmath> #include <vector> #include <string> #include <regex> #include <set> #include <iomanip> // #include <netcdfcpp.h> #include <Ncxx/Nc3File.hh> #include "VarDriver3D.h" #include "Dorade.h" #include "RecursiveFilter.h" #include "samurai.h" #include "timers.h" #include "BkgdObsLoaders.h" #include "LineSplit.h" #include "FileList.h" #include "timing/gptl.h" // Constructor VarDriver3D::VarDriver3D() : VarDriver() { numVars = 7; numDerivatives = 4; bkgdAdapter = NULL; bgU = NULL; bgWeights = NULL; sigmaTable = NULL; } // Destructor VarDriver3D::~VarDriver3D() { } // Initialize with the configHash already filled bool VarDriver3D::initialize() { // Run a 3D vortex background field cout << "Initializing SAMURAI 3D" << endl; return validateDriver(); } // Initialize from parsed xml bool VarDriver3D::initialize(const XMLNode& configuration) { // Run a 3D vortex background field cout << "Initializing SAMURAI 3D" << endl; // Parse the XML configuration file if (!parseXMLconfig(configuration)) return false; return validateDriver(); } // Initialize from a passed structure bool VarDriver3D::initialize(const samurai_config &configSam) { // Run a 3D vortex background field cout << "Initializing SAMURAI 3D" << endl; // Parse the Samurai configuration structure passed from COAMPS if (! parseSamuraiConfig(configSam)) return false; return validateDriver(); } // Validate and finish initializing the driver bool VarDriver3D::validateDriver() { // Make sure the config has all the keys we need if ( ! validateConfig()) return false; // std::cout << "==== Content of configHash" << std::endl; // dump_hash(configHash); // Validate the run geometry if (configHash["mode"] == "XYZ") { runMode = XYZ; } else if (configHash["mode"] == "RTZ") { runMode = RTZ; } else { cout << "Unrecognized run mode " << configHash["mode"] << ", Aborting...\n"; return false; } bool fractlBkgd = ( configHash["bkgd_obs_interpolation"] == "fractl" ); bool loadBG = ( configHash["load_background"] == "true" ); // Warn is there are non-sensical combos of options. // Just 1 right now, so put it inlie if (fractlBkgd && ( configHash["adjust_background"] == "true")) std::cout << "** Warning: 'adjust_background' set to 'true' " << "with 'bkgd_obs_interpolation' set to 'fractl' doesn't make sense." << std::endl; if (fractlBkgd && ! loadBG) { std::cout << "** Warning: 'bkgd_obs_interpolation' set " << "but 'load_background' set to false. Setting load_background to true." << std::endl; loadBG = true; } // Set the projection (to be used by the cost functions) projection.setProjection(projectionFromConfig()); /* Set the data path */ // NOTE (NCAR): Originally we filtered these by 'files' and then sorted - this is doable with std::filesystem, but // that's not fully implemented in some compilers yet, so for the moment we're just assuming it's a directory dataPath = configHash["data_directory"]; if (!DirectoryExists(dataPath)) { std::cout << "Can't find data directory: " << configHash["data_directory"] << endl; return false; } /* Check to make sure the output path exists */ std::string outputPath(configHash["output_directory"]); if (!DirectoryExists(outputPath)) { std::cout << "Can't find output directory: " << configHash["output_directory"] << endl; return false; } // Centers and Met Observations are tightly coupled. // // So if we allow different centers between each runs, preProcessMetObs() or loadMetObs() // have to be called again. // // What else is dependent on the data structures created by readFrameCenters() and // the *MetObs() ? // // Are all the Met Obs still available, or only the ones that were matched to the center // time frames? // With coamps, grid dimensions come from the run arguments, not the fixed confid // So only do validation that depends on grid dimensions if fixedGrid is set. if (fractlBkgd) { // Grid comes from the fractl file if ( ! validateFractlGrid() ) return false; bkgdAdapter = new BkgdFractl(); return gridDependentInit(); } else if (fixedGrid) { // If runGrid, this will be done in the run(......) call if ( ! validateFixedGrid() ) return false; // Set the background Obs adapter to get data from a file (if config says so) if (loadBG) { bkgdAdapter = new BkgdStream((dataPath + "/samurai_Background.in").c_str()); // Not cross-platform with the '/', but that's fixable later, easily. } return gridDependentInit(); } // If we got here, then everything probably went OK! return true; } // This used to be in validateDriver. // All the grid dependent initialization is performed here. // Prerequisit: Grid dimensions have been set and verified. *** bool VarDriver3D::gridDependentInit() { START_TIMER(timei); // Define the Reference state std::string refSounding = configHash["ref_state"]; refstate = new ReferenceState(refSounding); // cout << "Reference profile: Z\t\tQv\tRhoa\tRho\tH\tTemp\tPressure\n"; for (real k = kmin; k < kmax + kincr; k += kincr) { // cout << " " << k << "\t"; for (int i = 0; i < 6; i++) { real var = refstate->getReferenceVariable(i, k * 1000); if (i == 0) var = refstate->bhypInvTransform(var); // cout << setw(9) << setprecision(4) << var << "\t"; } // cout << "\n"; } cout << setprecision(9); // Set the maximum number of iterations to the multipass reduction factor // Multiple outer loops will reduce the cutoff wavelengths and background error variance maxIter = std::stoi(configHash["num_iterations"]); // Read in the Frame centers (if runGrid, user is responsible for managing center // structure instead) // // Ideally, create a time-based spline from limited center fixes here // but just load 1 second centers into vector for now if ( fixedGrid) { readFrameCenters(); if ( ! findReferenceCenter() ) { cout << "Error finding reference time, please check date and time in XML file\n"; return false; } } // These are used to process the obs (bkg and met) uStateSize = 8 * (idim + 1) * (jdim + 1) * (kdim + 1) * (numVars); // bgU size bStateSize = (idim + 2) * (jdim + 2) * (kdim + 2) * numVars; // 2 mish points between nodes std::cout << "Physical (mish) State size = " << uStateSize << std::endl; std::cout << "Nodal State size = " << bStateSize << std::endl; std::cout << "Grid dimensions: (" << idim << ", " << jdim << ", " << kdim << ")" << std::endl; if (bgU != NULL) delete[] bgU; bgU = new real[uStateSize]; std::memset(bgU, 0, uStateSize * sizeof(real)); // needed, as data not necessarily initialized to 0 // Initialize this to zero. std::fill(bgU,bgU+uStateSize,0.0); //for (int i=0;i< uStateSize;i++) {bgU[i]=0.0;} // Optionally load a set of background coefficients directly std::string loadBGcoeffs = configHash["load_bg_coefficients"]; if (loadBGcoeffs == "true") if (! loadBackgroundCoeffs() ) return false; // Optionally load a set of background estimates and interpolate to the Gaussian mish int numbgObs = 0; if(bkgdAdapter != NULL) { START_TIMER(timeb); numbgObs = loadBackgroundObs(); PRINT_TIMER("loadBackgroundObs", timeb); if (numbgObs < 0) { cout << "Error loading background Obs\n"; return false; } //NCAR - cleanup from dangling bkgAdapter pointer, as it's not needed elsewhere: delete bkgdAdapter; } // Optionally adjust the interpolated background to satisfy mass continuity // and match the supplied points exactly. In essence, do a SAMURAI analysis using // the background estimates as "observations" std::string adjustBG = configHash["adjust_background"]; if ((adjustBG == "true") and numbgObs) { if ( ! adjustBackground()) { cout << "Error adjusting background\n"; return false; } } START_TIMER(timem); if ( ! loadMetObs() ) return false; PRINT_TIMER("loadMetObs", timem); START_TIMER(timec); initObCost3D(); PRINT_TIMER("initObCost3D", timec); PRINT_TIMER("gridDependentInit", timei); return true; } // Find the center that matches the ref_time bool VarDriver3D::findReferenceCenter() { // NOTE (NCAR) : I'm not sure whether we're JUST comparing times, or if dates matter? Seems not, but get clarification from CSU team datetime reftime = ParseTime(configHash["ref_time"].c_str(), "%H:%M:%S"); for (unsigned int fi = 0; fi < frameVector.size(); fi++) { datetime frametime = frameVector[fi].getTime(); if (Time(reftime) == Time(frametime)) { configHash.insert("ref_lat", std::to_string(frameVector[fi].getLat())); configHash.insert("ref_lon", std::to_string(frameVector[fi].getLon())); // Note - we can't insert, since it already exists.. so we're doing the awkward 'GetMap', then assigning // a new value directly. This can definitely be cleaner, but let's get it correct first, clean later. configHash.GetMap()->find("ref_time")->second = std::to_string(Date(frametime)); cout << "Found matching reference time " << PrintTime(reftime) << " at " << frameVector[fi].getLat() << ", " << frameVector[fi].getLon() << "\n"; return true; } } return false; } // // Initialize background observations and run // // While this was developed to interface with coamps, nothing prevents a caller to use this interface. bool VarDriver3D::run(int nx, int ny, int nsigma, // ----- new ----- char cdtg[10], // "12Z oct 4 2015 -> "2015100412" int delta, // delta * iter past cdtg int iter, float imin, float imax, float iincr, // used to come from config float jmin, float jmax, float jincr, // ----- new ----- float *sigmas, float *latitude, // 2D arrays float *longitude, float *u1, // 3D array (nx, ny, nsigma) float *v1, float *w1, float *th1, float *p1, // These are output values float *usam, // 3D array float *vsam, float *wsam, float *thsam, float *psam) { fillRunCenters(cdtg, delta, iter, *latitude, *longitude); if (! validateRunGrid(nx, ny, nsigma, imin, imax, iincr, jmin, jmax, jincr, sigmas) ) return false; // Clean up from previous run if needed if(bkgdAdapter != NULL) delete bkgdAdapter; // Set the background obs adapter to get data from the passed arrays if (configHash["array_order"] == "row-major") bkgdAdapter = new BkgdCArray(nx, ny, nsigma, cdtg, delta, iter, sigmas, latitude, longitude, u1, v1, w1, th1, p1); else bkgdAdapter = new BkgdFArray(nx, ny, nsigma, cdtg, delta, iter, sigmas, latitude, longitude, u1, v1, w1, th1, p1); if (! gridDependentInit() ) return false; if( run() ) return obCost3D->copyResults(nx, ny, nsigma, usam, vsam, wsam, thsam, psam); return false; } /* This routine drives the CostFunction minimization There is support for an outer loop to change the background error covariance or update non-linear observation operators */ bool VarDriver3D::run() { int iter = 1; while (iter <= maxIter) { if (iter < maxIter) { configHash.update("save_mish", "true"); } else { configHash.update("save_mish", "false"); } cout << "Outer Loop Iteration: " << iter << endl; START_TIMER(timei); obCost3D->initState(iter); PRINT_TIMER("Cost3D Init", timei); START_TIMER(timem); obCost3D->minimize(); PRINT_TIMER("Cost3D minimize", timem); START_TIMER(timeu); obCost3D->updateBG(); PRINT_TIMER("Cost3d update", timeu); iter++; // Optionally update the analysis parameters for an additional iteration updateAnalysisParams(iter); } return true; } /* Clean up all that allocated memory */ bool VarDriver3D::finalize() { obCost3D->finalize(); delete[] obs; delete[] bgU; delete obCost3D; delete refstate; return true; } /* Pre-process the observations into a single vector On the wishlist is some integrated QC here other than just spatial thresholding */ bool VarDriver3D::preProcessMetObs() { GPTLstart("VarDriver3D::preprocessMetObs"); vector<real> rhoP; // Convert the bg dBZ back to Z for further processing with real radar data if ((configHash["qr_variable"] == "dbz") and (configHash["load_background"] == "true") and (configHash["adjust_background"] == "false")) { for (int ki = -1; ki < (kdim); ki++) { for (int kmu = -1; kmu <= 1; kmu += 2) { for (int ii = -1; ii < (idim); ii++) { for (int imu = -1; imu <= 1; imu += 2) { for (int ji = -1; ji < (jdim); ji++) { for (int jmu = -1; jmu <= 1; jmu += 2) { int bgI = (ii+1)*2 + (imu+1)/2; int bgJ = (ji+1)*2 + (jmu+1)/2; int bgK = (ki+1)*2 + (kmu+1)/2; int bIndex = numVars*(idim+1)*2*(jdim+1)*2*bgK + numVars*(idim+1)*2*bgJ +numVars*bgI; real dBZ = bgU[bIndex +6] * 10. - 35.; real ZZ = pow(10.0,(dBZ*0.1)); bgU[bIndex +6] = ZZ; bgWeights[bIndex] = 1.0; } } } } } } } // Geographic functions //GeographicLib::TransverseMercatorExact tm = GeographicLib::TransverseMercatorExact::UTM(); real referenceLon = std::stof(configHash["ref_lon"]); // Find the zero C line using Newton's method real zeroClevel = 273.15; real height = 5000; real tmin = 1e34; int iter = 0; while ((fabs(tmin) > 0.1) and (iter < 5000)) { real t = refstate->getReferenceVariable(ReferenceVariable::tempref, height) - zeroClevel; real tprime = (refstate->getReferenceVariable(ReferenceVariable::tempref, height + 500.) - refstate->getReferenceVariable(ReferenceVariable::tempref, height - 500.)) / 1000.; if (tprime != 0) { height = height - t / tprime; tmin = t; } iter++; } zeroClevel = height; cout << "Found zero C level at " << zeroClevel << " based on reference sounding" << endl; // Load Met. Observations auto filenames = FileList(dataPath); int processedFiles = 0; int attemptedFiles = 0; std::vector<MetObs>* metData = new std::vector<MetObs>; cout << "Found " << filenames.size() << " data files to read..." << endl; int totalFiles = filenames.size(); for (std::size_t i = 0; i < filenames.size(); ++i) { metData->clear(); if (filenames[i].empty()) { cout << "Unknown file! " << filenames[i] << endl; continue; } std::string file = filenames[i]; std::vector<std::string> parts = LineSplit(file, '.'); std::string suffix = parts[parts.size()-1]; std::string prefix = parts[0]; if (prefix == "swp") { // Switch it to suffix suffix = "swp"; } if (suffix == "nc") { // cfrad file? if (std::regex_match(file, std::regex(".*cfrad.*\\.nc"))) suffix = "cfrad"; } cout << "Processing " << file << " of type " << suffix << endl; attemptedFiles++; // Read different types of files std::string fullpath = dataPath + "/" + file; if (! read_met_obs_file(dataSuffix[suffix], fullpath, metData)) continue; processedFiles++; int obsProblem = 0; int coordProblem = 0; int timeProblem = 0; int domainProblem = 0; int radiusProblem = 0; // Process the metObs into Observations if (frameVector.size() == 0) { std::cout << "No centerfile, cannot process Met. Obs." << std::endl; return false; } datetime startTime_ob = frameVector.front().getTime(); auto startTime = Date(startTime_ob); datetime endTime_ob = frameVector.back().getTime(); auto endTime = Date(endTime_ob); int prevobs = obVector.size(); for (std::size_t i = 0; i < metData->size(); ++i) { // Make sure the ob is within the time limits MetObs metOb = metData->at(i); datetime obTime_ob = metOb.getTime(); auto obTime = Date(obTime_ob); // NOTE: Changing below line to account for msec vs. sec differences (discussion with M Bell, ongoing) // This makes the DesRosier case similar for now, but may need to change later //if ((obTime < startTime) or (obTime > endTime)) { if ((obTime < startTime) or (obTime >= endTime)) { timeProblem++; if (timeProblem < 10) std::cout << "tcstart: " << PrintDate(startTime_ob) << ", tcend: " << PrintDate(endTime_ob) << ", obTime: " << PrintDate(obTime_ob) << std::endl; continue; } int fi = std::chrono::duration_cast<std::chrono::seconds>(obTime_ob - startTime_ob).count(); if ((fi < 0) or (fi > (int)frameVector.size())) { cout << "**Time problem with observation " << fi << ", " << startTime << ", " << obTime << endl; timeProblem++; continue; } real Um = frameVector[fi].getUmean(); real Vm = frameVector[fi].getVmean(); // Get the X, Y & Z real tcX, tcY, metX, metY; if ((metOb.getLat() == -999) or (metOb.getLat() == -999)) { coordProblem++; continue; } projection.Forward(referenceLon, frameVector[fi].getLat() , frameVector[fi].getLon() , tcX, tcY); projection.Forward(referenceLon, metOb.getLat() , metOb.getLon() , metX, metY); real obX = (metX - tcX) / 1000.; real obY = (metY - tcY) / 1000.; real heightm = metOb.getAltitude(); real obZ = heightm/1000.; real obRadius = sqrt(obX*obX + obY*obY); real obTheta = 180.0 * atan2(obY, obX) / Pi; if (configHash["allow_negative_angles"] != "true") if (obTheta < 0) obTheta += 360.0; // Make sure the ob is in the domain if (runMode == XYZ) { if ((obX < imin) or (obX > imax) or (obY < jmin) or (obY > jmax) or (obZ < kmin) or (obZ > kmax)) { domainProblem++; continue; } } else if (runMode == RTZ) { if ((obRadius < imin) or (obRadius > imax) or (obTheta < jmin) or (obTheta > jmax) or (obZ < kmin) or (obZ > kmax)) { domainProblem++; continue; } if (obRadius == 0.0) { radiusProblem++; continue; } } // Create an observation and set its basic info Observation varOb; varOb.setCartesianX(obX); varOb.setCartesianY(obY); varOb.setRadius(obRadius); varOb.setTheta(obTheta); varOb.setAltitude(obZ); varOb.setTime(obTime); // Check this, given Qt's handling of time vs. ours (NCAR) // Reference states real rhoBar = refstate->getReferenceVariable(ReferenceVariable::rhoaref, heightm); real qBar = refstate->getReferenceVariable(ReferenceVariable::qvbhypref, heightm); real tBar = refstate->getReferenceVariable(ReferenceVariable::tempref, heightm); // Initialize the weights for (unsigned int var = 0; var < numVars; ++var) { for (unsigned int d = 0; d < numDerivatives; ++d) { varOb.setWeight(0.0, var, d); } } real u, v, w, rho, rhoa, qv, tempk, rhov, rhou, rhow, wspd; switch (metOb.getObType()) { case (MetObs::dropsonde): varOb.setType(MetObs::dropsonde); u = metOb.getCartesianUwind(); v = metOb.getCartesianVwind(); w = metOb.getVerticalVelocity(); rho = metOb.getMoistDensity(); rhoa = metOb.getAirDensity(); qv = metOb.getQv(); tempk = metOb.getTemperature(); // Separate obs for each measurement // rho v 1 m/s error if ((u != -999) and (rho != -999)) { // rho u 1 m/s error varOb.setWeight(1., 0); if (runMode == XYZ) { rhou = rho*(u - Um); } else if (runMode == RTZ) { rhou = rho*((u - Um)*obX + (v - Vm)*obY)/obRadius; } //cout << "RhoU: " << rhou << endl; varOb.setOb(rhou); varOb.setError(std::stof(configHash["dropsonde_rhou_error"])); obVector.push_back(varOb); varOb.setWeight(0., 0); varOb.setWeight(1., 1); if (runMode == XYZ) { rhov = rho*(v - Vm); } else if (runMode == RTZ) { rhov = rho*(-(u - Um)*obY + (v - Vm)*obX)/obRadius; } varOb.setOb(rhov); varOb.setError(std::stof(configHash["dropsonde_rhov_error"])); obVector.push_back(varOb); varOb.setWeight(0., 1); } if ((w != -999) and (rho != -999)) { // rho w 1.5 m/s error varOb.setWeight(1., 2); rhow = rho*w; varOb.setOb(rhow); varOb.setError(std::stof(configHash["dropsonde_rhow_error"])); obVector.push_back(varOb); varOb.setWeight(0., 2); } if (tempk != -999) { // temperature 1 K error varOb.setWeight(1., 3); varOb.setOb(tempk - tBar); varOb.setError(std::stof(configHash["dropsonde_tempk_error"])); obVector.push_back(varOb); varOb.setWeight(0., 3); } if (qv != -999) { // Qv 0.5 g/kg error varOb.setWeight(1., 4); qv = refstate->bhypTransform(qv); varOb.setOb(qv-qBar); varOb.setError(std::stof(configHash["dropsonde_qv_error"])); obVector.push_back(varOb); varOb.setWeight(0., 4); } if (rhoa != -999) { // Rho prime .1 kg/m^3 error varOb.setWeight(1., 5); varOb.setOb((rhoa-rhoBar)*100); varOb.setError(std::stof(configHash["dropsonde_rhoa_error"])); obVector.push_back(varOb); varOb.setWeight(0., 5); } break; case (MetObs::flightlevel): varOb.setType(MetObs::flightlevel); u = metOb.getCartesianUwind(); v = metOb.getCartesianVwind(); w = metOb.getVerticalVelocity(); rho = metOb.getMoistDensity(); rhoa = metOb.getAirDensity(); qv = metOb.getQv(); tempk = metOb.getTemperature(); // Separate obs for each measurement // rho v 1 m/s error if ((u != -999) and (rho != -999)) { // rho u 1 m/s error varOb.setWeight(1., 0); if (runMode == XYZ) { rhou = rho*(u - Um); } else if (runMode == RTZ) { rhou = rho*((u - Um)*obX + (v - Vm)*obY)/obRadius; } varOb.setOb(rhou); varOb.setError(std::stof(configHash["flightlevel_rhou_error"])); obVector.push_back(varOb); varOb.setWeight(0., 0); varOb.setWeight(1., 1); if (runMode == XYZ) { rhov = rho*(v - Vm); } else if (runMode == RTZ) { rhov = rho*(-(u - Um)*obY + (v - Vm)*obX)/obRadius; } varOb.setOb(rhov); varOb.setError(std::stof(configHash["flightlevel_rhov_error"])); obVector.push_back(varOb); varOb.setWeight(0., 1); } if ((w != -999) and (rho != -999)) { // rho w 1 dm/s error varOb.setWeight(1., 2); rhow = rho*w; varOb.setOb(rhow); varOb.setError(std::stof(configHash["flightlevel_rhow_error"])); obVector.push_back(varOb); varOb.setWeight(0., 2); } if (tempk != -999) { // temperature 1 K error varOb.setWeight(1., 3); varOb.setOb(tempk - tBar); varOb.setError(std::stof(configHash["flightlevel_tempk_error"])); obVector.push_back(varOb); varOb.setWeight(0., 3); } if (qv != -999) { // Qv 0.5 g/kg error varOb.setWeight(1., 4); qv = refstate->bhypTransform(qv); varOb.setOb(qv-qBar); varOb.setError(std::stof(configHash["flightlevel_qv_error"])); obVector.push_back(varOb); varOb.setWeight(0., 4); } if (rhoa != -999) { // Rho prime .1 kg/m^3 error varOb.setWeight(1., 5); varOb.setOb((rhoa-rhoBar)*100); varOb.setError(std::stof(configHash["flightlevel_rhoa_error"])); obVector.push_back(varOb); varOb.setWeight(0., 5); } break; case (MetObs::insitu): varOb.setType(MetObs::insitu); u = metOb.getCartesianUwind(); v = metOb.getCartesianVwind(); w = metOb.getVerticalVelocity(); rho = metOb.getMoistDensity(); rhoa = metOb.getAirDensity(); qv = metOb.getQv(); tempk = metOb.getTemperature(); // Separate obs for each measurement // rho v 1 m/s error if ((u != -999) and (rho != -999)) { // rho u 1 m/s error varOb.setWeight(1., 0); if (runMode == XYZ) { rhou = rho*(u - Um); } else if (runMode == RTZ) { rhou = rho*((u - Um)*obX + (v - Vm)*obY)/obRadius; } //cout << "RhoU: " << rhou << endl; varOb.setOb(rhou); varOb.setError(std::stof(configHash["insitu_rhou_error"])); obVector.push_back(varOb); varOb.setWeight(0., 0); varOb.setWeight(1., 1); if (runMode == XYZ) { rhov = rho*(v - Vm); } else if (runMode == RTZ) { rhov = rho*(-(u - Um)*obY + (v - Vm)*obX)/obRadius; } varOb.setOb(rhov); varOb.setError(std::stof(configHash["insitu_rhov_error"])); obVector.push_back(varOb); varOb.setWeight(0., 1); } if ((w != -999) and (rho != -999)) { // rho w 1.5 m/s error varOb.setWeight(1., 2); rhow = rho*w; varOb.setOb(rhow); varOb.setError(std::stof(configHash["insitu_rhow_error"])); obVector.push_back(varOb); varOb.setWeight(0., 2); } if (tempk != -999) { // temperature 1 K error varOb.setWeight(1., 3); varOb.setOb(tempk - tBar); varOb.setError(std::stof(configHash["insitu_tempk_error"])); obVector.push_back(varOb); varOb.setWeight(0., 3); } if (qv != -999) { // Qv 0.5 g/kg error varOb.setWeight(1., 4); qv = refstate->bhypTransform(qv); varOb.setOb(qv-qBar); varOb.setError(std::stof(configHash["insitu_qv_error"])); obVector.push_back(varOb); varOb.setWeight(0., 4); } if (rhoa != -999) { // Rho prime .1 kg/m^3 error varOb.setWeight(1., 5); varOb.setOb((rhoa-rhoBar)*100); varOb.setError(std::stof(configHash["insitu_rhoa_error"])); obVector.push_back(varOb); varOb.setWeight(0., 5); } break; case (MetObs::mtp): varOb.setType(MetObs::mtp); rhoa = metOb.getDryDensity(); // Pressure/density is from dry air only? tempk = metOb.getTemperature(); if (tempk != -999) { // temperature 1 K error varOb.setWeight(1., 3); varOb.setOb(tempk - tBar); varOb.setError(metOb.getTemperatureError() + std::stof(configHash["mtp_tempk_error"])); obVector.push_back(varOb); varOb.setWeight(0., 3); } if (rhoa != -999) { // Rho prime .1 kg/m^3 error varOb.setWeight(1., 5); varOb.setOb((rhoa-rhoBar)*100); varOb.setError(std::stof(configHash["mtp_rhoa_error"])); obVector.push_back(varOb); varOb.setWeight(0., 5); } break; case (MetObs::sfmr): varOb.setType(MetObs::sfmr); wspd = metOb.getWindSpeed(); // This needs to be redone for the Cartesian case //vBG = 1.e3*bilinearField(obX, obY, 0); //uBG = -1.e5*bilinearField(obX, 20., 1)/(rad*20.); //varOb.setWeight(1., 0); varOb.setWeight(1., 1); varOb.setOb(wspd); varOb.setError(std::stof(configHash["sfmr_windspeed_error"])); obVector.push_back(varOb); break; case (MetObs::qscat): varOb.setType(MetObs::qscat); u = metOb.getCartesianUwind(); v = metOb.getCartesianVwind(); if (u != -999) { // rho u 1 m/s error // Multiply by rho later from grid values varOb.setWeight(1., 0); if (runMode == XYZ) { rhou = (u - Um); } else if (runMode == RTZ) { rhou = ((u - Um)*obX + (v - Vm)*obY)/obRadius; } //cout << "RhoU: " << rhou << endl; varOb.setOb(rhou); varOb.setError(std::stof(configHash["qscat_rhou_error"])); obVector.push_back(varOb); varOb.setWeight(0., 0); varOb.setWeight(1., 1); // Multiply by rho later from grid values if (runMode == XYZ) { rhov = (v - Vm); } else if (runMode == RTZ) { rhov = (-(u - Um)*obY + (v - Vm)*obX)/obRadius; } varOb.setOb(rhov); varOb.setError(std::stof(configHash["qscat_rhov_error"])); obVector.push_back(varOb); varOb.setWeight(0., 1); } break; case (MetObs::ascat): varOb.setType(MetObs::ascat); u = metOb.getCartesianUwind(); v = metOb.getCartesianVwind(); if (u != -999) { // rho u 1 m/s error // Multiply by rho later from grid values varOb.setWeight(1., 0); if (runMode == XYZ) { rhou = (u - Um); } else if (runMode == RTZ) { rhou = ((u - Um)*obX + (v - Vm)*obY)/obRadius; } //cout << "RhoU: " << rhou << endl; varOb.setOb(rhou); varOb.setError(std::stof(configHash["ascat_rhou_error"])); obVector.push_back(varOb); varOb.setWeight(0., 0); varOb.setWeight(1., 1); // Multiply by rho later from grid values if (runMode == XYZ) { rhov = (v - Vm); } else if (runMode == RTZ) { rhov = (-(u - Um)*obY + (v - Vm)*obX)/obRadius; } varOb.setOb(rhov); varOb.setError(std::stof(configHash["ascat_rhov_error"])); obVector.push_back(varOb); varOb.setWeight(0., 1); } break; case (MetObs::AMV): varOb.setType(MetObs::AMV); u = metOb.getCartesianUwind(); v = metOb.getCartesianVwind(); if (u != -999) { // rho u 10 m/s error // Multiply by rho later from grid values varOb.setWeight(1., 0); if (runMode == XYZ) { rhou = (u - Um); } else if (runMode == RTZ) { rhou = ((u - Um)*obX + (v - Vm)*obY)/obRadius; } //cout << "RhoU: " << rhou << endl; varOb.setOb(rhou); varOb.setError(std::stof(configHash["amv_rhou_error"])); obVector.push_back(varOb); varOb.setWeight(0., 0); varOb.setWeight(1., 1); // Multiply by rho later from grid values if (runMode == XYZ) { rhov = (v - Vm); } else if (runMode == RTZ) { rhov = (-(u - Um)*obY + (v - Vm)*obX)/obRadius; } varOb.setOb(rhov); varOb.setError(std::stof(configHash["amv_rhov_error"])); obVector.push_back(varOb); varOb.setWeight(0., 1); } break; case (MetObs::lidar): { varOb.setType(MetObs::lidar); // Geometry terms real az = metOb.getAzimuth()*Pi/180.; real el = metOb.getElevation()*Pi/180.; real uWgt, vWgt; if (runMode == XYZ) { uWgt = sin(az)*cos(el); vWgt = cos(az)*cos(el); } else if (runMode == RTZ) { uWgt = (obX*sin(az)*cos(el) + obY*cos(az)*cos(el))/obRadius; vWgt = (obX*cos(az)*cos(el) - obY*sin(az)*cos(el))/obRadius; } real wWgt = sin(el); // Fall speed is assumed zero since we are dealing with aerosols real db = metOb.getReflectivity(); real vr = metOb.getRadialVelocity(); real w_term = 0.0; real Vdopp = vr - w_term*sin(el) - Um*sin(az)*cos(el) - Vm*cos(az)*cos(el); varOb.setWeight(uWgt, 0); varOb.setWeight(vWgt, 1); varOb.setWeight(wWgt, 2); // Set the error according to the spectrum width and power real DopplerError = metOb.getSpectrumWidth()*std::stof(configHash["lidar_sw_error"]) + log(std::stof(configHash["lidar_power_error"])/db); if (DopplerError < std::stof(configHash["lidar_min_error"])) DopplerError = std::stof(configHash["lidar_min_error"]); varOb.setError(DopplerError); varOb.setOb(Vdopp); obVector.push_back(varOb); varOb.setWeight(0., 0); varOb.setWeight(0., 1); varOb.setWeight(0., 2); break; } case (MetObs::radar): { varOb.setType(MetObs::radar); // Geometry terms real az = metOb.getAzimuth()*Pi/180.; real el = metOb.getElevation()*Pi/180.; real uWgt, vWgt; if (runMode == XYZ) { uWgt = sin(az)*cos(el); vWgt = cos(az)*cos(el); } else if (runMode == RTZ) { uWgt = (obX*sin(az)*cos(el) + obY*cos(az)*cos(el))/obRadius; vWgt = (obX*cos(az)*cos(el) - obY*sin(az)*cos(el))/obRadius; } real wWgt = sin(el); // Restrict to horizontal component only if (configHash["horizontal_radar_appx"] == "true") wWgt = 0; // Fall speed real Z = metOb.getReflectivity(); real w_term = 0.0; real ZZ = -999.0; if (Z > -999.0) { real H = metOb.getAltitude(); ZZ=pow(10.0,(Z*0.1)); real melting_zone = 1000 * std::stof(configHash["melting_zone_width"]); real hlow= zeroClevel; real hhi= hlow + melting_zone; /* density correction term (rhoo/rho)*0.45 0.45 density correction from Beard (1985, JOAT pp 468-471) */ real rho = refstate->getReferenceVariable(ReferenceVariable::rhoref, H); real rhosfc = refstate->getReferenceVariable(ReferenceVariable::rhoref, 0.); real DCOR = pow((rhosfc/rho),(real)0.45); // The snow relationship (Atlas et al., 1973) --- VT=0.817*Z**0.063 (m/s) real VTS=-DCOR * (0.817*pow(ZZ,(real)0.063)); // The rain relationship (Joss and Waldvogel,1971) --- VT=2.6*Z**.107 (m/s) */ real VTR=-DCOR * (2.6*pow(ZZ,(real).107)); /* Test if height is in the transition region between SNOW and RAIN defined as hlow in km < H < hhi in km if in the transition region do a linear weight of VTR and VTS */ real mixed_dbz = std::stof(configHash["mixed_phase_dbz"]); real rain_dbz = std::stof(configHash["rain_dbz"]); if ((Z > mixed_dbz) and (Z <= rain_dbz)) { real WEIGHTR=(Z-mixed_dbz)/(rain_dbz - mixed_dbz); real WEIGHTS=1.-WEIGHTR; VTS=(VTR*WEIGHTR+VTS*WEIGHTS)/(WEIGHTR+WEIGHTS); } else if (Z > rain_dbz) { VTS=VTR; } w_term=VTR*(hhi-H)/melting_zone + VTS*(H-hlow)/melting_zone; if (H < hlow) w_term=VTR; if (H > hhi) w_term=VTS; } real VR = metOb.getRadialVelocity(); if (VR != -999.0) { real Vdopp = metOb.getRadialVelocity() - w_term*sin(el) - Um*sin(az)*cos(el) - Vm*cos(az)*cos(el); varOb.setWeight(uWgt, 0); varOb.setWeight(vWgt, 1); varOb.setWeight(wWgt, 2); /* Theoretically, rhoPrime could be included as a prognostic variable here... However, adding another unknown without an extra equation makes the problem even more underdetermined so assume it is small and ignore it real rhopWgt = -Vdopp; varOb.setWeight(rhopWgt, 5); */ // Set the error according to the spectrum width and potential fall speed error (assume 2 m/s?) real DopplerError = fabs(wWgt)*std::stof(configHash["radar_fallspeed_error"]); if (metOb.getSpectrumWidth() != -999.0) { DopplerError += metOb.getSpectrumWidth()*std::stof(configHash["radar_sw_error"]); } if (DopplerError < std::stof(configHash["radar_min_error"])) DopplerError = std::stof(configHash["radar_min_error"]); varOb.setError(DopplerError); varOb.setOb(Vdopp); real maxel; if (configHash.exists("max_radar_elevation") == false) { maxel = 90.0; } else { maxel = std::stof(configHash["max_radar_elevation"]); } if (fabs(metOb.getElevation() <= maxel)) obVector.push_back(varOb); varOb.setWeight(0., 0); varOb.setWeight(0., 1); varOb.setWeight(0., 2); } // Reflectivity observations std::string gridref = configHash["qr_variable"]; real qr = 0.; if (ZZ > 0) { if (gridref == "qr") { // Do the gridding as part of the variational synthesis using Z-M relationships // Z-M relationships from Gamache et al (1993) JAS real H = metOb.getAltitude(); real melting_zone = 1000 * std::stof(configHash["melting_zone_width"]); real hlow= zeroClevel; real hhi= hlow + melting_zone; real rainmass = pow(ZZ/14630.,(real)0.6905); real icemass = pow(ZZ/670.,(real)0.5587); real mixed_dbz = std::stof(configHash["mixed_phase_dbz"]); real rain_dbz = std::stof(configHash["rain_dbz"]); if ((Z > mixed_dbz) and (Z <= rain_dbz)) { real WEIGHTR=(Z-mixed_dbz)/(rain_dbz - mixed_dbz); real WEIGHTS=1.-WEIGHTR; icemass=(rainmass*WEIGHTR+icemass*WEIGHTS)/(WEIGHTR+WEIGHTS); } else if (Z > 30) { icemass=rainmass; } real precipmass = rainmass*(hhi-H)/melting_zone + icemass*(H-hlow)/melting_zone; if (H < hlow) precipmass = rainmass; if (H > hhi) precipmass = icemass; qr = refstate->bhypTransform(precipmass/rhoBar); //Include an observation of this quantity in the variational synthesis varOb.setOb(qr); varOb.setWeight(1., 6); varOb.setError(1.0); obVector.push_back(varOb); } else if (gridref == "dbz") { qr = ZZ; /* Include an observation of this quantity in the variational synthesis varOb.setOb(qr); varOb.setWeight(1., 6); varOb.setError(1.0); obVector.push_back(varOb); */ } // Do a Exponential & power weighted interpolation of the reflectivity/qr in a grid box real iROI = std::stof(configHash["i_reflectivity_roi"]) / iincr; real jROI = std::stof(configHash["j_reflectivity_roi"]) / jincr; real kROI = std::stof(configHash["k_reflectivity_roi"]) / kincr; real Rsquare = (iincr*iROI)*(iincr*iROI) + (jincr*jROI)*(jincr*jROI) + (kincr*kROI)*(kincr*kROI); #pragma omp parallel for for (int ki = 0; ki < (kdim-1); ki++) { for (int kmu = -1; kmu <= 1; kmu += 2) { real kPos = kmin + kincr * (ki + (0.5*sqrt(1./3.) * kmu + 0.5)); if (fabs(kPos-obZ) > kincr*kROI*2.) continue; for (int ii = 0; ii < (idim-1); ii++) { for (int imu = -1; imu <= 1; imu += 2) { real iPos = imin + iincr * (ii + (0.5*sqrt(1./3.) * imu + 0.5)); if (runMode == XYZ) { if (fabs(iPos-obX) > iincr*iROI*2.) continue; } else if (runMode == RTZ) { if (fabs(iPos-obRadius) > iincr*iROI*2.) continue; } for (int ji = 0; ji < (jdim-1); ji++) { for (int jmu = -1; jmu <= 1; jmu += 2) { real jPos = jmin + jincr * (ji + (0.5*sqrt(1./3.) * jmu + 0.5)); real rSquare = 0.0; if (runMode == XYZ) { if (fabs(jPos-obY) > jincr*jROI*2.) continue; rSquare = (obX-iPos)*(obX-iPos) + (obY-jPos)*(obY-jPos) + (obZ-kPos)*(obZ-kPos); } else if (runMode == RTZ) { real dTheta = fabs(jPos-obTheta); if (dTheta > 360.) dTheta -= 360.; if (dTheta > jincr*jROI*2.) continue; rSquare = (obRadius-iPos)*(obRadius-iPos) + (dTheta)*(dTheta) + (obZ-kPos)*(obZ-kPos); } // Add one extra index to account for buffer zone in analysis int bgI = (ii+1)*2 + (imu+1)/2; int bgJ = (ji+1)*2 + (jmu+1)/2; int bgK = (ki+1)*2 + (kmu+1)/2; int64_t bIndex = numVars*(idim+1)*2*(jdim+1)*2*bgK + numVars*(idim+1)*2*bgJ +numVars*bgI; if (rSquare < Rsquare) { real weight = exp(-2.302585092994045*rSquare/Rsquare); //real weight = (Rsquare - rSquare)/(Rsquare + rSquare); //if (qr > bgU[bIndex +6]) bgU[bIndex +6] = qr; bgU[bIndex +6] += weight*qr; bgWeights[bIndex] += weight; } } } } } } } } break; } case(MetObs::mesonet): { varOb.setType(MetObs::mesonet); u = metOb.getCartesianUwind(); v = metOb.getCartesianVwind(); w = metOb.getVerticalVelocity(); rho = metOb.getMoistDensity(); rhoa = metOb.getAirDensity(); qv = metOb.getQv(); tempk = metOb.getTemperature(); // Separate obs for each measurement // rho v 1 m/s error if ((u != -999) and (rho != -999)) { // rho u 1 m/s error varOb.setWeight(1., 0); if (runMode == XYZ) { rhou = rho*(u - Um); } else if (runMode == RTZ) { rhou = rho*((u - Um)*obX + (v - Vm)*obY)/obRadius; } //cout << "RhoU: " << rhou << endl; varOb.setOb(rhou); varOb.setError(std::stof(configHash["mesonet_rhou_error"])); obVector.push_back(varOb); varOb.setWeight(0., 0); varOb.setWeight(1., 1); if (runMode == XYZ) { rhov = rho*(v - Vm); } else if (runMode == RTZ) { rhov = rho*(-(u - Um)*obY + (v - Vm)*obX)/obRadius; } varOb.setOb(rhov); varOb.setError(std::stof(configHash["mesonet_rhov_error"])); obVector.push_back(varOb); varOb.setWeight(0., 1); } if ((w != -999) and (rho != -999)) { // rho w 1.5 m/s error varOb.setWeight(1., 2); rhow = rho*w; varOb.setOb(rhow); varOb.setError(std::stof(configHash["mesonet_rhow_error"])); obVector.push_back(varOb); varOb.setWeight(0., 2); } if (tempk != -999) { // temperature 1 K error varOb.setWeight(1., 3); varOb.setOb(tempk - tBar); varOb.setError(std::stof(configHash["mesonet_tempk_error"])); obVector.push_back(varOb); varOb.setWeight(0., 3); } if (qv != -999) { // Qv 0.5 g/kg error varOb.setWeight(1., 4); qv = refstate->bhypTransform(qv); varOb.setOb(qv-qBar); varOb.setError(std::stof(configHash["mesonet_qv_error"])); obVector.push_back(varOb); varOb.setWeight(0., 4); } if (rhoa != -999) { // Rho prime .1 kg/m^3 error varOb.setWeight(1., 5); varOb.setOb((rhoa-rhoBar)*100); varOb.setError(std::stof(configHash["mesonet_rhoa_error"])); obVector.push_back(varOb); varOb.setWeight(0., 5); } break; } case(MetObs::aeri): { varOb.setType(MetObs::aeri); u = metOb.getCartesianUwind(); v = metOb.getCartesianVwind(); w = metOb.getVerticalVelocity(); rho = metOb.getMoistDensity(); rhoa = metOb.getAirDensity(); qv = metOb.getQv(); tempk = metOb.getTemperature(); // Separate obs for each measurement // rho v 1 m/s error if ((u != -999) and (rho != -999)) { // rho u 1 m/s error varOb.setWeight(1., 0); if (runMode == XYZ) { rhou = rho*(u - Um); } else if (runMode == RTZ) { rhou = rho*((u - Um)*obX + (v - Vm)*obY)/obRadius; } //cout << "RhoU: " << rhou << endl; varOb.setOb(rhou); varOb.setError(std::stof(configHash["aeri_rhou_error"])); obVector.push_back(varOb); varOb.setWeight(0., 0); varOb.setWeight(1., 1); if (runMode == XYZ) { rhov = rho*(v - Vm); } else if (runMode == RTZ) { rhov = rho*(-(u - Um)*obY + (v - Vm)*obX)/obRadius; } varOb.setOb(rhov); varOb.setError(std::stof(configHash["aeri_rhov_error"])); obVector.push_back(varOb); varOb.setWeight(0., 1); } if ((w != -999) and (rho != -999)) { // rho w 1.5 m/s error varOb.setWeight(1., 2); rhow = rho*w; varOb.setOb(rhow); varOb.setError(std::stof(configHash["aeri_rhow_error"])); obVector.push_back(varOb); varOb.setWeight(0., 2); } if (tempk != -999) { // temperature 1 K error varOb.setWeight(1., 3); varOb.setOb(tempk - tBar); varOb.setError(std::stof(configHash["aeri_tempk_error"])); obVector.push_back(varOb); varOb.setWeight(0., 3); } if (qv != -999) { // Qv 0.5 g/kg error varOb.setWeight(1., 4); qv = refstate->bhypTransform(qv); varOb.setOb(qv-qBar); varOb.setError(std::stof(configHash["aeri_qv_error"])); obVector.push_back(varOb); varOb.setWeight(0., 4); } if (rhoa != -999) { // Rho prime .1 kg/m^3 error varOb.setWeight(1., 5); varOb.setOb((rhoa-rhoBar)*100); varOb.setError(std::stof(configHash["aeri_rhoa_error"])); obVector.push_back(varOb); varOb.setWeight(0., 5); } break; } } } // for everything in metData // Show a summary of what got tossed out cout << "Observation problem: " << obsProblem << ", Time problem: " << timeProblem << ", Coordinate problem: " << coordProblem << ", Domain problem: " << domainProblem << ", Radius problem: " << radiusProblem << endl; std::cout << "obVector size: " << obVector.size() << std::endl; int newobs = obVector.size() - prevobs; // if (metData->size() > 0) { if (newobs > 0) { cout << "Processed " << newobs << " observations from " << metData->size() << " entries (" << 100.0*(float)newobs/(6*(float)metData->size()) << "%) file: " << file << std::endl; } else { cout << "No valid observations in file\n"; } cout << obVector.size() << " total observations." << " ( " << attemptedFiles << " of " << totalFiles << " files processed ) " << endl; } delete metData; // Finish reflectivity interpolation Observation varOb; varOb.setTime(std::stoi(configHash["ref_time"])); real pseudow_weight = std::stof(configHash["dbz_pseudow_weight"]); real mc_weight = std::stof(configHash["mc_weight"]); // Initialize the weights for (unsigned int var = 0; var < numVars; ++var) { for (unsigned int d = 0; d < numDerivatives; ++d) { varOb.setWeight(0.0, var, d); } } real gausspoint = 0.5*sqrt(1./3.); for (int iIndex = -1; iIndex < idim; iIndex++) { for (int ihalf = 0; ihalf <= 1; ihalf++) { for (int imu = -ihalf; imu <= ihalf; imu++) { real i = imin + iincr * (iIndex + (gausspoint * imu + 0.5*ihalf)); for (int jIndex = -1; jIndex < jdim; jIndex++) { for (int jhalf =0; jhalf <= 1; jhalf++) { for (int jmu = -jhalf; jmu <= jhalf; jmu++) { real j = jmin + jincr * (jIndex + (gausspoint * jmu + 0.5*jhalf)); real maxrefHeight = -1; for (int kIndex = -1; kIndex < kdim; kIndex++) { for (int khalf =0; khalf <= 1; khalf++) { for (int kmu = -khalf; kmu <= khalf; kmu++) { real k = kmin + kincr * (kIndex + (gausspoint * kmu + 0.5*khalf)); // On the mish if (ihalf and jhalf and khalf and (imu != 0) and (jmu != 0) and (kmu != 0)){ int bgI = (iIndex+1)*2 + (imu+1)/2; int bgJ = (jIndex+1)*2 + (jmu+1)/2; int bgK = (kIndex+1)*2 + (kmu+1)/2; int64_t bIndex = numVars*(idim+1)*2*(jdim+1)*2*bgK + numVars*(idim+1)*2*bgJ +numVars*bgI; if (bgWeights[bIndex] != 0) { bgU[bIndex +6] /= bgWeights[bIndex]; } if (configHash["qr_variable"] == "dbz") { if (bgU[bIndex +6] > 0) { real dbzavg = 10* log10(bgU[bIndex +6]); bgU[bIndex +6] = (dbzavg+35.)*0.1; } else { bgU[bIndex +6] = 0.0; } if (bgU[bIndex +6] > 3.5) { maxrefHeight = k; } } } // On the nodes for mass continuity if ((mc_weight > 0.0) and !ihalf and !jhalf and !khalf and (i >= imin) and (i <= imax) and (j >= jmin) and (j <= jmax) and (k >= kmin) and (k <= kmax)) { if (runMode == XYZ) { varOb.setCartesianX(i); varOb.setCartesianY(j); varOb.setWeight(1.0, 0, 1); varOb.setWeight(1.0, 1, 2); varOb.setWeight(1.0, 2, 3); } else if (runMode == RTZ) { if (i > 0) { varOb.setRadius(i); varOb.setTheta(j); real rInverse = 180.0/(i*Pi); varOb.setWeight((1.0/i), 0, 0); varOb.setWeight(1.0, 0, 1); varOb.setWeight(rInverse, 1, 2); varOb.setWeight(1.0, 2, 3); } } varOb.setAltitude(k); varOb.setError(mc_weight); varOb.setOb(0.); obVector.push_back(varOb); } } } } varOb.setWeight(0.0, 0, 1); varOb.setWeight(0.0, 1, 2); varOb.setWeight(0.0, 2, 3); varOb.setWeight(1., 2); if (runMode == XYZ) { varOb.setCartesianX(i); varOb.setCartesianY(j); } else if (runMode == RTZ) { varOb.setRadius(i); varOb.setTheta(j); } varOb.setError(pseudow_weight); varOb.setOb(0.); if (!ihalf and !jhalf){ // Set an upper boundary condition for W if ((maxrefHeight > 0) and (maxrefHeight < kmax) and (pseudow_weight > 0.0)) { varOb.setAltitude(maxrefHeight); obVector.push_back(varOb); } // Set a lower boundary condition for W // Ideally use a terrain map here, but just use Z=0 for now if (pseudow_weight > 0.0) { varOb.setAltitude(0.0); varOb.setError(pseudow_weight); obVector.push_back(varOb); } } varOb.setWeight(0., 2); } } } } } } cout << obVector.size() << " total observations including pseudo-obs for W and mass continuity" << endl; #if IO_WRITEOBS GPTLstart("VarDriver3D::preprocessMetObs->writeobs"); // Write the Obs to a summary text file std::string obFilename = dataPath + "/samurai_Observations.in"; ofstream obstream(obFilename); // Header messes up reload /*ostream_iterator<string> os(obstream, "\t "); *os++ = "Type"; *os++ = "r"; *os++ = "z"; *os++ = "NULL"; *os++ = "Observation"; *os++ = "Inverse Error"; *os++ = "Weight 1"; *os++ = "Weight 2"; *os++ = "Weight 3"; *os++ = "Weight 4"; *os++ = "Weight 5"; *os++ = "Weight 6"; obstream << endl; */ ostream_iterator<real> od(obstream, "\t "); ostream_iterator<int> oi(obstream, "\t "); for (int i=0; i < obVector.size(); i++) { Observation ob = obVector.at(i); *od++ = ob.getOb(); real invError = ob.getInverseError(); if (!invError) { cout << "Undefined instrument error specification for " << ob.getType() << "instrument type!\n"; return false; } *od++ = invError; if (runMode == XYZ) { *od++ = ob.getCartesianX(); *od++ = ob.getCartesianY(); } else if (runMode == RTZ) { *od++ = ob.getRadius(); *od++ = ob.getTheta(); } *od++ = ob.getAltitude(); *oi++ = ob.getType(); *oi++ = ob.getTime(); for (unsigned int var = 0; var < numVars; var++) { for (unsigned int d = 0; d < numDerivatives; ++d) { *od++ = ob.getWeight(var, d); } } obstream << endl; } GPTLstop("VarDriver3D::preprocessMetObs->writeobs"); #endif // Load the observations into a vector int64_t vector_size = (obVector.size() * (7 + numVars * numDerivatives)); obs = new real[vector_size]; for (int64_t m=0; m < obVector.size(); m++) { int64_t n = m * (7 + numVars * numDerivatives); Observation ob = obVector.at(m); obs[n] = ob.getOb(); real invError = ob.getInverseError(); if (!invError) { cout << "Undefined instrument error specification for " << ob.getType() << "instrument type!\n"; return false; } obs[n+1] = invError; if (runMode == XYZ) { obs[n+2] = ob.getCartesianX(); obs[n+3] = ob.getCartesianY(); } else if (runMode == RTZ) { obs[n+2] = ob.getRadius(); obs[n+3] = ob.getTheta(); } obs[n+4] = ob.getAltitude(); obs[n+5] = ob.getType(); obs[n+6] = ob.getTime(); for (unsigned int var = 0; var < numVars; var++) { for (unsigned int d = 0; d < numDerivatives; ++d) { int64_t wgt_index = n + ( 7 * (d + 1)) + var; obs[wgt_index] = ob.getWeight(var, d); } } } // All done preprocessing if (!processedFiles) { cout << "No files processed, nothing to do :(" << endl; // return 0; } else { cout << "Finished preprocessing " << processedFiles << " files." << endl; } GPTLstop("VarDriver3D::preprocessMetObs"); return true; } /* Load the meteorological observations from a file into a vector */ bool VarDriver3D::loadPreProcessMetObs() { GPTLstart("VarDriver3D::loadPreprocessMetObs"); Observation varOb; real wgt[numVars][4]; real iPos, jPos, kPos, ob, error; int type; int64_t time; cout << "Loading preprocessed observations from samurai_Observations.in" << endl; // Open and read the file std::string obFilename = dataPath + "/samurai_Observations.in"; ifstream obstream(obFilename); while (obstream >> ob >> error >> iPos >> jPos >> kPos >> type >> time >> wgt[0][0] >> wgt[0][1] >> wgt[0][2] >> wgt[0][3] >> wgt[1][0] >> wgt[1][1] >> wgt[1][2] >> wgt[1][3] >> wgt[2][0] >> wgt[2][1] >> wgt[2][2] >> wgt[2][3] >> wgt[3][0] >> wgt[3][1] >> wgt[3][2] >> wgt[3][3] >> wgt[4][0] >> wgt[4][1] >> wgt[4][2] >> wgt[4][3] >> wgt[5][0] >> wgt[5][1] >> wgt[5][2] >> wgt[5][3] >> wgt[6][0] >> wgt[6][1] >> wgt[6][2] >> wgt[6][3]) { varOb.setOb(ob); if (runMode == XYZ) { varOb.setCartesianX(iPos); varOb.setCartesianY(jPos); } else if (runMode == RTZ) { varOb.setRadius(iPos); varOb.setTheta(jPos); } varOb.setAltitude(kPos); varOb.setType(type); varOb.setTime(time); varOb.setError(1./error); for (unsigned int var = 0; var < numVars; var++) { for (unsigned int d = 0; d < numDerivatives; ++d) { varOb.setWeight(wgt[var][d], var, d); } } obVector.push_back(varOb); } // Load the observations into the vector obs = new real[obVector.size() * (7 + numVars * numDerivatives)]; for (int m=0; m < obVector.size(); m++) { int n = m * (7 + numVars * numDerivatives); Observation ob = obVector.at(m); obs[n] = ob.getOb(); real invError = ob.getInverseError(); if (!invError) { cout << "Undefined instrument error specification for " << ob.getType() << "instrument type!\n"; return false; } obs[n+1] = invError; if (runMode == XYZ) { obs[n+2] = ob.getCartesianX(); obs[n+3] = ob.getCartesianY(); } else if (runMode == RTZ) { obs[n+2] = ob.getRadius(); obs[n+3] = ob.getTheta(); } obs[n+4] = ob.getAltitude(); obs[n+5] = ob.getType(); obs[n+6] = ob.getTime(); for (unsigned int var = 0; var < numVars; var++) { for (unsigned int d = 0; d < numDerivatives; ++d) { int wgt_index = n + (7 * (d + 1)) + var; obs[wgt_index] = ob.getWeight(var, d); } } } GPTLstop("VarDriver3D::loadPreprocessMetObs"); return true; } // Background Observations can come from // - a samurai_Background.in file, // - a FRACTL generated netcdf file // - from passed arguments to the run() function. int VarDriver3D::loadBackgroundObs() { if(bkgdAdapter == NULL) { std::cerr << "Error: VarDriver3D::loadBackgroundObs() called without adapter initialization." << std::endl; exit(1); } // Get a background obs loader to load the background observations // Default is Spline. BkgdObsLoader::bg_loader_t loaderType = BkgdObsLoader::BG_LOADER_SPLINE; if (configHash["bkgd_obs_interpolation"] == "kd_tree") loaderType = BkgdObsLoader::BG_LOADER_KD; else if (configHash["bkgd_obs_interpolation"] == "fractl") loaderType = BkgdObsLoader::BG_LOADER_FRACTL; BkgdObsLoader *bkgdObsLoader = BkgdObsLoaderFactory::createBkgdObsLoader(loaderType); if (bkgdObsLoader == NULL) return -1; bkgdObsLoader->initialize(&configHash, frameVector, bkgdAdapter, projection, refstate, uStateSize, bgU, numVars, idim, jdim, kdim, imin, jmin, kmin, imax, jmax, kmax, iincr, jincr, kincr); if (! bkgdObsLoader->loadBkgdObs(bgIn)) { std::cerr << "Failed to load background observations" << std::endl; return -1; } return bgIn.size() * 7 / 11; } bool VarDriver3D::adjustBackground() { // Set the minimum filter length to the background resolution, not the analysis resolution // to avoid artifacts when running interpolating to small mesoscale grids START_TIMER(timeab); // Load the observations into a vector int numbgObs = bgIn.size() * 7 / 11; if (std::stof(configHash["mc_weight"]) > 0) { numbgObs += idim * jdim * kdim; } bgObs = new real[numbgObs * (7 + numVars * numDerivatives)]; for (unsigned int m = 0; m < numbgObs * (7 + numVars * numDerivatives); m++) bgObs[m] = 0.; int p = 0; real obX, obY, obRadius, obTheta; obX = obY = obRadius = obTheta = -32768.; for (int m = 0; m < bgIn.size(); m += 11) { if (runMode == XYZ) { obX = bgIn[m]; obY = bgIn[m + 1]; } else if (runMode == RTZ) { obRadius = bgIn[m]; obTheta = bgIn[m + 1]; } real obZ = exp(bgIn[m + 2]); real obTime = bgIn[m + 3]; // Make sure the ob is in the domain if (runMode == XYZ) { if ((obX < imin) or (obX > imax) or (obY < jmin) or (obY > jmax) or (obZ < kmin) or (obZ > kmax)) { numbgObs -= 7; continue; } } else if (runMode == RTZ) { if ((obRadius < imin) or (obRadius > imax) or (obTheta < jmin) or (obTheta > jmax) or (obZ < kmin) or (obZ > kmax)) { numbgObs -= 7; continue; } } for (unsigned int n = 0; n < numVars; n++) { bgObs[p] = bgIn[m + 4 + n]; if ((n == 6) and (configHash["qr_variable"] == "dbz")) { // Convert to dBZ control variable real dbzavg = 10 * log10(bgIn[m + 4 + n]); bgObs[p] = (dbzavg + 35.) * 0.1; } // Default error of background = 0.1 if ((configHash.exists("bg_obs_error") or (std::stof(configHash["bg_obs_error"]) <= 0.0))) { bgObs[p + 1] = 100.; } else { bgObs[p + 1] = 1.0 / std::stof(configHash["bg_obs_error"]); } if (runMode == XYZ) { bgObs[p + 2] = obX; bgObs[p + 3] = obY; } else if (runMode == RTZ) { bgObs[p + 2] = obRadius; bgObs[p + 3] = obTheta; } bgObs[p + 4] = obZ; // Null type bgObs[p + 5] = -1; bgObs[p + 6] = obTime; bgObs[p + 7 + n] = 1.; p += (7 + numVars * numDerivatives); } } // Add mass continuity constraint if (std::stof(configHash["mc_weight"]) > 0) { for (int iIndex = 0; iIndex < idim; iIndex++) { real i = imin + iincr * iIndex; if (i > ((idim - 1) * iincr + imin)) continue; for (int jIndex = 0; jIndex < jdim; jIndex++) { real j = jmin + jincr * jIndex; if (j > ((jdim - 1) * jincr + jmin)) continue; for (int kIndex = 0; kIndex < kdim; kIndex++) { real k = kmin + kincr * kIndex; if (k > ((kdim - 1)*kincr + kmin)) continue; bgObs[p] = 0.0; bgObs[p+1] = std::stof(configHash["mc_weight"]); bgObs[p+2] = i; bgObs[p+3] = j; bgObs[p+4] = k; // Null type bgObs[p + 5] = -1; bgObs[p + 6] = std::stoi(configHash["ref_time"]); if (runMode == XYZ) { bgObs[p + (7 * (1 + 1))] = 1.0; bgObs[p + (7 * (2 + 1)) + 1] = 1.0; bgObs[p + (7 * (3 + 1)) + 2] = 1.0; } else if (runMode == RTZ) { if (i > 0) { real rInverse = 180.0/(i * Pi); bgObs[p + 7] = 1.0/i; bgObs[p + (7 * (1 + 1))] = 1.0; bgObs[p + (7 * (2 + 1)) + 1] = rInverse; bgObs[p + (7 * (3 + 1)) + 2] = 1.0; } } p += (7 + numVars * numDerivatives); } } } } // Store and set the background errors std::string bgError[7]; bgError[0] = configHash["bg_rhou_error"]; bgError[1] = configHash["bg_rhov_error"]; bgError[2] = configHash["bg_rhow_error"]; bgError[3] = configHash["bg_tempk_error"]; bgError[4] = configHash["bg_qv_error"]; bgError[5] = configHash["bg_rhoa_error"]; bgError[6] = configHash["bg_qr_error"]; std::string bg_interpolation_error = "1.0"; if (configHash.exists("bg_interpolation_error")) { bg_interpolation_error = configHash["bg_interpolation_error"]; cout << "Setting background interpolation error to " << bg_interpolation_error << "\n"; } else { cout << "Using default background interpolation error of 1.0\n"; } configHash.update("bg_rhou_error", bg_interpolation_error); configHash.update("bg_rhov_error", bg_interpolation_error); configHash.update("bg_rhow_error", bg_interpolation_error); configHash.update("bg_tempk_error", bg_interpolation_error); configHash.update("bg_qv_error", bg_interpolation_error); configHash.update("bg_rhoa_error", bg_interpolation_error); configHash.update("bg_qr_error", bg_interpolation_error); configHash.update("save_mish", "true"); // Adjust the background field to the spline mish if (runMode == XYZ) { if (std::stof(configHash["output_pressure_increment"]) > 0) { bgCost3D = new CostFunctionXYP(projection, numbgObs, bStateSize); } else { bgCost3D = new CostFunctionXYZ(projection, numbgObs, bStateSize); } } else if (runMode == RTZ) { bgCost3D = new CostFunctionRTZ(projection, numbgObs, bStateSize); } bgCost3D->initialize(&configHash, bgU, bgObs, refstate); // Set the iteration to zero -- // this will prevent writing the background file until after the adjustment // which is presumably what you want most of the time. Otherwise, you would not be here int bgIter = 1; bgCost3D->initState(bgIter); bgCost3D->minimize(); // Increment the variables bgCost3D->updateBG(); bgCost3D->finalize(); delete bgCost3D; delete[] bgObs; // Reset the background errors configHash.update("bg_rhou_error", bgError[0]); configHash.update("bg_rhov_error", bgError[1]); configHash.update("bg_rhow_error", bgError[2]); configHash.update("bg_tempk_error", bgError[3]); configHash.update("bg_qv_error", bgError[4]); configHash.update("bg_rhoa_error", bgError[5]); configHash.update("bg_qr_error", bgError[6]); configHash.update("save_mish", "false"); // Convert the dBZ back to Z for further processing if (configHash["qr_variable"] == "dbz") { for (int ki = -1; ki < (kdim); ki++) { for (int kmu = -1; kmu <= 1; kmu += 2) { for (int ii = -1; ii < (idim); ii++) { for (int imu = -1; imu <= 1; imu += 2) { for (int ji = -1; ji < (jdim); ji++) { for (int jmu = -1; jmu <= 1; jmu += 2) { int bgI = (ii + 1) * 2 + (imu + 1) / 2; int bgJ = (ji + 1) * 2 + (jmu + 1) / 2; int bgK = (ki + 1) * 2 + (kmu + 1) / 2; int bIndex = numVars * (idim + 1) * 2 * (jdim + 1) * 2 * bgK + numVars * (idim + 1) * 2 * bgJ + numVars * bgI; real dbZ = bgU[bIndex + 6] * 10. - 35.; real ZZ = pow(10.0, (dbZ * 0.1)); bgU[bIndex + 6] = ZZ; } } } } } } } PRINT_TIMER("adjustBackground", timeab); return true; } /* Any updates needed for additional analysis iterations go here */ void VarDriver3D::updateAnalysisParams(const int& iteration) { std::string iter = std::to_string(iteration); std::string key = "bg_rhou_error_" + iter; std::string val = configHash[key]; configHash.update("bg_rhou_error", val); key = "bg_rhov_error_" + iter; val = configHash[key]; configHash.update("bg_rhov_error", val); key = "bg_rhow_error_" + iter; val = configHash[key]; configHash.update("bg_rhow_error", val); key = "bg_tempk_error_" + iter; val = configHash[key]; configHash.update("bg_tempk_error", val); key = "bg_qv_error_" + iter; val = configHash[key]; configHash.update("bg_qv_error", val); key = "bg_rhoa_error_" + iter; val = configHash[key]; configHash.update("bg_rhoa_error", val); key = "bg_qr_error_" + iter; val = configHash[key]; configHash.update("bg_qr_error", val); key = "mc_weight_" + iter; val = configHash[key]; configHash.update("mc_weight", val); key = "i_filter_length_" + iter; val = configHash[key]; configHash.update("i_filter_length", val); key = "j_filter_length_" + iter; val = configHash[key]; configHash.update("j_filter_length", val); key = "k_filter_length_" + iter; val = configHash[key]; configHash.update("k_filter_length", val); key = "i_spline_cutoff_" + iter; val = configHash[key]; configHash.update("i_spline_cutoff", val); key = "j_spline_cutoff_" + iter; val = configHash[key]; configHash.update("j_spline_cutoff", val); key = "k_spline_cutoff_" + iter; val = configHash[key]; configHash.update("k_spline_cutoff", val); } /* This routine validates that all required parameters are present It currently does not check the validity of a particular parameter, just that it exists */ bool VarDriver3D::validateConfig() { // Validate the hash -- multiple passes are not validated currently std::set<std::string> configKeys; configKeys.insert("mc_weight"); configKeys.insert("i_filter_length"); configKeys.insert("j_filter_length"); configKeys.insert("k_filter_length"); configKeys.insert("i_spline_cutoff"); configKeys.insert("j_spline_cutoff"); configKeys.insert("k_spline_cutoff"); configKeys.insert("i_rhou_bcL"); configKeys.insert("i_rhou_bcR"); configKeys.insert("j_rhou_bcL"); configKeys.insert("j_rhou_bcR"); configKeys.insert("k_rhou_bcL"); configKeys.insert("k_rhou_bcR"); configKeys.insert("i_rhov_bcL"); configKeys.insert("i_rhov_bcR"); configKeys.insert("j_rhov_bcL"); configKeys.insert("j_rhov_bcR"); configKeys.insert("k_rhov_bcL"); configKeys.insert("k_rhov_bcR"); configKeys.insert("i_rhow_bcL"); configKeys.insert("i_rhow_bcR"); configKeys.insert("j_rhow_bcL"); configKeys.insert("j_rhow_bcR"); configKeys.insert("k_rhow_bcL"); configKeys.insert("k_rhow_bcR"); configKeys.insert("i_tempk_bcL"); configKeys.insert("i_tempk_bcR"); configKeys.insert("j_tempk_bcL"); configKeys.insert("j_tempk_bcR"); configKeys.insert("k_tempk_bcL"); configKeys.insert("k_tempk_bcR"); configKeys.insert("i_qv_bcL"); configKeys.insert("i_qv_bcR"); configKeys.insert("j_qv_bcL"); configKeys.insert("j_qv_bcR"); configKeys.insert("k_qv_bcL"); configKeys.insert("k_qv_bcR"); configKeys.insert("i_rhoa_bcL"); configKeys.insert("i_rhoa_bcR"); configKeys.insert("j_rhoa_bcL"); configKeys.insert("j_rhoa_bcR"); configKeys.insert("k_rhoa_bcL"); configKeys.insert("k_rhoa_bcR"); configKeys.insert("i_qr_bcL"); configKeys.insert("i_qr_bcR"); configKeys.insert("j_qr_bcL"); configKeys.insert("j_qr_bcR"); configKeys.insert("k_qr_bcL"); configKeys.insert("k_qr_bcR"); configKeys.insert("data_directory"); configKeys.insert("output_directory"); if (fixedGrid) { configKeys.insert("i_min"); configKeys.insert("i_max"); configKeys.insert("i_incr"); configKeys.insert("j_min"); configKeys.insert("j_max"); configKeys.insert("j_incr"); configKeys.insert("k_min"); configKeys.insert("k_max"); configKeys.insert("k_incr"); } for (auto &key : configKeys) { if ( configHash.exists(key) == false ) { std::cout << "No configuration found for <" << key << "> aborting..." << std::endl; return false; } } // Add default values here if ( configHash.exists("bkgd_obs_interpolation") == false) configHash.insert("bkgd_obs_interpolation", "spline"); if ( configHash.exists("bkgd_kd_num_neighbors") == false) configHash.insert("bkgd_kd_num_neighbors", "6"); if ( configHash.exists("bkgd_kd_max_distance") == false) { // TODO What should the default max distance for a nearest neighbor be? configHash.insert("bkgd_kd_max_distance", "100"); } // All done return true; } bool VarDriver3D::loadBackgroundCoeffs() { // Load a set of coefficients directly for the same grid cout << "Loading previous coefficients from samurai_Coefficients.in" << endl; std::ifstream bgFile(dataPath + "/samurai_Coefficients.in"); if (!bgFile.is_open()) return false; int numbgCoeffs = 0; std::string line; while (std::getline(bgFile, line)) { std::istringstream iss(line); if (line.find("Variable") != std::string::npos) { continue; } else { int var; iss >> var; int iIndex; iss >> iIndex; int jIndex; iss >> jIndex; int kIndex; iss >> kIndex; int bIndex = numVars*(idim+2)*(jdim+2)*kIndex + numVars*(idim+2)*jIndex +numVars*iIndex + var; float value; iss >> value; bgU[bIndex] = value; numbgCoeffs++; } } cout << numbgCoeffs << " background coeffients loaded" << endl; if (numbgCoeffs != bStateSize) { cout << "Error loading background coefficients" << endl; return false; } return true; } // fill up variables from arguments and call the common validateGrid() bool VarDriver3D::validateRunGrid(float n_x, float n_y, float n_z, float i_min, float i_max, float i_incr, float j_min, float j_max, float j_incr, float *sigmas) { // Grid specs imin = i_min; imax = i_max; iincr = i_incr; jmin = j_min; jmax = j_max; jincr = j_incr; // k grid dimension. This is pretty arbitrary kmin = 0.0; // kmax = sigmas[0] / 1000; // do we ned to round this up? kmax = *std::max_element(sigmas, sigmas + (int) n_z) / 1000; kincr = 0.5; // Array dimensions idim = n_x; jdim = n_y; kdim = n_z; sigmaTable = sigmas; return validateGrid(); } bool VarDriver3D::validateFractlGrid() { // Need to read grid from fractl file. Nc3Error err(Nc3Error::verbose_nonfatal); std::string fname = configHash["fractl_nc_file"]; // Open the file. Nc3File dataFile(fname.c_str(), Nc3File::ReadOnly); // Check to see if the file was opened. if(!dataFile.is_valid()) { std::cout << "Failed to read FRACTL generated nc file " << fname << std::endl; return false; } Nc3Dim *timeDim = dataFile.get_dim("time"); if (! timeDim) return false; Nc3Dim *z0Dim = dataFile.get_dim("z0"); if (! z0Dim) return false; Nc3Dim *y0Dim = dataFile.get_dim("y0"); if (! y0Dim) return false; Nc3Dim *x0Dim = dataFile.get_dim("x0"); if (! x0Dim) return false; Nc3Att *sam_idim = dataFile.get_att("sam_idim"); if (! sam_idim) return false; Nc3Att *sam_jdim = dataFile.get_att("sam_jdim"); if (! sam_jdim) return false; Nc3Att *sam_kdim = dataFile.get_att("sam_kdim"); if (! sam_kdim) return false; Nc3Att *sam_imin = dataFile.get_att("sam_imin"); if (! sam_imin) return false; Nc3Att *sam_imax = dataFile.get_att("sam_imax"); if (! sam_imax) return false; Nc3Att *sam_iincr = dataFile.get_att("sam_iincr"); if (! sam_iincr) return false; Nc3Att *sam_jmin = dataFile.get_att("sam_jmin"); if (! sam_jmin) return false; Nc3Att *sam_jmax = dataFile.get_att("sam_jmax"); if (! sam_jmax) return false; Nc3Att *sam_jincr = dataFile.get_att("sam_jincr"); if (! sam_jincr) return false; Nc3Att *sam_kmin = dataFile.get_att("sam_kmin"); if (! sam_kmin) return false; Nc3Att *sam_kmax = dataFile.get_att("sam_kmax"); if (! sam_kmax) return false; Nc3Att *sam_kincr = dataFile.get_att("sam_kincr"); if (! sam_kincr) return false; // long ntime = timeDim->size(); long nz0 = z0Dim->size(); long ny0 = y0Dim->size(); long nx0 = x0Dim->size(); Nc3Var *z0 = dataFile.get_var("z0"); if (! z0) return false; Nc3Var *y0 = dataFile.get_var("y0"); if (! y0) return false; Nc3Var *x0 = dataFile.get_var("x0"); if (! x0) return false; double *xs = new double[nx0]; double *ys = new double[ny0]; double *zs = new double[nz0]; bool success = true; if ( (xs == NULL) || (ys == NULL) || (zs == NULL) ) { std::cout << "Failed to allocate memory for Fractl grid coordinates." << std::endl; success = false; } if (success && ! z0->get(zs, nz0)) { std::cout << "Failed to read z scale." << std::endl; success = false; } if (success && ! y0->get(ys, ny0)) { std::cout << "Failed to read y scale." << std::endl; success = false; } if (success && ! x0->get(xs, nx0)) { std::cout << "Failed to read x scale." << std::endl; success = false; } if (success) { idim = sam_idim->as_long(0); jdim = sam_jdim->as_long(0); kdim = sam_kdim->as_long(0); imin = sam_imin->as_double(0); imax = sam_imax->as_double(0); iincr = sam_iincr->as_double(0); jmin = sam_jmin->as_double(0); jmax = sam_jmax->as_double(0); jincr = sam_jincr->as_double(0); kmin = sam_kmin->as_double(0); kmax = sam_kmax->as_double(0); kincr = sam_kincr->as_double(0); // TODO Do we need to read in the sigmas? // CostFunction3D reads grid dims from the configHash configHash["i_min"] = std::to_string(imin); configHash["i_max"] = std::to_string(imax); configHash["i_incr"] = std::to_string(iincr); configHash["j_min"] = std::to_string(jmin); configHash["j_max"] = std::to_string(jmax); configHash["j_incr"] = std::to_string(jincr); configHash["k_min"] = std::to_string(kmin); configHash["k_max"] = std::to_string(kmax); configHash["k_incr"] = std::to_string(kincr); success = validateGrid(); } delete[] xs; delete[] ys; delete[] zs; return success; } // Create centers at 1 second increments, from -2 seconds to +2 seconds of the computed date/time // All centers are at the given lat and lon. void VarDriver3D::fillRunCenters(char *cdtg, int delta, int iter, float lat, float lon) { // get rid of previous centers clearCenters(); // Compute ref_time // NCAR - question for CSU - do we deal with time zones other than UTC? That was specified in the original file (Qt::UTC) std::string tString; datetime cDateTime = ParseDate(cdtg, "%Y%m%d%H") + std::chrono::seconds(delta * iter); configHash.insert("ref_time", PrintTime(cDateTime)); configHash.insert("ref_lat", std::to_string(lat)); configHash.insert("ref_lat", std::to_string(lon)); // create 6 "centers" centered around the ref time, at 1 second intervals float zero = 0.0; // Framecenter constructor needs a reference... why? for(int delta2 = -2; delta2 <= 2; delta2 += 1) { datetime tTime = ParseDate(cdtg, "%Y%m%d%H") + std::chrono::seconds(delta * iter) + std::chrono::seconds(delta2); frameVector.push_back(FrameCenter(tTime, lat, lon, zero, zero)); } } // fill up variables from the config hash and call the common validateGrid() bool VarDriver3D::validateFixedGrid() { // Define the grid dimensions imin = std::stof(configHash["i_min"]); imax = std::stof(configHash["i_max"]); iincr = std::stof(configHash["i_incr"]); idim = (int)((imax - imin) / iincr) + 1; jmin = std::stof(configHash["j_min"]); jmax = std::stof(configHash["j_max"]); jincr = std::stof(configHash["j_incr"]); jdim = (int)((jmax - jmin) / jincr) + 1; kmin = std::stof(configHash["k_min"]); kmax = std::stof(configHash["k_max"]); kincr = std::stof(configHash["k_incr"]); kdim = (int)((kmax - kmin)/kincr) + 1; return validateGrid(); } bool VarDriver3D::validateGrid() { // The recursive filter uses a fourth order stencil to spread the observations, // so less than 4 gridpoints will cause a memory fault if (idim < 4) { cout << "i dimension is less than 4 gridpoints and recursive filter will fail. Aborting...\n"; return false; } if (jdim < 4) { cout << "j dimension is less than 4 gridpoints and recursive filter will fail. Aborting...\n"; return false; } if (kdim < 4) { cout << "k dimension is less than 4 gridpoints and recursive filter will fail. Aborting...\n"; return false; } // Define the sizes of the arrays we are passing to the cost function cout << "iMin\tiMax\tiIncr\tjMin\tjMax\tjIncr\tkMin\tkMax\tkIncr\n"; cout << imin << "\t" << imax << "\t" << iincr << "\t"; cout << jmin << "\t" << jmax << "\t" << jincr << "\t"; cout << kmin << "\t" << kmax << "\t" << kincr << "\n\n"; return true; } bool VarDriver3D::loadMetObs() { // Read in the meteorological observations, process them into weights and positions // Either preprocess from raw observations or load an already processed Observations.in file std::string preprocess = configHash["preprocess_obs"]; if (preprocess == "true") { bgWeights = new real[uStateSize]; bool success = preProcessMetObs(); delete[] bgWeights; if (! success) { cout << "Error pre-processing observations\n"; return false; } } else { if (!loadPreProcessMetObs()) { cout << "Error loading observations\n"; return false; } } if (obVector.size() == 0) { // No observations so quit cout << "No observations loaded, unable to perform analysis.\n"; return false; } else { cout << "Number of New Observations: " << obVector.size() << endl; } return true; } bool VarDriver3D::initObCost3D() { if (runMode == XYZ) { if (std::stof(configHash["output_pressure_increment"]) > 0) { obCost3D = new CostFunctionXYP(projection, obVector.size(), bStateSize); } else if (configHash["output_COAMPS"] == "true") { CostFunctionCOAMPS *cf = new CostFunctionCOAMPS(projection, obVector.size(), bStateSize); cf->setSigmas(sigmaTable, kdim); // TODO kdim (grid) vs. number of sigmas. Same? obCost3D = cf; } else { obCost3D = new CostFunctionXYZ(projection, obVector.size(), bStateSize); } } else if (runMode == RTZ) { obCost3D = new CostFunctionRTZ(projection, obVector.size(), bStateSize); } obCost3D->initialize(&configHash, bgU, obs, refstate); return true; } void VarDriver3D::dumpBgu() { std::cout << "------------- Dump of bgU after initialization ---------------" << std::endl; for(int64_t i = 0; i < uStateSize; i++) { if( (i % 20) == 0) std::cout << std::endl; std::cout << bgU[i] << " "; } std::cout << std::endl << "------ Done with bgU dump -----"; } void VarDriver3D::dumpBgIn() { std::cout << "------------- Dump of bgIn after initialization ---------------" << std::endl; for(int i = 0; i < bgIn.size(); i++) { if( (i % 11) == 0) std::cout << std::endl; std::cout << bgIn[i] << " "; } std::cout << std::endl << "------ Done with bgIn dump -----"; }
mmbell/samurai
src/VarDriver3D.cpp
C++
gpl-3.0
76,547
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("XCOM2 Launcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XCOM2 Launcher")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("943d3600-eb84-4ee5-aed6-74ad9e4dd978")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] // // Now handled by GitVersion //[assembly: AssemblyVersion("1.0.0.0")] //[assembly: AssemblyFileVersion("1.0.0.0")]
aEnigmatic/xcom2-launcher
xcom2-launcher/xcom2-launcher/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,547
/* * BungeeEssentials: Full customization of a few necessary features for your server! * Copyright (C) 2016 David Shen (PantherMan594) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pantherman594.gssentials.command.general; import com.google.common.collect.ImmutableSet; import com.pantherman594.gssentials.BungeeEssentials; import com.pantherman594.gssentials.Dictionary; import com.pantherman594.gssentials.Permissions; import com.pantherman594.gssentials.command.BECommand; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.TabExecutor; import java.util.Set; import java.util.UUID; /** * Created by David on 12/05. * * @author David */ @SuppressWarnings("unused") public class FriendCommand extends BECommand implements TabExecutor { public FriendCommand() { super("friend", Permissions.General.FRIEND); } @Override public void execute(CommandSender sender, String[] args) { if (sender instanceof ProxiedPlayer) { String uuid = ((ProxiedPlayer) sender).getUniqueId().toString(); Set<String> friends = pD.getFriends(uuid); if (args.length == 0 || (args.length == 1 && args[0].equalsIgnoreCase("list"))) { sender.sendMessage(Dictionary.format(Dictionary.FRIEND_HEADER, "COUNT", String.valueOf(pD.getFriends(uuid).size()))); for (String friend : friends) { String server = "Offline"; String name; if (ProxyServer.getInstance().getPlayer(UUID.fromString(friend)) != null) { server = ProxyServer.getInstance().getPlayer(UUID.fromString(friend)).getServer().getInfo().getName(); name = ProxyServer.getInstance().getPlayer(UUID.fromString(friend)).getName(); } else { name = pD.getName(friend); } sender.sendMessage(Dictionary.format(Dictionary.FRIEND_BODY, "NAME", name, "SERVER", server)); } boolean headerSent = false; Set<String> outRequests = pD.getOutRequests(uuid); for (String outRequest : outRequests) { if (!headerSent) { sender.sendMessage(Dictionary.format(Dictionary.OUTREQUESTS_HEADER, "COUNT", String.valueOf(outRequests.size()))); headerSent = true; } String name; if (ProxyServer.getInstance().getPlayer(UUID.fromString(outRequest)) != null) { name = ProxyServer.getInstance().getPlayer(UUID.fromString(outRequest)).getName(); } else { name = pD.getName(outRequest); } sender.sendMessage(Dictionary.format(Dictionary.OUTREQUESTS_BODY, "NAME", name)); } headerSent = false; Set<String> inRequests = pD.getInRequests(uuid); for (String inRequest : inRequests) { if (!headerSent) { sender.sendMessage(Dictionary.format(Dictionary.INREQUESTS_HEADER, "COUNT", String.valueOf(inRequests.size()))); headerSent = true; } String name; if (ProxyServer.getInstance().getPlayer(UUID.fromString(inRequest)) != null) { name = ProxyServer.getInstance().getPlayer(UUID.fromString(inRequest)).getName(); } else { name = pD.getName(inRequest); } sender.sendMessage(Dictionary.format(Dictionary.INREQUESTS_BODY, "NAME", name)); } } else if (args.length == 2 && (args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("accept") || args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("deny"))) { ProxiedPlayer p = ProxyServer.getInstance().getPlayer(args[1]); String friendUuid; if (p == sender) { sender.sendMessage(Dictionary.format("&cYou can't be friends with yourself!.")); } else { if (p != null) { // If the player is online, pull up the player's data. friendUuid = p.getUniqueId().toString(); } else { // If the player is offline, lookup the player's uuid and load it. friendUuid = BungeeEssentials.getInstance().getOfflineUUID(args[1]); if (friendUuid == null) { sender.sendMessage(Dictionary.format("&cError: Could not find player.")); return; } } String friendName = pD.getName(friendUuid); if (args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("accept")) { if (pD.getFriends(uuid).contains(friendUuid)) { // Tell player if they are already friends sender.sendMessage(Dictionary.format(Dictionary.FRIEND_OLD, "NAME", args[1])); } else { if (p != null && !pD.isHidden(friendUuid)) { // Will only add if player is online. if (pD.getInRequests(uuid).contains(friendUuid)) { /* * If the command sender already has an incoming request from the target player, will treat as accepting the request. * Will add as a friend on both sides and remove the requests. */ pD.removeInRequest(uuid, friendUuid); pD.addFriend(uuid, friendUuid); pD.removeOutRequest(friendUuid, uuid); pD.addFriend(friendUuid, uuid); p.sendMessage(Dictionary.format(Dictionary.FRIEND_NEW, "NAME", sender.getName())); sender.sendMessage(Dictionary.format(Dictionary.FRIEND_NEW, "NAME", p.getName())); } else if (!pD.getOutRequests(uuid).contains(friendUuid)) { // If not sender's outgoing requests already, will add. Will also add to target's incoming requests. pD.addOutRequest(uuid, friendUuid); pD.addInRequest(friendUuid, uuid); p.sendMessage(Dictionary.format(Dictionary.INREQUESTS_NEW, "NAME", sender.getName())); sender.sendMessage(Dictionary.format(Dictionary.OUTREQUESTS_NEW, "NAME", p.getName())); } else { // If none of the above true, means sender has already sent a request. sender.sendMessage(Dictionary.format(Dictionary.OUTREQUESTS_OLD, "NAME", p.getName())); } } else { sender.sendMessage(Dictionary.format(Dictionary.ERROR_PLAYER_NOT_FOUND)); } } } else { // For denying/removing if (pD.getFriends(uuid).contains(friendUuid)) { // If they are currently friends, will remove from both. pD.removeFriend(uuid, friendUuid); pD.removeFriend(friendUuid, uuid); sender.sendMessage(Dictionary.format(Dictionary.FRIEND_REMOVE, "NAME", friendName)); if (p != null) { p.sendMessage(Dictionary.format(Dictionary.FRIEND_REMOVE, "NAME", sender.getName())); } } else if (pD.getOutRequests(uuid).contains(friendUuid)) { // If sender has a pending outgoing request, will remove that and the target's incoming request. pD.removeOutRequest(uuid, friendUuid); pD.removeInRequest(friendUuid, uuid); sender.sendMessage(Dictionary.format(Dictionary.OUTREQUESTS_REMOVE, "NAME", friendName)); if (p != null) { p.sendMessage(Dictionary.format(Dictionary.INREQUESTS_REMOVE, "NAME", sender.getName())); } } else if (pD.getInRequests(uuid).contains(friendUuid)) { // If sender has incoming request, will treat as denying request. pD.removeInRequest(uuid, friendUuid); pD.removeOutRequest(friendUuid, uuid); sender.sendMessage(Dictionary.format(Dictionary.INREQUESTS_REMOVE, "NAME", friendName)); if (p != null) { p.sendMessage(Dictionary.format(Dictionary.OUTREQUESTS_REMOVE, "NAME", sender.getName())); } } else { sender.sendMessage(Dictionary.format(Dictionary.CANNOT_REMOVE_FRIEND, "NAME", friendName)); } } } } else { sender.sendMessage(Dictionary.format(Dictionary.ERROR_INVALID_ARGUMENTS, "HELP", "/" + getName() + " [list|add <player>|remove <player>]")); } } else { sender.sendMessage(Dictionary.format("&cConsole does not have any friends.")); } } @Override public Iterable<String> onTabComplete(CommandSender sender, String[] args) { switch (args.length) { case 2: return tabPlayers(sender, args[1]); case 1: return tabStrings(args[0], new String[]{"list", "add", "remove"}); default: return ImmutableSet.of(); } } }
PantherMan594/BungeeEssentials
src/main/java/com/pantherman594/gssentials/command/general/FriendCommand.java
Java
gpl-3.0
10,887
<?php /** * Piwik - free/libre analytics platform * * @link https://matomo.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ namespace Piwik\Tests\Core\DataTable\Filter; use Piwik\API\Proxy; use Piwik\Plugins\CustomVariables\CustomVariables; use Piwik\Tests\Framework\TestCase\IntegrationTestCase; use Piwik\Tracker\Cache; use Piwik\DataTable; use Piwik\DataTable\Filter\PivotByDimension; use Piwik\DataTable\Row; use Piwik\Plugin\Manager as PluginManager; use Exception; use Piwik\Translate; /** * @group DataTableTest */ class PivotByDimensionTest extends IntegrationTestCase { /** * The number of segment tables that have been created. Used when injecting API results to make sure each * segment table is different. * * @var int */ private $segmentTableCount; /** * Segment query params used to fetch intersected tables in PivotByDimension filter. Captured by mock * API\Proxy class. * * @var array */ public $segmentUsedToGetIntersected = array(); public function setUp() { parent::setUp(); Translate::reset(); Cache::clearCacheGeneral(); \Piwik\Cache::flushAll(); $this->segmentTableCount = 0; } /** * @expectedException Exception * @expectedExceptionMessage Unsupported pivot: report 'ExampleReport.getExampleReport' has no subtable dimension. */ public function test_construction_ShouldFail_WhenReportHasNoSubtableAndSegmentFetchingIsDisabled() { $this->loadPlugins('ExampleReport', 'UserCountry'); new PivotByDimension(new DataTable(), "ExampleReport.GetExampleReport", "UserCountry.City", 'nb_visits', $columnLimit = -1, $enableFetchBySegment = false); } /** * @expectedException Exception * @expectedExceptionMessage Unsupported pivot: the subtable dimension for 'Referrers.getKeywords' does not match the requested pivotBy dimension. */ public function test_construction_ShouldFail_WhenDimensionIsNotSubtableAndSegmentFetchingIsDisabled() { $this->loadPlugins('Referrers', 'UserCountry'); new PivotByDimension(new DataTable(), "Referrers.getKeywords", "UserCountry.City", "nb_visits", $columnLimit = -1, $enableFetchBySegment = false); } /** * @expectedException Exception * @expectedExceptionMessage Unsupported pivot: No segment for dimension of report 'Resolution.getConfiguration' */ public function test_construction_ShouldFail_WhenDimensionIsNotSubtableAndSegmentFetchingIsEnabledButThereIsNoSegment() { $this->loadPlugins('Referrers', 'Resolution'); new PivotByDimension(new DataTable(), "Resolution.GetConfiguration", "Referrers.Keyword", "nb_visits"); } /** * @expectedException Exception * @expectedExceptionMessage Invalid dimension 'ExampleTracker.InvalidDimension' */ public function test_construction_ShouldFail_WhenDimensionDoesNotExist() { $this->loadPlugins('ExampleReport', 'ExampleTracker'); new PivotByDimension(new DataTable(), "ExampleReport.GetExampleReport", "ExampleTracker.InvalidDimension", 'nb_visits'); } /** * @expectedException Exception * @expectedExceptionMessage Unsupported pivot: No report for pivot dimension 'ExampleTracker.ExampleDimension' */ public function test_construction_ShouldFail_WhenThereIsNoReportForADimension() { $this->loadPlugins('ExampleReport', 'ExampleTracker'); new PivotByDimension(new DataTable(), "ExampleReport.GetExampleReport", "ExampleTracker.ExampleDimension", "nb_visits"); } /** * @expectedException Exception * @expectedExceptionMessage Unable to find report 'ExampleReport.InvalidReport' */ public function test_construction_ShouldFail_WhenSpecifiedReportIsNotValid() { $this->loadPlugins('ExampleReport', 'Referrers'); new PivotByDimension(new DataTable(), "ExampleReport.InvalidReport", "Referrers.Keyword", "nb_visits"); } public function test_filter_ReturnsEmptyResult_WhenTableToFilterIsEmpty() { $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); $table = new DataTable(); $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "Referrers.SearchEngine", 'nb_visits'); $pivotFilter->filter($table); $this->assertEquals(array(), $table->getRows()); } public function test_filter_CorrectlyCreatesPivotTable_WhenUsingSubtableReport() { $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); $table = $this->getTableToFilter(true); $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "Referrers.SearchEngine", 'nb_actions', $columnLimit = -1, $fetchBySegment = false); $pivotFilter->filter($table); $expectedRows = array( array('label' => 'row 1', 'col 1' => 2, 'col 2' => false, 'col 3' => false, 'col 4' => false), array('label' => 'row 2', 'col 1' => 4, 'col 2' => 6, 'col 3' => false, 'col 4' => false), array('label' => 'row 3', 'col 1' => false, 'col 2' => 8, 'col 3' => 31, 'col 4' => 33) ); $this->assertTableRowsEquals($expectedRows, $table); } public function test_filter_CorrectlyCreatesPivotTable_WhenUsingSegment() { $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); $table = $this->getTableToFilter(true); $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "UserCountry.City", 'nb_visits'); $pivotFilter->filter($table); $expectedSegmentParams = array('referrerKeyword==row+1', 'referrerKeyword==row+2', 'referrerKeyword==row+3'); $this->assertEquals($expectedSegmentParams, $this->segmentUsedToGetIntersected); $expectedRows = array( array('label' => 'row 1', 'col 0' => 2, 'col 1' => false, 'col 2' => false), array('label' => 'row 2', 'col 0' => 2, 'col 1' => 4, 'col 2' => false), array('label' => 'row 3', 'col 0' => 2, 'col 1' => 4, 'col 2' => 6) ); $this->assertTableRowsEquals($expectedRows, $table); } /** * @backupGlobals enabled */ public function test_filter_UsesCorrectSegment_WhenPivotingSegmentedReport() { $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); $table = $this->getTableToFilter(true); $_GET['segment'] = 'asegment==value'; $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "UserCountry.City", 'nb_visits'); $pivotFilter->filter($table); $expectedSegmentParams = array( 'asegment==value;referrerKeyword==row+1', 'asegment==value;referrerKeyword==row+2', 'asegment==value;referrerKeyword==row+3' ); $this->assertEquals($expectedSegmentParams, $this->segmentUsedToGetIntersected); } public function test_filter_CorrectlyCreatesPivotTable_WhenPivotMetricDoesNotExistInTable() { $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); $table = $this->getTableToFilter(true); $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "Referrers.SearchEngine", 'invalid_metric'); $pivotFilter->filter($table); $expectedRows = array( array('label' => 'row 1', 'col 1' => false, 'col 2' => false, 'col 3' => false, 'col 4' => false), array('label' => 'row 2', 'col 1' => false, 'col 2' => false, 'col 3' => false, 'col 4' => false), array('label' => 'row 3', 'col 1' => false, 'col 2' => false, 'col 3' => false, 'col 4' => false) ); $this->assertTableRowsEquals($expectedRows, $table); } public function test_filter_CorrectlyCreatesPivotTable_WhenSubtablesHaveNoRows() { Cache::setCacheGeneral(array(CustomVariables::MAX_NUM_CUSTOMVARS_CACHEKEY => 5)); $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); $table = $this->getTableToFilter(false); $pivotFilter = new PivotByDimension($table, "CustomVariables.getCustomVariables", "CustomVariables.CustomVariableValue", 'nb_visits', $fetchBySegment = false); $pivotFilter->filter($table); $expectedRows = array( array('label' => 'row 1'), array('label' => 'row 2'), array('label' => 'row 3') ); Cache::clearCacheGeneral(); $this->assertTableRowsEquals($expectedRows, $table); } public function test_filter_CorrectlyDefaultsPivotByColumn_WhenNoneProvided() { $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); $table = $this->getTableToFilter(true); $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "Referrers.SearchEngine", $column = false, $columnLimit = -1, $fetchBySegment = false); $pivotFilter->filter($table); $expectedRows = array( array('label' => 'row 1', 'col 1' => 1, 'col 2' => false, 'col 3' => false, 'col 4' => false), array('label' => 'row 2', 'col 1' => 3, 'col 2' => 5, 'col 3' => false, 'col 4' => false), array('label' => 'row 3', 'col 1' => false, 'col 2' => 7, 'col 3' => 9, 'col 4' => 32) ); $this->assertTableRowsEquals($expectedRows, $table); } public function test_filter_CorrectlyLimitsTheColumnNumber_WhenColumnLimitProvided() { $this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables'); $table = $this->getTableToFilter(true); $pivotFilter = new PivotByDimension($table, "Referrers.getKeywords", "Referrers.SearchEngine", $column = 'nb_visits', $columnLimit = 3, $fetchBySegment = false); $pivotFilter->filter($table); $expectedRows = array( array('label' => 'row 1', 'col 2' => false, 'col 4' => false, 'Others' => 1), array('label' => 'row 2', 'col 2' => 5, 'col 4' => false, 'Others' => 3), array('label' => 'row 3', 'col 2' => 7, 'col 4' => 32, 'Others' => 9) ); $this->assertTableRowsEquals($expectedRows, $table); } private function getTableToFilter($addSubtables = false) { $row1 = new Row(array(Row::COLUMNS => array( 'label' => 'row 1', 'nb_visits' => 10, 'nb_actions' => 15 ))); if ($addSubtables) { $row1->setSubtable($this->getRow1Subtable()); } $row2 = new Row(array(Row::COLUMNS => array( 'label' => 'row 2', 'nb_visits' => 13, 'nb_actions' => 18 ))); if ($addSubtables) { $row2->setSubtable($this->getRow2Subtable()); } $row3 = new Row(array(Row::COLUMNS => array( 'label' => 'row 3', 'nb_visits' => 20, 'nb_actions' => 25 ))); if ($addSubtables) { $row3->setSubtable($this->getRow3Subtable()); } $table = new DataTable(); $table->addRowsFromArray(array($row1, $row2, $row3)); return $table; } private function getRow1Subtable() { $table = new DataTable(); $table->addRowsFromArray(array( new Row(array(Row::COLUMNS => array( 'label' => 'col 1', 'nb_visits' => 1, 'nb_actions' => 2 ))) )); return $table; } private function getRow2Subtable() { $table = new DataTable(); $table->addRowsFromArray(array( new Row(array(Row::COLUMNS => array( 'label' => 'col 1', 'nb_visits' => 3, 'nb_actions' => 4 ))), new Row(array(Row::COLUMNS => array( 'label' => 'col 2', 'nb_visits' => 5, 'nb_actions' => 6 ))) )); return $table; } private function getRow3Subtable() { $table = new DataTable(); $table->addRowsFromArray(array( new Row(array(Row::COLUMNS => array( 'label' => 'col 2', 'nb_visits' => 7, 'nb_actions' => 8 ))), new Row(array(Row::COLUMNS => array( 'label' => 'col 3', 'nb_visits' => 9, 'nb_actions' => 31 ))), new Row(array(Row::COLUMNS => array( 'label' => 'col 4', 'nb_visits' => 32, 'nb_actions' => 33 ))) )); return $table; } public function getSegmentTable() { ++$this->segmentTableCount; $table = new DataTable(); for ($i = 0; $i != $this->segmentTableCount; ++$i) { $row = new Row(array(Row::COLUMNS => array( 'label' => 'col ' . $i, 'nb_visits' => ($i + 1) * 2, 'nb_actions' => ($i + 1) * 3 ))); $table->addRow($row); } return $table; } private function assertTableRowsEquals($expectedRows, $table) { $renderer = new DataTable\Renderer\Php(); $renderer->setSerialize(false); $actualRows = $renderer->render($table); $this->assertEquals($expectedRows, $actualRows); } private function loadPlugins() { PluginManager::getInstance()->loadPlugins(func_get_args()); } public function provideContainerConfig() { $proxyMock = $this->getMockBuilder('stdClass')->setMethods(array('call'))->getMock(); $proxyMock->expects($this->any())->method('call')->willReturnCallback(function ($className, $methodName, $parameters) { if ($className == "\\Piwik\\Plugins\\UserCountry\\API" && $methodName == 'getCity' ) { $this->segmentUsedToGetIntersected[] = $parameters['segment']; return $this->getSegmentTable(); } else { throw new Exception("Unknown API request: $className::$methodName."); } }); return [ Proxy::class => $proxyMock, ]; } }
piwik/piwik
tests/PHPUnit/Integration/DataTable/Filter/PivotByDimensionTest.php
PHP
gpl-3.0
14,309