repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
OreCruncher/ThermalRecycling
src/main/java/org/blockartistry/mod/ThermalRecycling/util/Matrix2D.java
2111
/* This file is part of ThermalRecycling, licensed under the MIT License (MIT). * * Copyright (c) OreCruncher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.blockartistry.mod.ThermalRecycling.util; import com.google.common.base.Optional; /** * Quick/easy 2D matrix implementation. Backed by an array because * ArrayList<> doesn't behave in a sparse way. */ public final class Matrix2D<T> { protected final int rows; protected final int cols; protected final T[] cells; @SuppressWarnings("unchecked") public Matrix2D(final int rows, final int cols) { this.rows = rows; this.cols = cols; this.cells = (T[])new Object[rows * cols]; } public boolean isPresent(final int row, final int col) { return cells[row * cols + col] != null; } public Optional<T> get(final int row, final int col) { return Optional.of(cells[row * cols + col]); } public void set(final int row, final int col, final T obj) { cells[row * cols + col] = obj; } public int getRowCount() { return rows; } public int getColCount() { return cols; } }
mit
bdjnk/cerebral
packages/cerebral-provider-forms/src/helpers/resetForm.test.js
1110
/* eslint-env mocha */ import resetForm from './resetForm' import assert from 'assert' describe('resetForm', () => { it('should reset form', () => { const form = resetForm({ name: { value: 'Ben', defaultValue: '' } }) assert.equal(form.name.value, '') assert.equal(form.name.isPristine, true) }) it('Should reset nested Form', () => { const form = resetForm({ name: { value: '' }, address: { street: { value: 'mop', defaultValue: '' } } }) assert.equal(form.address.street.value, '') }) it('Should reset nested form arrays', () => { const form = resetForm({ name: { value: '' }, address: [ { street: { value: '' } }, { street: { value: '31 3nd Street', defaultValue: '' } } ] }) assert.equal(form.name.value, '') assert.equal(form.address[0].street.value, '') assert.equal(form.address[1].street.value, '') }) })
mit
ubpb/alma_api
spec/spec_helper.rb
687
if ENV["CODECLIMATE_REPO_TOKEN"] require "codeclimate-test-reporter" CodeClimate::TestReporter.start else require "simplecov" SimpleCov.start end require "alma_api" require "hashdiff" require "yaml" begin require "pry" rescue LoadError end RSpec.configure do |config| # begin --- rspec 3.1 generator config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end # end --- rspec 3.1 generator end def read_asset(path_to_file) File.read(File.expand_path(File.join(File.dirname(__FILE__), "assets", path_to_file))) end
mit
nelson-liu/paraphrase-id-tensorflow
tests/util/test_pooling.py
1709
import tensorflow as tf from numpy.testing import assert_allclose import numpy as np from duplicate_questions.util.pooling import mean_pool from ..common.test_case import DuplicateTestCase class TestUtilsPooling(DuplicateTestCase): def test_mean_pool_with_sequence_length(self): with tf.Session(): lstm_output = tf.constant( np.asarray([[[0.1, 0.2], [0.8, 0.9], [0.0, 0.0]], [[1.1, 1.2], [0.0, 0.0], [0.0, 0.0]], [[2.1, 2.2], [2.8, 2.9], [2.3, 2.9]]]), dtype="float32") lstm_sequence_lengths = tf.constant(np.asarray([2, 1, 3]), dtype="int32") mean_pooled_outputs = mean_pool(lstm_output, lstm_sequence_lengths) assert_allclose(mean_pooled_outputs.eval(), np.asarray([[0.45, 0.55], [1.1, 1.2], [2.4, 8 / 3]])) def test_mean_pool_without_sequence_length(self): with tf.Session(): lstm_output = tf.constant( np.asarray([[[0.1, 0.2], [0.8, 0.9], [0.0, 0.0]], [[1.1, 1.2], [0.0, 0.0], [0.0, 0.0]], [[2.1, 2.2], [2.8, 2.9], [2.3, 2.9]]]), dtype="float32") mean_pooled_outputs = mean_pool(lstm_output) assert_allclose(mean_pooled_outputs.eval(), np.asarray([[0.9 / 3, 1.1 / 3], [1.1 / 3, 1.2 / 3], [7.2 / 3, 8 / 3]]))
mit
johnny-miyake/handle_as
lib/sample/app/controllers/application_controller.rb
280
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception handle_as_gateway_timeout RuntimeError before_action ->{raise "hoge"} end
mit
Gogra/Majespay-UFC
src/Majespay/Ufc/Transaction/TransactionProcessException.php
108
<?php namespace Majespay\Ufc\Transaction; class TransactionProcessException extends \Exception { }
mit
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Objects/Get/Users/Implementations/TraktUserComment.cs
2099
namespace TraktApiSharp.Objects.Get.Users { using Basic; using Enums; using Episodes; using Lists; using Movies; using Seasons; using Shows; /// <summary>A Trakt user comment.</summary> public class TraktUserComment : ITraktUserComment { /// <summary> /// Gets or sets the object type, which this comment contains. /// See also <seealso cref="TraktObjectType" />. /// <para>Nullable</para> /// </summary> public TraktObjectType Type { get; set; } /// <summary>Gets or sets the comment's content.<para>Nullable</para></summary> public ITraktComment Comment { get; set; } /// <summary> /// Gets or sets the movie, if <see cref="Type" /> is <see cref="TraktObjectType.Movie" />. /// See also <seealso cref="ITraktMovie" />. /// <para>Nullable</para> /// </summary> public ITraktMovie Movie { get; set; } /// <summary> /// Gets or sets the show, if <see cref="Type" /> is <see cref="TraktObjectType.Episode" />. /// See also <seealso cref="ITraktShow" />. /// <para>Nullable</para> /// </summary> public ITraktShow Show { get; set; } /// <summary> /// Gets or sets the season, if <see cref="Type" /> is <see cref="TraktObjectType.Episode" />. /// See also <seealso cref="ITraktSeason" />. /// <para>Nullable</para> /// </summary> public ITraktSeason Season { get; set; } /// <summary> /// Gets or sets the episode, if <see cref="Type" /> is <see cref="TraktObjectType.Episode" />. /// See also <seealso cref="ITraktEpisode" />. /// <para>Nullable</para> /// </summary> public ITraktEpisode Episode { get; set; } /// <summary> /// Gets or sets the list, if <see cref="Type" /> is <see cref="TraktObjectType.Episode" />. /// See also <seealso cref="ITraktList" />. /// <para>Nullable</para> /// </summary> public ITraktList List { get; set; } } }
mit
Lugdunum3D/Lugdunum
src/lug/Graphics/Vulkan/API/Semaphore.cpp
1005
#include <lug/Graphics/Vulkan/API/Semaphore.hpp> #include <lug/Graphics/Vulkan/API/Device.hpp> namespace lug { namespace Graphics { namespace Vulkan { namespace API { Semaphore::Semaphore(VkSemaphore semaphore, const Device* device) : _semaphore(semaphore), _device(device) {} Semaphore::Semaphore(Semaphore&& semaphore) { _semaphore = semaphore._semaphore; _device = semaphore._device; semaphore._semaphore = VK_NULL_HANDLE; semaphore._device = nullptr; } Semaphore& Semaphore::operator=(Semaphore&& semaphore) { destroy(); _semaphore = semaphore._semaphore; _device = semaphore._device; semaphore._semaphore = VK_NULL_HANDLE; semaphore._device = nullptr; return *this; } Semaphore::~Semaphore() { destroy(); } void Semaphore::destroy() { if (_semaphore != VK_NULL_HANDLE) { vkDestroySemaphore(static_cast<VkDevice>(*_device), _semaphore, nullptr); _semaphore = VK_NULL_HANDLE; } } } // API } // Vulkan } // Graphics } // lug
mit
crowning-/dash
src/qt/dash.cpp
25069
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/dash-config.h" #endif #include "bitcoingui.h" #include "chainparams.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "intro.h" #include "net.h" #include "networkstyle.h" #include "optionsmodel.h" #include "platformstyle.h" #include "splashscreen.h" #include "utilitydialog.h" #include "winshutdownmonitor.h" #ifdef ENABLE_WALLET #include "paymentserver.h" #include "walletmodel.h" #endif #include "masternodeconfig.h" #include "init.h" #include "rpc/server.h" #include "scheduler.h" #include "ui_interface.h" #include "util.h" #include "warnings.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <stdint.h> #include <boost/filesystem/operations.hpp> #include <boost/thread.hpp> #include <QApplication> #include <QDebug> #include <QLibraryInfo> #include <QLocale> #include <QMessageBox> #include <QProcess> #include <QSettings> #include <QThread> #include <QTimer> #include <QTranslator> #include <QSslConfiguration> #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if QT_VERSION < 0x050000 Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #else #if QT_VERSION < 0x050400 Q_IMPORT_PLUGIN(AccessibleFactory) #endif #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif #endif #endif #if QT_VERSION < 0x050000 #include <QTextCodec> #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) Q_DECLARE_METATYPE(CAmount) static void InitMessage(const std::string &message) { LogPrintf("init message: %s\n", message); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("dash-core", psz).toStdString(); } static QString GetLangTerritory() { QSettings settings; // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = QLocale::system().name(); // 2) Language from QSettings QString lang_territory_qsettings = settings.value("language", "").toString(); if(!lang_territory_qsettings.isEmpty()) lang_territory = lang_territory_qsettings; // 3) -lang command line argument lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString())); return lang_territory; } /** Set up translations */ static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator) { // Remove old translators QApplication::removeTranslator(&qtTranslatorBase); QApplication::removeTranslator(&qtTranslator); QApplication::removeTranslator(&translatorBase); QApplication::removeTranslator(&translator); // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = GetLangTerritory(); // Convert to "de" only by truncating "_DE" QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in dash.qrc) if (translatorBase.load(lang, ":/translations/")) QApplication::installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in dash.qrc) if (translator.load(lang_territory, ":/translations/")) QApplication::installTranslator(&translator); } /* qDebug() message handler --> debug.log */ #if QT_VERSION < 0x050000 void DebugMessageHandler(QtMsgType type, const char *msg) { const char *category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg); } #else void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg) { Q_UNUSED(context); const char *category = (type == QtDebugMsg) ? "qt" : NULL; LogPrint(category, "GUI: %s\n", msg.toStdString()); } #endif /** Class encapsulating Dash Core startup and shutdown. * Allows running startup and shutdown in a different thread from the UI thread. */ class BitcoinCore: public QObject { Q_OBJECT public: explicit BitcoinCore(); public Q_SLOTS: void initialize(); void shutdown(); void restart(QStringList args); Q_SIGNALS: void initializeResult(int retval); void shutdownResult(int retval); void runawayException(const QString &message); private: boost::thread_group threadGroup; CScheduler scheduler; /// Pass fatal exception message to UI thread void handleRunawayException(const std::exception *e); }; /** Main Dash application object */ class BitcoinApplication: public QApplication { Q_OBJECT public: explicit BitcoinApplication(int &argc, char **argv); ~BitcoinApplication(); #ifdef ENABLE_WALLET /// Create payment server void createPaymentServer(); #endif /// parameter interaction/setup based on rules void parameterSetup(); /// Create options model void createOptionsModel(bool resetSettings); /// Create main window void createWindow(const NetworkStyle *networkStyle); /// Create splash screen void createSplashScreen(const NetworkStyle *networkStyle); /// Request core initialization void requestInitialize(); /// Request core shutdown void requestShutdown(); /// Get process return value int getReturnValue() { return returnValue; } /// Get window identifier of QMainWindow (BitcoinGUI) WId getMainWinId() const; public Q_SLOTS: void initializeResult(int retval); void shutdownResult(int retval); /// Handle runaway exceptions. Shows a message box with the problem and quits the program. void handleRunawayException(const QString &message); Q_SIGNALS: void requestedInitialize(); void requestedRestart(QStringList args); void requestedShutdown(); void stopThread(); void splashFinished(QWidget *window); private: QThread *coreThread; OptionsModel *optionsModel; ClientModel *clientModel; BitcoinGUI *window; QTimer *pollShutdownTimer; #ifdef ENABLE_WALLET PaymentServer* paymentServer; WalletModel *walletModel; #endif int returnValue; const PlatformStyle *platformStyle; std::unique_ptr<QWidget> shutdownWindow; void startThread(); }; #include "dash.moc" BitcoinCore::BitcoinCore(): QObject() { } void BitcoinCore::handleRunawayException(const std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); Q_EMIT runawayException(QString::fromStdString(GetWarnings("gui"))); } void BitcoinCore::initialize() { try { qDebug() << __func__ << ": Running AppInit2 in thread"; if (!AppInitBasicSetup()) { Q_EMIT initializeResult(false); return; } if (!AppInitParameterInteraction()) { Q_EMIT initializeResult(false); return; } if (!AppInitSanityChecks()) { Q_EMIT initializeResult(false); return; } int rv = AppInitMain(threadGroup, scheduler); Q_EMIT initializeResult(rv); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } void BitcoinCore::restart(QStringList args) { static bool executing_restart{false}; if(!executing_restart) { // Only restart 1x, no matter how often a user clicks on a restart-button executing_restart = true; try { qDebug() << __func__ << ": Running Restart in thread"; Interrupt(threadGroup); threadGroup.join_all(); StartRestart(); PrepareShutdown(); qDebug() << __func__ << ": Shutdown finished"; Q_EMIT shutdownResult(1); CExplicitNetCleanup::callCleanup(); QProcess::startDetached(QApplication::applicationFilePath(), args); qDebug() << __func__ << ": Restart initiated..."; QApplication::quit(); } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } } void BitcoinCore::shutdown() { try { qDebug() << __func__ << ": Running Shutdown in thread"; Interrupt(threadGroup); threadGroup.join_all(); Shutdown(); qDebug() << __func__ << ": Shutdown finished"; Q_EMIT shutdownResult(1); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } BitcoinApplication::BitcoinApplication(int &argc, char **argv): QApplication(argc, argv), coreThread(0), optionsModel(0), clientModel(0), window(0), pollShutdownTimer(0), #ifdef ENABLE_WALLET paymentServer(0), walletModel(0), #endif returnValue(0) { setQuitOnLastWindowClosed(false); // UI per-platform customization // This must be done inside the BitcoinApplication constructor, or after it, because // PlatformStyle::instantiate requires a QApplication std::string platformName; platformName = GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM); platformStyle = PlatformStyle::instantiate(QString::fromStdString(platformName)); if (!platformStyle) // Fall back to "other" if specified name not found platformStyle = PlatformStyle::instantiate("other"); assert(platformStyle); } BitcoinApplication::~BitcoinApplication() { if(coreThread) { qDebug() << __func__ << ": Stopping thread"; Q_EMIT stopThread(); coreThread->wait(); qDebug() << __func__ << ": Stopped thread"; } delete window; window = 0; #ifdef ENABLE_WALLET delete paymentServer; paymentServer = 0; #endif // Delete Qt-settings if user clicked on "Reset Options" QSettings settings; if(optionsModel && optionsModel->resetSettings){ settings.clear(); settings.sync(); } delete optionsModel; optionsModel = 0; delete platformStyle; platformStyle = 0; } #ifdef ENABLE_WALLET void BitcoinApplication::createPaymentServer() { paymentServer = new PaymentServer(this); } #endif void BitcoinApplication::createOptionsModel(bool resetSettings) { optionsModel = new OptionsModel(NULL, resetSettings); } void BitcoinApplication::createWindow(const NetworkStyle *networkStyle) { window = new BitcoinGUI(platformStyle, networkStyle, 0); pollShutdownTimer = new QTimer(window); connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown())); pollShutdownTimer->start(200); } void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle) { SplashScreen *splash = new SplashScreen(0, networkStyle); // We don't hold a direct pointer to the splash screen after creation, but the splash // screen will take care of deleting itself when slotFinish happens. splash->show(); connect(this, SIGNAL(splashFinished(QWidget*)), splash, SLOT(slotFinish(QWidget*))); connect(this, SIGNAL(requestedShutdown()), splash, SLOT(close())); } void BitcoinApplication::startThread() { if(coreThread) return; coreThread = new QThread(this); BitcoinCore *executor = new BitcoinCore(); executor->moveToThread(coreThread); /* communication to and from thread */ connect(executor, SIGNAL(initializeResult(int)), this, SLOT(initializeResult(int))); connect(executor, SIGNAL(shutdownResult(int)), this, SLOT(shutdownResult(int))); connect(executor, SIGNAL(runawayException(QString)), this, SLOT(handleRunawayException(QString))); connect(this, SIGNAL(requestedInitialize()), executor, SLOT(initialize())); connect(this, SIGNAL(requestedShutdown()), executor, SLOT(shutdown())); connect(window, SIGNAL(requestedRestart(QStringList)), executor, SLOT(restart(QStringList))); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), coreThread, SLOT(quit())); coreThread->start(); } void BitcoinApplication::parameterSetup() { InitLogging(); InitParameterInteraction(); } void BitcoinApplication::requestInitialize() { qDebug() << __func__ << ": Requesting initialize"; startThread(); Q_EMIT requestedInitialize(); } void BitcoinApplication::requestShutdown() { // Show a simple window indicating shutdown status // Do this first as some of the steps may take some time below, // for example the RPC console may still be executing a command. shutdownWindow.reset(ShutdownWindow::showShutdownWindow(window)); qDebug() << __func__ << ": Requesting shutdown"; startThread(); window->hide(); window->setClientModel(0); pollShutdownTimer->stop(); #ifdef ENABLE_WALLET window->removeAllWallets(); delete walletModel; walletModel = 0; #endif delete clientModel; clientModel = 0; StartShutdown(); // Request shutdown from core thread Q_EMIT requestedShutdown(); } void BitcoinApplication::initializeResult(int retval) { qDebug() << __func__ << ": Initialization result: " << retval; // Set exit result: 0 if successful, 1 if failure returnValue = retval ? 0 : 1; if(retval) { // Log this only after AppInit2 finishes, as then logging setup is guaranteed complete qWarning() << "Platform customization:" << platformStyle->getName(); #ifdef ENABLE_WALLET PaymentServer::LoadRootCAs(); paymentServer->setOptionsModel(optionsModel); #endif clientModel = new ClientModel(optionsModel); window->setClientModel(clientModel); #ifdef ENABLE_WALLET if(pwalletMain) { walletModel = new WalletModel(platformStyle, pwalletMain, optionsModel); window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel); window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET); connect(walletModel, SIGNAL(coinsSent(CWallet*,SendCoinsRecipient,QByteArray)), paymentServer, SLOT(fetchPaymentACK(CWallet*,const SendCoinsRecipient&,QByteArray))); } #endif // If -min option passed, start window minimized. if(GetBoolArg("-min", false)) { window->showMinimized(); } else { window->show(); } Q_EMIT splashFinished(window); #ifdef ENABLE_WALLET // Now that initialization/startup is done, process any command-line // dash: URIs or payment requests: connect(paymentServer, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)), window, SLOT(handlePaymentRequest(SendCoinsRecipient))); connect(window, SIGNAL(receivedURI(QString)), paymentServer, SLOT(handleURIOrFile(QString))); connect(paymentServer, SIGNAL(message(QString,QString,unsigned int)), window, SLOT(message(QString,QString,unsigned int))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); #endif } else { quit(); // Exit main loop } } void BitcoinApplication::shutdownResult(int retval) { qDebug() << __func__ << ": Shutdown result: " << retval; quit(); // Exit main loop after shutdown finished } void BitcoinApplication::handleRunawayException(const QString &message) { QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Dash Core can no longer continue safely and will quit.") + QString("\n\n") + message); ::exit(EXIT_FAILURE); } WId BitcoinApplication::getMainWinId() const { if (!window) return 0; return window->winId(); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { SetupEnvironment(); /// 1. Parse command-line options. These take precedence over anything else. // Command-line options take precedence: ParseParameters(argc, argv); // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory /// 2. Basic Qt initialization (not dependent on parameters or configuration) #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(dash); Q_INIT_RESOURCE(dash_locale); BitcoinApplication app(argc, argv); #if QT_VERSION > 0x050100 // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif #if QT_VERSION >= 0x050600 QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #ifdef Q_OS_MAC QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif #if QT_VERSION >= 0x050500 // Because of the POODLE attack it is recommended to disable SSLv3 (https://disablessl3.com/), // so set SSL protocols to TLS1.0+. QSslConfiguration sslconf = QSslConfiguration::defaultConfiguration(); sslconf.setProtocol(QSsl::TlsV1_0OrLater); QSslConfiguration::setDefaultConfiguration(sslconf); #endif // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType< bool* >(); // Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType) // IMPORTANT if it is no longer a typedef use the normal variant above qRegisterMetaType< CAmount >("CAmount"); qRegisterMetaType< std::function<void(void)> >("std::function<void(void)>"); /// 3. Application identification // must be set before OptionsModel is initialized or translations are loaded, // as it is used to locate QSettings QApplication::setOrganizationName(QAPP_ORG_NAME); QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN); QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT); GUIUtil::SubstituteFonts(GetLangTerritory()); /// 4. Initialization of translations, so that intro dialog is in user's language // Now that QSettings are accessible, initialize translations QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); translationInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) { HelpMessageDialog help(NULL, IsArgSet("-version") ? HelpMessageDialog::about : HelpMessageDialog::cmdline); help.showOrPrint(); return EXIT_SUCCESS; } /// 5. Now that settings and translations are available, ask user for data directory // User language is set up: pick a data directory if (!Intro::pickDataDirectory()) return EXIT_SUCCESS; /// 6. Determine availability of data directory and parse dash.conf /// - Do not call GetDataDir(true) before this step finishes if (!boost::filesystem::is_directory(GetDataDir(false))) { QMessageBox::critical(0, QObject::tr(PACKAGE_NAME), QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(GetArg("-datadir", "")))); return EXIT_FAILURE; } try { ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)); } catch (const std::exception& e) { QMessageBox::critical(0, QObject::tr(PACKAGE_NAME), QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what())); return EXIT_FAILURE; } /// 7. Determine network (and switch to network specific options) // - Do not call Params() before this step // - Do this after parsing the configuration file, as the network can be switched there // - QSettings() will use the new application name after this, resulting in network-specific settings // - Needs to be done before createOptionsModel // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(ChainNameFromCommandLine()); } catch(std::exception &e) { QMessageBox::critical(0, QObject::tr(PACKAGE_NAME), QObject::tr("Error: %1").arg(e.what())); return EXIT_FAILURE; } #ifdef ENABLE_WALLET // Parse URIs on command line -- this can affect Params() PaymentServer::ipcParseCommandLine(argc, argv); #endif QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString()))); assert(!networkStyle.isNull()); // Allow for separate UI settings for testnets // QApplication::setApplicationName(networkStyle->getAppName()); // moved to NetworkStyle::NetworkStyle // Re-initialize translations after changing application name (language in network-specific settings can be different) initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); #ifdef ENABLE_WALLET /// 7a. parse masternode.conf std::string strErr; if(!masternodeConfig.read(strErr)) { QMessageBox::critical(0, QObject::tr("Dash Core"), QObject::tr("Error reading masternode configuration file: %1").arg(strErr.c_str())); return EXIT_FAILURE; } /// 8. URI IPC sending // - Do this early as we don't want to bother initializing if we are just calling IPC // - Do this *after* setting up the data directory, as the data directory hash is used in the name // of the server. // - Do this after creating app and setting up translations, so errors are // translated properly. if (PaymentServer::ipcSendCommandLine()) exit(EXIT_SUCCESS); // Start up the payment server early, too, so impatient users that click on // dash: links repeatedly have their payment requests routed to this process: app.createPaymentServer(); #endif /// 9. Main GUI initialization // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); #if QT_VERSION < 0x050000 // Install qDebug() message handler to route to debug.log qInstallMsgHandler(DebugMessageHandler); #else #if defined(Q_OS_WIN) // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION) qApp->installNativeEventFilter(new WinShutdownMonitor()); #endif // Install qDebug() message handler to route to debug.log qInstallMessageHandler(DebugMessageHandler); #endif // Allow parameter interaction before we create the options model app.parameterSetup(); // Load GUI settings from QSettings app.createOptionsModel(IsArgSet("-resetguisettings")); // Subscribe to global signals from core uiInterface.InitMessage.connect(InitMessage); if (GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !GetBoolArg("-min", false)) app.createSplashScreen(networkStyle.data()); try { app.createWindow(networkStyle.data()); app.requestInitialize(); #if defined(Q_OS_WIN) && QT_VERSION >= 0x050000 WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("%1 didn't yet exit safely...").arg(QObject::tr(PACKAGE_NAME)), (HWND)app.getMainWinId()); #endif app.exec(); app.requestShutdown(); app.exec(); } catch (const std::exception& e) { PrintExceptionContinue(&e, "Runaway exception"); app.handleRunawayException(QString::fromStdString(GetWarnings("gui"))); } catch (...) { PrintExceptionContinue(NULL, "Runaway exception"); app.handleRunawayException(QString::fromStdString(GetWarnings("gui"))); } return app.getReturnValue(); } #endif // BITCOIN_QT_TEST
mit
goldrush/goldrush
app/helpers/contract_term_helper.rb
56
# -*- encoding: utf-8 -*- module ContractTermHelper end
mit
chav1961/purelib
src/main/java/chav1961/purelib/streams/char2byte/asm/macro/Macros.java
44625
package chav1961.purelib.streams.char2byte.asm.macro; import java.io.Closeable; import java.io.IOException; import java.io.Reader; import java.lang.reflect.Array; import java.util.Arrays; import chav1961.purelib.basic.AndOrTree; import chav1961.purelib.basic.exceptions.CalculationException; import chav1961.purelib.basic.exceptions.SyntaxException; import chav1961.purelib.basic.growablearrays.GrowableCharArray; import chav1961.purelib.basic.interfaces.LineByLineProcessorCallback; import chav1961.purelib.basic.interfaces.SyntaxTreeInterface; import chav1961.purelib.basic.intern.UnsafedCharUtils; import chav1961.purelib.streams.char2byte.asm.ExpressionNodeType; // Syntax of the macros: // Name .macro &positional,...,&key=[defaultValue],... // &Var .local [initialValue] // &Var .set expression // .if expression // .elseif expression // .else expression // .end // Label: .while expression // .end // Label: .for &parameter = initial to expression [step expression] // .end // .break [Label] // .continue [Label] // .choise expression // .of expression // .otherwise // .end // .merror expression // .exit // Name .mend // // Functions: // uniqueL() - locally unique number // uniqueG() - globally unique number. Doesn't change inside current macro call // exists(...) - true if parameter value exists // int(...) - convert value to integer // real(...) - convert value to real // str(...) - convert value to string // bool(...) - convert value to boolean // // Operators: // +, - , *, /, % - arithmetical operations // # - concatenation // ==, >=, <=, !=, >, < - comparison operations //// =[value,from..to,...] - in list //// ~= - match template // ? : - ternary operation // !, &&, || - logical operators // public class Macros implements LineByLineProcessorCallback, Closeable { private static final SyntaxTreeInterface<Command> COMMANDS = new AndOrTree<>(); private static final int CMD_MACRO = 0; private static final int CMD_LOCAL = 1; private static final int CMD_SET = 2; private static final int CMD_SET_INDEX = 3; private static final int CMD_IF = 4; private static final int CMD_ELSEIF = 5; private static final int CMD_ELSE = 6; private static final int CMD_ENDIF = 7; private static final int CMD_WHILE = 8; private static final int CMD_ENDWHILE = 9; private static final int CMD_FOR = 10; private static final int CMD_ENDFOR = 11; private static final int CMD_IN = 12; private static final int CMD_TO = 13; private static final int CMD_STEP = 14; private static final int CMD_FOR_ALL = 15; private static final int CMD_ENDFOR_ALL = 16; private static final int CMD_BREAK = 17; private static final int CMD_CONTINUE = 18; private static final int CMD_CHOISE = 19; private static final int CMD_ENDCHOISE = 20; private static final int CMD_OF = 21; private static final int CMD_OTHERWISE = 22; private static final int CMD_ERROR = 23; private static final int CMD_EXIT = 24; private static final int CMD_MEND = 25; private static final int FSM_BEFORE_MACRO = 0; private static final int FSM_DECLARATIONS = 1; private static final int FSM_IN_CODE = 2; private static final int FSM_AFTER_MACRO = 3; @FunctionalInterface private interface AssignWithConversion { void assign(AssignableExpressionNode node, ExpressionNode value) throws CalculationException; } private static final AssignWithConversion[][] CONV_TABLE; static { COMMANDS.placeName(".break",CMD_BREAK,null); COMMANDS.placeName(".choise",CMD_CHOISE,null); COMMANDS.placeName(".continue",CMD_CONTINUE,null); COMMANDS.placeName(".else",CMD_ELSE,null); COMMANDS.placeName(".elseif",CMD_ELSEIF,null); COMMANDS.placeName(".endchoise",CMD_ENDCHOISE,null); COMMANDS.placeName(".endfor",CMD_ENDFOR,null); COMMANDS.placeName(".endforall",CMD_ENDFOR_ALL,null); COMMANDS.placeName(".endif",CMD_ENDIF,null); COMMANDS.placeName(".endwhile",CMD_ENDWHILE,null); COMMANDS.placeName(".exit",CMD_EXIT,null); COMMANDS.placeName(".for",CMD_FOR,null); COMMANDS.placeName(".forall",CMD_FOR_ALL,null); COMMANDS.placeName(".if",CMD_IF,null); COMMANDS.placeName("in",CMD_IN,null); COMMANDS.placeName(".macro",CMD_MACRO,null); COMMANDS.placeName(".mend",CMD_MEND,null); COMMANDS.placeName(".error",CMD_ERROR,null); COMMANDS.placeName(".local",CMD_LOCAL,null); COMMANDS.placeName(".of",CMD_OF,null); COMMANDS.placeName(".otherwise",CMD_OTHERWISE,null); COMMANDS.placeName(".set",CMD_SET,null); COMMANDS.placeName(".setindex",CMD_SET_INDEX,null); COMMANDS.placeName("step",CMD_STEP,null); COMMANDS.placeName("to",CMD_TO,null); COMMANDS.placeName(".while",CMD_WHILE,null); CONV_TABLE = new AssignWithConversion[ExpressionNodeValue.class.getEnumConstants().length][ExpressionNodeValue.class.getEnumConstants().length]; CONV_TABLE[ExpressionNodeValue.BOOLEAN.ordinal()][ExpressionNodeValue.BOOLEAN.ordinal()] = (to,from) -> to.assign(from.getBoolean()); CONV_TABLE[ExpressionNodeValue.BOOLEAN.ordinal()][ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN.ordinal()][ExpressionNodeValue.INTEGER.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN.ordinal()][ExpressionNodeValue.INTEGER_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN.ordinal()][ExpressionNodeValue.REAL.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN.ordinal()][ExpressionNodeValue.REAL_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN.ordinal()][ExpressionNodeValue.STRING.ordinal()] = (to,from) -> to.assign(new ConstantNode(Boolean.valueOf(new String(from.getString())))); CONV_TABLE[ExpressionNodeValue.BOOLEAN.ordinal()][ExpressionNodeValue.STRING_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()][ExpressionNodeValue.BOOLEAN.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()][ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()] = (to,from) -> to.assign(from); CONV_TABLE[ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()][ExpressionNodeValue.INTEGER.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()][ExpressionNodeValue.INTEGER_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()][ExpressionNodeValue.REAL.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()][ExpressionNodeValue.REAL_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()][ExpressionNodeValue.STRING.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()][ExpressionNodeValue.STRING_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER.ordinal()][ExpressionNodeValue.BOOLEAN.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER.ordinal()][ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER.ordinal()][ExpressionNodeValue.INTEGER.ordinal()] = (to,from) -> to.assign(from.getLong()); CONV_TABLE[ExpressionNodeValue.INTEGER.ordinal()][ExpressionNodeValue.INTEGER_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER.ordinal()][ExpressionNodeValue.REAL.ordinal()] = (to,from) -> to.assign((long)from.getDouble()); CONV_TABLE[ExpressionNodeValue.INTEGER.ordinal()][ExpressionNodeValue.REAL_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER.ordinal()][ExpressionNodeValue.STRING.ordinal()] = (to,from) -> to.assign(Long.valueOf(new String(from.getString())).longValue()); CONV_TABLE[ExpressionNodeValue.INTEGER.ordinal()][ExpressionNodeValue.STRING_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER_ARRAY.ordinal()][ExpressionNodeValue.BOOLEAN.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER_ARRAY.ordinal()][ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER_ARRAY.ordinal()][ExpressionNodeValue.INTEGER.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER_ARRAY.ordinal()][ExpressionNodeValue.INTEGER_ARRAY.ordinal()] = (to,from) -> to.assign(from); CONV_TABLE[ExpressionNodeValue.INTEGER_ARRAY.ordinal()][ExpressionNodeValue.REAL.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER_ARRAY.ordinal()][ExpressionNodeValue.REAL_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER_ARRAY.ordinal()][ExpressionNodeValue.STRING.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.INTEGER_ARRAY.ordinal()][ExpressionNodeValue.STRING_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL.ordinal()][ExpressionNodeValue.BOOLEAN.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL.ordinal()][ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL.ordinal()][ExpressionNodeValue.INTEGER.ordinal()] = (to,from) -> to.assign((double)from.getLong()); CONV_TABLE[ExpressionNodeValue.REAL.ordinal()][ExpressionNodeValue.INTEGER_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL.ordinal()][ExpressionNodeValue.REAL.ordinal()] = (to,from) -> to.assign(from.getDouble()); CONV_TABLE[ExpressionNodeValue.REAL.ordinal()][ExpressionNodeValue.REAL_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL.ordinal()][ExpressionNodeValue.STRING.ordinal()] = (to,from) -> to.assign(Double.valueOf(new String(from.getString())).doubleValue()); CONV_TABLE[ExpressionNodeValue.REAL.ordinal()][ExpressionNodeValue.STRING_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL_ARRAY.ordinal()][ExpressionNodeValue.BOOLEAN.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL_ARRAY.ordinal()][ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL_ARRAY.ordinal()][ExpressionNodeValue.INTEGER.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL_ARRAY.ordinal()][ExpressionNodeValue.INTEGER_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL_ARRAY.ordinal()][ExpressionNodeValue.REAL.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL_ARRAY.ordinal()][ExpressionNodeValue.REAL_ARRAY.ordinal()] = (to,from) -> to.assign(from); CONV_TABLE[ExpressionNodeValue.REAL_ARRAY.ordinal()][ExpressionNodeValue.STRING.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.REAL_ARRAY.ordinal()][ExpressionNodeValue.STRING_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING.ordinal()][ExpressionNodeValue.BOOLEAN.ordinal()] = (to,from) -> to.assign(Boolean.valueOf(from.getBoolean()).toString().toCharArray()); CONV_TABLE[ExpressionNodeValue.STRING.ordinal()][ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING.ordinal()][ExpressionNodeValue.INTEGER.ordinal()] = (to,from) -> to.assign(Long.valueOf(from.getLong()).toString().toCharArray()); CONV_TABLE[ExpressionNodeValue.STRING.ordinal()][ExpressionNodeValue.INTEGER_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING.ordinal()][ExpressionNodeValue.REAL.ordinal()] = (to,from) -> to.assign(Double.valueOf(from.getDouble()).toString().toCharArray());; CONV_TABLE[ExpressionNodeValue.STRING.ordinal()][ExpressionNodeValue.REAL_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING.ordinal()][ExpressionNodeValue.STRING.ordinal()] = (to,from) -> to.assign(from.getString()); CONV_TABLE[ExpressionNodeValue.STRING.ordinal()][ExpressionNodeValue.STRING_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING_ARRAY.ordinal()][ExpressionNodeValue.BOOLEAN.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING_ARRAY.ordinal()][ExpressionNodeValue.BOOLEAN_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING_ARRAY.ordinal()][ExpressionNodeValue.INTEGER.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING_ARRAY.ordinal()][ExpressionNodeValue.INTEGER_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING_ARRAY.ordinal()][ExpressionNodeValue.REAL.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING_ARRAY.ordinal()][ExpressionNodeValue.REAL_ARRAY.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING_ARRAY.ordinal()][ExpressionNodeValue.STRING.ordinal()] = (to,from) -> throwConvException(to,from); CONV_TABLE[ExpressionNodeValue.STRING_ARRAY.ordinal()][ExpressionNodeValue.STRING_ARRAY.ordinal()] = (to,from) -> to.assign(from); } private Command[] stack = new Command[16]; private int stackTop = -1; private int fsmState = FSM_BEFORE_MACRO; private MacroCommand root = null; private MacroExecutorInterface exec; public Macros() { } @Override public void close() throws IOException { // TODO Auto-generated method stub } @Override public void processLine(final long displacement, final int lineNo, final char[] data, int from, final int length) throws IOException, SyntaxException { final int to = from+length, begin = from; char[] name; int start = from; boolean isLabel = false, hasName = false; if (data[from] > ' ') { // Process name (the same first column is non-blank) final int[] bounds = new int[2]; try{from = UnsafedCharUtils.uncheckedParseName(data,from,bounds); from = InternalUtils.skipBlank(data,from); hasName = true; if (data[from] == ':') { isLabel = true; from = InternalUtils.skipBlank(data,from+1); } name = Arrays.copyOfRange(data,bounds[0],bounds[1]+1); } catch (IllegalArgumentException exc) { name = null; } } else { from = start = InternalUtils.skipBlank(data,from); name = null; } try{start = from; from = InternalUtils.skipNonBlank(data,from); if (from == start) { if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } stack[stackTop].append(lineNo,new SubstitutionCommand().processCommand(lineNo,begin,data,begin,to,(MacroCommand)stack[0])); fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,"macro string outside .macro"); } } else { switch ((int)COMMANDS.seekName(data,start,from)) { case CMD_MACRO : if (fsmState == FSM_BEFORE_MACRO) { if (!hasName) { throw new SyntaxException(lineNo,from-begin,".macro doesn't have name. Name must start from the same first position in the line!"); } else if (isLabel) { throw new SyntaxException(lineNo,from-begin,".macro has label instead of name! Remove (:)"); } else { push(new MacroCommand(name).processCommand(lineNo,begin,data,from,to,null)); fsmState = FSM_DECLARATIONS; } } else { throw new SyntaxException(lineNo,from-begin,".macro inside .macro! Possibly .mend was loosed?"); } break; case CMD_LOCAL : if (fsmState == FSM_DECLARATIONS) { if (!hasName) { throw new SyntaxException(lineNo,from-begin,".local doesn't have name. Name must start from the same first position in the line!"); } else if (isLabel) { throw new SyntaxException(lineNo,from-begin,".local has label instead of name! Remove (:)"); } else if (stack[stackTop].getType() != CommandType.MACRO) { throw new SyntaxException(lineNo,from-begin,".local can't be used inside nested operators!"); } else { final int bounds[] = new int[2], number[] = new int[1]; final boolean isArray; from = InternalUtils.skipBlank(data,from); if (Character.isJavaIdentifierStart(data[from])) { final int size; from = InternalUtils.skipBlank(data,UnsafedCharUtils.uncheckedParseName(data,from,bounds)); if (data[from] == '[') { from = InternalUtils.skipBlank(data,from+1); if (data[from] == ']') { from++; isArray = true; size = -1; } else if (data[from] >= '0' && data[from] <= '9') { from = UnsafedCharUtils.uncheckedParseInt(data, from, number, true); if (data[from] == ']') { from++; isArray = true; size = number[0]; } else { throw new SyntaxException(lineNo,from-begin,"illegal brackets []"); } } else { throw new SyntaxException(lineNo,from-begin,"illegal brackets []"); } } else { isArray = false; size = -1; } from = InternalUtils.skipBlank(data,from); if (data[from] == '=') { final ExpressionNode[] value = new ExpressionNode[1]; final AssignableExpressionNode var = new LocalVariable(name,InternalUtils.defineType(data,bounds,isArray)); if (isArray) { InternalUtils.parseExpressionList(InternalUtils.ORDER_OR,lineNo,data,begin,from+1,(MacroCommand)stack[0],var.getValueType(),value); setInitialValue(var,value[0]); } else { InternalUtils.parseExpression(InternalUtils.ORDER_OR,lineNo,data,begin,from+1,(MacroCommand)stack[0],value); setInitialValue(var,value[0]); } ((MacroCommand)stack[stackTop]).addDeclaration(var); } else if (isArray) { if (size == -1) { throw new SyntaxException(lineNo,from-begin,"Neither array size nor initials for local array variable"); } else { final ExpressionNodeValue valType = InternalUtils.defineType(data,bounds,isArray); final ExpressionNode value; switch (valType) { case BOOLEAN_ARRAY : value = new ConstantNode(new boolean[size]); break; case INTEGER_ARRAY : value = new ConstantNode(new long[size]); break; case REAL_ARRAY : value = new ConstantNode(new double[size]); break; case STRING_ARRAY : value = new ConstantNode(new char[size][]); break; default : throw new UnsupportedOperationException("Value type ["+valType+"] is not supported yet"); } ((MacroCommand)stack[stackTop]).addDeclaration(new LocalVariable(name,valType,value)); } } else { ((MacroCommand)stack[stackTop]).addDeclaration(new LocalVariable(name,InternalUtils.defineType(data,bounds,isArray))); } } else { throw new SyntaxException(lineNo,from-begin,".local declaration doesn't have legal name"); } } } else { throw new SyntaxException(lineNo,from-begin,"all .local declarations must immediately follow .macro entity"); } break; case CMD_SET : if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { final AssignableExpressionNode leftPart; if ((leftPart = ((MacroCommand)stack[0]).seekDeclaration(name)) == null) { throw new SyntaxException(lineNo,from-begin,"Undeclared left name in the .set operator."); } else { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } stack[stackTop].append(lineNo,new SetCommand(leftPart).processCommand(lineNo,begin,data,from,to,(MacroCommand)stack[0])); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".set operator outside .macro"); } break; case CMD_SET_INDEX : if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { final AssignableExpressionNode leftPart; if ((leftPart = ((MacroCommand)stack[0]).seekDeclaration(name)) == null) { throw new SyntaxException(lineNo,from-begin,"Undeclared left name in the .set operator."); } else { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } stack[stackTop].append(lineNo,new SetIndexCommand(leftPart).processCommand(lineNo,begin,data,from,to,(MacroCommand)stack[0])); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".set operator outside .macro"); } break; case CMD_IF : if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".if doesn't use with name/label"); } else { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } final Command ifCond = new IfConditionCommand().processCommand(lineNo,begin,data,from,to,(MacroCommand)stack[0]); push(new IfContainer()); push(ifCond); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".if operator outside .macro"); } break; case CMD_ELSEIF : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".elseif doesn't use with name/label"); } else if (!(stack[stackTop] instanceof IfConditionCommand)) { throw new SyntaxException(lineNo,from-begin,".elseif without .if"); } else { final Command ifCmd = new IfConditionCommand().processCommand(lineNo,begin,data,from,to,(MacroCommand)stack[0]); ((IfContainer)stack[stackTop-1]).append(lineNo,pop()); push(ifCmd); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".elseif operator outside context"); } break; case CMD_ELSE : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".else doesn't use with name/label"); } else if (!(stack[stackTop] instanceof IfConditionCommand)) { throw new SyntaxException(lineNo,from-begin,".elseif without .if"); } else { ((IfContainer)stack[stackTop-1]).append(lineNo,pop()); push(new ElseCommand()); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".else operator outside context"); } break; case CMD_ENDIF : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".endif doesn't use with name/label"); } else if (((stack[stackTop] instanceof IfConditionCommand) || (stack[stackTop] instanceof ElseCommand))&& (stack[stackTop-1] instanceof IfContainer)) { stack[stackTop-1].append(lineNo,pop()); stack[stackTop-1].append(lineNo,pop()); } else if (stack[stackTop] instanceof ForCommand) { stack[stackTop-1].append(lineNo,pop()); } else { throw new SyntaxException(lineNo,from-begin,".endif operator outside any context"); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".endif operator outside any context"); } break; case CMD_WHILE : if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { if (hasName && !isLabel) { throw new SyntaxException(lineNo,from-begin,".while doesn't use with name. Possibly label?"); } else if (hasName && isLabel) { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } push(new WhileCommand(name).processCommand(lineNo,begin,data,from,to,(MacroCommand)stack[0])); } else { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } push(new WhileCommand().processCommand(lineNo,begin,data,from,to,(MacroCommand)stack[0])); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".while operator outside .macro"); } break; case CMD_ENDWHILE : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".endwhile doesn't use with name/label"); } else if (stack[stackTop] instanceof WhileCommand) { stack[stackTop-1].append(lineNo,pop()); } else { throw new SyntaxException(lineNo,from-begin,".endwhile operator outside any context"); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".endwhile operator outside any context"); } break; case CMD_FOR : if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { if (hasName && !isLabel) { throw new SyntaxException(lineNo,from-begin,".for doesn't use with name. Possibly label?"); } else if (hasName && isLabel) { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } push(new ForCommand(name).processCommand(lineNo,begin,data,from,to,(MacroCommand)stack[0])); } else { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } push(new ForCommand().processCommand(lineNo,begin,data,from,to,(MacroCommand)stack[0])); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".for operator outside .macro"); } break; case CMD_ENDFOR : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".endfor doesn't use with name/label"); } else if (stack[stackTop] instanceof ForCommand) { stack[stackTop-1].append(lineNo,pop()); } else { throw new SyntaxException(lineNo,from-begin,".endfor operator outside any context"); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".endfor operator outside any context"); } break; case CMD_FOR_ALL : if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { if (hasName && !isLabel) { throw new SyntaxException(lineNo,from-begin,".for doesn't use with name. Possibly label?"); } else if (hasName && isLabel) { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } push(new ForCommand(name).processCommand(lineNo,begin,data,from,to,(MacroCommand)stack[0])); } else { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } push(new ForEachCommand().processCommand(lineNo,begin,data,from,to,(MacroCommand)stack[0])); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".for operator outside .macro"); } break; case CMD_ENDFOR_ALL : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".endforall doesn't use with name/label"); } else if (stack[stackTop] instanceof ForEachCommand) { stack[stackTop-1].append(lineNo,pop()); } else { throw new SyntaxException(lineNo,from-begin,".endforall operator outside any context"); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".endforall operator outside any context"); } break; case CMD_BREAK : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".break doesn't use with name/label"); } else { final BreakCommand cmd = new BreakCommand().processCommand(lineNo,begin,data, InternalUtils.skipBlank(data,from),to,(MacroCommand)stack[0]); if (cmd.getLabel() != null && !seekLabel(cmd.getLabel())) { throw new SyntaxException(lineNo,from-begin,".break: label referenced not found anywhere"); } boolean found = false; for (int index = stackTop; index > 0; index--) { if (stack[index] instanceof LoopCommand) { found = true; stack[stackTop].append(lineNo,cmd); break; } } if (!found) { throw new SyntaxException(lineNo,from-begin,".break outside the loop"); } } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".break operator outside context"); } break; case CMD_CONTINUE : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".continue doesn't use with name/label"); } else { final ContinueCommand cmd = new ContinueCommand().processCommand(lineNo,begin,data, InternalUtils.skipBlank(data,from),to,(MacroCommand)stack[0]); if (cmd.getLabel() != null && !seekLabel(cmd.getLabel())) { throw new SyntaxException(lineNo,from-begin,".continue: label referenced not found anywhere"); } boolean found = false; for (int index = stackTop; index > 0; index--) { if (stack[index] instanceof LoopCommand) { found = true; stack[stackTop].append(lineNo,cmd); break; } } if (!found) { throw new SyntaxException(lineNo,from-begin,".break outside the loop"); } } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".continue operator outside context"); } break; case CMD_CHOISE : if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".choise doesn't use with name/label"); } else { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } push(new ChoiseContainer().processCommand(lineNo,begin,data,InternalUtils.skipBlank(data,from),to,(MacroCommand)stack[0])); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".choise operator outside .macro"); } break; case CMD_ENDCHOISE : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".endchoise doesn't use with name/label"); } if (((stack[stackTop] instanceof ChoiseConditionCommand) || (stack[stackTop] instanceof OtherwiseCommand))&& (stack[stackTop-1] instanceof ChoiseContainer)) { stack[stackTop-1].append(lineNo,pop()); stack[stackTop-1].append(lineNo,pop()); } else { throw new SyntaxException(lineNo,from-begin,".endchoise operator outside any context"); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".endchoise operator outside any context"); } break; case CMD_OF : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".of doesn't use with name/label"); } else if (stack[stackTop] instanceof ChoiseContainer) { final Command cmd = new ChoiseConditionCommand().processCommand(lineNo,begin,data,InternalUtils.skipBlank(data,from),to,(MacroCommand)stack[0]); push(cmd); } else if (stack[stackTop] instanceof ChoiseConditionCommand) { final ChoiseConditionCommand cmd = new ChoiseConditionCommand().processCommand(lineNo,begin,data,InternalUtils.skipBlank(data,from),to,(MacroCommand)stack[0]); if (((ChoiseContainer)stack[stackTop-1]).expr[0].getValueType() != cmd.value[0].getValueType()) { throw new SyntaxException(lineNo,from-begin,"Value type in the .of clause is differ than value type of the .choise expression! Use convert functions!"); } else { stack[stackTop-1].append(lineNo,pop()); push(cmd); } } else { throw new SyntaxException(lineNo,from-begin,".of without .choise"); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".of operator outside context"); } break; case CMD_OTHERWISE : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".otherwise doesn't use with name/label"); } else if (!(stack[stackTop] instanceof ChoiseConditionCommand)) { throw new SyntaxException(lineNo,from-begin,".otherwise without .choise"); } else { ((ChoiseContainer)stack[stackTop-1]).append(lineNo,pop()); push(new OtherwiseCommand()); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".otherwise operator outside context"); } break; case CMD_ERROR : if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".merror doesn't use with name/label"); } else { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } stack[stackTop].append(lineNo,new MErrorCommand().processCommand(lineNo,begin,data,InternalUtils.skipBlank(data,from),to,(MacroCommand)stack[0])); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".merror operator outside context"); } break; case CMD_EXIT : if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".exit doesn't use with name/label"); } else { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } stack[stackTop].append(lineNo,new ExitCommand()); } fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,".exit operator outside context"); } break; case CMD_MEND : if (fsmState == FSM_IN_CODE) { if (hasName || isLabel) { throw new SyntaxException(lineNo,from-begin,".mend doesn't use with name/label"); } else if ((stackTop == 0) && (stack[stackTop] instanceof MacroCommand)){ root = (MacroCommand)pop(); } else { throw new SyntaxException(lineNo,0,".mend: there are ["+stackTop+"] unclosed operators in the macro"); } fsmState = FSM_AFTER_MACRO; } else if (fsmState == FSM_DECLARATIONS) { throw new SyntaxException(lineNo,from-begin,".mend: empty .macro body was detected"); } else { throw new SyntaxException(lineNo,from-begin,".mend operator outside .macro"); } break; default : // String to substitute if (fsmState == FSM_DECLARATIONS || fsmState == FSM_IN_CODE) { if (fsmState == FSM_DECLARATIONS) { ((MacroCommand)stack[0]).commitDeclarations(); } stack[stackTop].append(lineNo,new SubstitutionCommand().processCommand(lineNo,begin,data,begin,to,(MacroCommand)stack[0])); fsmState = FSM_IN_CODE; } else { throw new SyntaxException(lineNo,from-begin,"macro string outside .macro"); } break; } } } catch (IllegalArgumentException | CalculationException exc) { exc.printStackTrace(); throw new SyntaxException(lineNo,from-begin,exc.getLocalizedMessage()); } } public Reader processCall(final int lineNo, final char[] data, int from, final int length) throws IOException, SyntaxException { final MacroCommand cmd = parseCall(lineNo,data,from,length); final GrowableCharArray<?> gca = new GrowableCharArray<>(false); try{exec.exec(cmd.getDeclarations(),gca); } catch (CalculationException exc) { exc.printStackTrace(); throw new IOException("Macro "+new String(cmd.getName())+": "+exc.getLocalizedMessage()); } return gca.getReader(); } MacroCommand parseCall(final int lineNo, final char[] data, int from, final int length) throws IOException, SyntaxException { final MacroCommand cmd = root.clone(); final ExpressionNode[] val = new ExpressionNode[1]; final int[] bounds = new int[2]; int positional = 0; try{from--; loop: do {if ((from = InternalUtils.skipCallEntity(data,InternalUtils.skipBlank(data,from+1),bounds)) >= data.length) { break; } switch (data[from]) { case '\r' : case '\n' : if (bounds[1] >= bounds[0]) { if (positional >= root.getDeclarations().length) { throw new SyntaxException(lineNo,from,"Too many parameters in the macro call!"); } else if (root.getDeclarations()[positional].getType() != ExpressionNodeType.POSITIONAL_PARAMETER) { throw new SyntaxException(lineNo,from,"Too many positional parameters in the macro call!"); } else { InternalUtils.parseConstant(data, bounds[0], true, true, cmd.getDeclarations()[positional].getValueType(), val); cmd.getDeclarations()[positional].assign(val[0]); positional++; } } break loop; case ',' : if (bounds[1] >= bounds[0]) { if (positional >= root.getDeclarations().length) { throw new SyntaxException(lineNo,from,"Too many parameters in the macro call!"); } else if (root.getDeclarations()[positional].getType() != ExpressionNodeType.POSITIONAL_PARAMETER) { throw new SyntaxException(lineNo,from,"Too many positional parameters in the macro call!"); } else { final AssignableExpressionNode node = cmd.getDeclarations()[positional]; from = InternalUtils.parseConstant(data, bounds[0], true, true, cmd.getDeclarations()[positional].getValueType(), val); if (node.getValueType().isArray()) { if (val[0].getValueType().isArray()) { node.assign(val[0]); } else { node.assign(new ConstantNode(node.getValueType(), val[0])); } } else { node.assign(val[0]); } positional++; } } else { // Skipped positional parameter if (positional >= root.getDeclarations().length) { throw new SyntaxException(lineNo,from,"Too many parameters in the macro call!"); } else if (root.getDeclarations()[positional].getType() != ExpressionNodeType.POSITIONAL_PARAMETER) { throw new SyntaxException(lineNo,from,"Too many positional parameters in the macro call!"); } else { // InternalUtils.parseConstant(data,bounds[0],true,val); // cmd.getDeclarations()[positional].assign(val[0]); positional++; } } continue loop; case '=' : final char[] keyName = Arrays.copyOfRange(data,bounds[0],bounds[1]+1); final AssignableExpressionNode key = cmd.seekDeclaration(keyName); if (key != null && key.getType() == ExpressionNodeType.KEY_PARAMETER) { from = InternalUtils.parseConstant(data, InternalUtils.skipBlank(data,from+1), true, true, key.getValueType(), val); if (key.getValueType().isArray()) { if (val[0].getValueType().isArray()) { setInitialValue(key,val[0]); } else { setInitialValue(key,new ConstantNode(key.getValueType(), val[0])); } } else { setInitialValue(key,val[0]); } } else { throw new SyntaxException(lineNo,from,"Unknown key parameter ["+new String(keyName)+"]"); } break; default : throw new SyntaxException(lineNo,from,"Illegal symbol in the macro call"); } from = InternalUtils.skipBlank(data,from); } while (from < data.length && data[from] == ','); } catch (CalculationException | IllegalArgumentException exc) { exc.printStackTrace(); throw new SyntaxException(lineNo,from,exc.getLocalizedMessage(),exc); } return cmd; } @SuppressWarnings("exports") public MacroCommand getRoot() { return root; } public void compile(final MacroExecutorInterface executor) { this.exec = executor; } public boolean isPrepared() { return root != null; } public char[] getName() { if (!isPrepared()) { throw new IllegalStateException("Attempt to get macro name for unprepared macro"); } else { return root.getName(); } } private void push(final Command command) { if (stackTop >= stack.length-1) { stack = Arrays.copyOf(stack,2*stack.length); } stack[++stackTop] = command; } private Command pop() { return stack[stackTop--]; } private boolean seekLabel(final char[] label) { for (int index = stackTop; index > 0; index--) { if (stack[index] instanceof LoopCommand) { final char[] templ = ((LoopCommand)stack[index]).getLabel(); if (UnsafedCharUtils.uncheckedCompare(label,0,templ,0,templ.length)) { return true; } } } return false; } private void setInitialValue(final AssignableExpressionNode node, final ExpressionNode value) throws CalculationException { CONV_TABLE[node.getValueType().ordinal()][value.getValueType().ordinal()].assign(node, value); } private static void throwConvException(final AssignableExpressionNode to, final ExpressionNode from) throws CalculationException { throw new CalculationException("Illegal conversion from ["+from.getValueType()+"] to ["+to.getValueType()+"]"); } }
mit
choijun/Javier-Package-Demo
importer/importer.php
33591
<?php defined( 'ABSPATH' ) or die( 'No script kiddies please!' ); if(!class_exists('WXR_Importer')){ require dirname( __FILE__ ) . '/verdor/humanmade/WordPress-Importer/plugin.php'; } //defined('IMPORT_DEBUG') or define('IMPORT_DEBUG', true); class LaStudio_Importer { protected $fetch_attachments = true; protected $demo_data, $current_id, $setting_args, $wxr_import, $theme_name; protected $logger = null; private static $instance = null; public static function instance() { if ( null === static::$instance ) { static::$instance = new static(); } return static::$instance; } protected function __construct() { $this->set_logger(); $this->theme_name = sanitize_key(wp_get_theme()->get('Name')); add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) ); add_action( 'init', array( $this, 'setup_plugin_data' ) ); add_action( 'wp_ajax_lastudio-importer', array( $this, 'action_process_importer' ) ); add_filter( 'LaStudio_Importer/widgets/widget_setting_object', array( $this, 'fixed_nav_menu_widget_settings' ) ); } public static function admin_enqueue_scripts(){ wp_register_script( 'eventsource', plugin_dir_url( __FILE__ ) . 'assets/js/eventsource.js' ); wp_enqueue_script( 'lastudio-importer-js', plugin_dir_url( __FILE__ ) . 'assets/js/import.js' , array( 'jquery', 'eventsource' ) ); wp_localize_script( 'lastudio-importer-js', 'lastudio_importer', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'ajax_nonce' => wp_create_nonce( 'lastudio-importer-security' ), 'loader_text' => esc_html__( 'Importing now, please wait!', LA_TEXTDOMAIN ), ) ); wp_enqueue_style( 'lastudio-importer-css', plugin_dir_url( __FILE__ ) . 'assets/css/import.css', array() ); } public static function fixed_nav_menu_widget_settings( $widgets ) { if(isset($widgets->nav_menu)){ $nav_menu = wp_get_nav_menu_object($widgets->nav_menu); if(isset($nav_menu->term_id)){ $widgets->nav_menu = $nav_menu->term_id; } } return $widgets; } /** * Get data from filters, after the theme has loaded and instantiate the importer. */ public function setup_plugin_data(){ // Get info of import data files and filter it. $this->demo_data = apply_filters( 'javier/filter/demo_data', array() ); } public function get_demo_data(){ return $this->demo_data; } public function action_process_importer(){ if( false === check_ajax_referer( 'lastudio-importer-security', 'security', false ) ) { wp_send_json( __( 'Access define!', LA_TEXTDOMAIN ) ); } if( !current_user_can( 'import' ) ) { wp_send_json( __( 'Access define!', LA_TEXTDOMAIN ) ); } $id = isset( $_REQUEST['id'] ) ? $_REQUEST['id'] : false; $args = shortcode_atts( array( 'content' => true, 'widget' => true, 'slider' => true, 'option' => true, 'fetch_attachments' => true ), isset($_REQUEST['args']) ? $_REQUEST['args'] : array() ); if( empty( $id ) || !array_key_exists( $id, $this->demo_data ) ) { wp_send_json( __( 'Access define!', LA_TEXTDOMAIN ) ); } $this->current_id = $id; $this->setting_args = $args; $this->wxr_import = $this->get_importer(); if(isset($_REQUEST['start_import']) && $_REQUEST['start_import'] == 'true' && !empty($this->current_id) && !empty($this->demo_data) && !empty($this->wxr_import)){ do_action('LaStudio_Importer/copy_image'); add_filter( 'intermediate_image_sizes_advanced', '__return_null' ); add_filter( 'wxr_importer.pre_process.post', array( $this, 'modify_post_author_when_using_ajax'), 10, 4 ); $this->_start_import_stream(); } elseif(!empty($_REQUEST['start_import_without_content']) && $_REQUEST['start_import_without_content'] == 'true' && !empty($this->current_id) && !empty($this->demo_data)){ $this->_start_import_stream_without_content(); } else{ if(!isset($this->importer_is_running)){ $this->_start_ajax_importer_handling(); } } } protected function set_logger(){ $this->logger = new WP_Importer_Logger_ServerSentEvents(); } protected function _start_ajax_importer_handling(){ /** * Check data-sample.xml has imported */ $opts = get_option($this->theme_name . '_imported_demos'); if(!empty($opts)){ /* * If content has been imported. We need import theme options, custom setting, slider ... etc. */ if( array_key_exists($this->current_id, $opts) ) { $this->setting_args = array( 'content' => false, 'widget' => false, 'slider' => false, 'option' => true, 'fetch_attachments' => true ); } $ajax_import_url = add_query_arg( array( 'action' => 'lastudio-importer', 'id' => $this->current_id, 'args' => $this->setting_args, 'security' => $_REQUEST['security'], 'start_import_without_content' => 'true' ), admin_url( 'admin-ajax.php' ) ); } else{ $ajax_import_url = add_query_arg( array( 'action' => 'lastudio-importer', 'id' => $this->current_id, 'args' => $this->setting_args, 'security' => $_REQUEST['security'], 'start_import' => 'true' ), admin_url( 'admin-ajax.php' ) ); } $xml_data = $this->_get_data_for_demo(); $mapping = $this->get_author_mapping(); $fetch_attachments = ( ! empty( $this->setting_args['fetch_attachments'] ) && $this->setting_args['fetch_attachments'] && $this->allow_fetch_attachments() ); $this->fetch_attachments = $fetch_attachments; $settings = compact( 'mapping', 'fetch_attachments' ); update_option('_wxr_import_settings', $settings); wp_send_json(array( 'status' => 'success', 'data' => array( 'count' => array( 'posts' => $xml_data->post_count, 'media' => $xml_data->media_count, 'users' => count( $xml_data->users ), 'comments' => $xml_data->comment_count, 'terms' => $xml_data->term_count, ), 'url' => $ajax_import_url, 'strings' => array( 'complete' => __( 'Import complete!', LA_TEXTDOMAIN ), ) ) )); } protected function _get_data_for_demo(){ $existing = get_option( $this->theme_name . sanitize_key($this->current_id) . '_wxr_import_info' ); if ( ! empty( $existing ) ) { $this->authors = $existing->users; $this->version = $existing->version; return $existing; } $selected_demo = $this->demo_data[ $this->current_id ]; $importer = $this->wxr_import; $data = $importer->get_preliminary_information( $selected_demo['content'] ); if ( is_wp_error( $data ) ) { return $data; } update_option( $this->theme_name . sanitize_key($this->current_id) . '_wxr_import_info', $data); $this->authors = $data->users; $this->version = $data->version; return $data; } protected function _start_import_stream(){ @ini_set( 'output_buffering', 'off' ); @ini_set( 'zlib.output_compression', false ); if ( $GLOBALS['is_nginx'] ) { header( 'X-Accel-Buffering: no' ); header( 'Content-Encoding: none' ); } // Start the event stream. header( 'Content-Type: text/event-stream' ); $demo_selected = $this->demo_data[ $this->current_id ]; $settings = get_option('_wxr_import_settings'); if ( empty( $settings ) ) { // Tell the browser to stop reconnecting. status_header( 204 ); exit; } // 2KB padding for IE echo ':' . str_repeat(' ', 2048) . "\n\n"; // Time to run the import! set_time_limit(0); // Ensure we're not buffered. wp_ob_end_flush_all(); flush(); $mapping = $settings['mapping']; $importer = $this->wxr_import; if ( ! empty( $mapping['mapping'] ) ) { $importer->set_user_mapping( $mapping['mapping'] ); } if ( ! empty( $mapping['slug_overrides'] ) ) { $importer->set_user_slug_overrides( $mapping['slug_overrides'] ); } // Are we allowed to create users? if ( ! $this->allow_create_users() ) { add_filter( 'wxr_importer.pre_process.user', '__return_null' ); } // Keep track of our progress add_action( 'wxr_importer.processed.post', array( $this, 'imported_post' ), 10, 2 ); add_action( 'wxr_importer.process_failed.post', array( $this, 'imported_post' ), 10, 2 ); add_action( 'wxr_importer.processed.comment', array( $this, 'imported_comment' ) ); add_action( 'wxr_importer.processed.term', array( $this, 'imported_term' ) ); add_action( 'wxr_importer.process_failed.term', array( $this, 'imported_term' ) ); add_action( 'wxr_importer.processed.user', array( $this, 'imported_user' ) ); add_action( 'wxr_importer.process_failed.user', array( $this, 'imported_user' ) ); // Clean up some memory unset( $settings ); // Flush once more. flush(); if( $this->setting_args['content'] && !empty( $demo_selected['content'] ) ) { if(!isset($this->running_import_content)){ $err = $importer->import( $demo_selected['content'] ); // Let the browser know we're done. $complete = array( 'action' => 'ImportingContent', 'error' => false, ); if ( is_wp_error( $err ) ) { $complete['error'] = $err->get_error_message(); } $this->running_import_content = false; $this->emit_sse_message( $complete ); } } if( $this->setting_args['slider'] && !empty( $demo_selected['slider'] ) ) { if(!isset($this->running_import_slider)){ $this->handling_importer_slider( $demo_selected['slider'] ); $this->running_import_slider = false; } } if( $this->setting_args['widget'] && !empty( $demo_selected['widget'] ) ) { if(!isset($this->running_import_widget)){ $this->handling_importer_widgets( $demo_selected['widget'] ); $this->running_import_widget = false; } } if( $this->setting_args['option'] && !empty( $demo_selected['option'] ) ) { if(!isset($this->running_import_option)){ $this->handling_importer_option( $demo_selected['option'] ); $this->running_import_option = false; } } if(!isset($this->running_import_theme_mode)){ $this->handling_importer_theme_mode( $this->current_id ); $this->running_import_theme_mode = false; } if(!isset($this->importer_is_running)){ if( false !== has_action('LaStudio_Importer/after_import') ){ do_action( 'LaStudio_Importer/after_import', $demo_selected, $this->current_id, $this ); } $this->importer_is_running = false; } // Remove the settings to stop future reconnects. delete_option('_wxr_import_settings'); unset($this->running_import_content); unset($this->running_import_slider); unset($this->running_import_widget); unset($this->running_import_option); unset($this->running_import_theme_mode); unset($this->importer_is_running); exit; } protected function _start_import_stream_without_content(){ @ini_set( 'output_buffering', 'off' ); @ini_set( 'zlib.output_compression', false ); if ( $GLOBALS['is_nginx'] ) { header( 'X-Accel-Buffering: no' ); header( 'Content-Encoding: none' ); } header( 'Content-Type: text/event-stream' ); $demo_selected = $this->demo_data[ $this->current_id ]; $settings = get_option('_wxr_import_settings'); if ( empty( $settings ) ) { status_header( 204 ); exit; } // 2KB padding for IE echo ':' . str_repeat(' ', 2048) . "\n\n"; // Time to run the import! set_time_limit(0); // Ensure we're not buffered. wp_ob_end_flush_all(); flush(); unset( $settings ); flush(); if( $this->setting_args['slider'] && !empty( $demo_selected['slider'] ) ) { if(!isset($this->running_import_slider)){ $this->handling_importer_slider( $demo_selected['slider'] ); $this->running_import_slider = false; } } if( $this->setting_args['widget'] && !empty( $demo_selected['widget'] ) ) { if(!isset($this->running_import_widget)){ $this->handling_importer_widgets( $demo_selected['widget'] ); $this->running_import_widget = false; } } if( $this->setting_args['option'] && !empty( $demo_selected['option'] ) ) { if(!isset($this->running_import_option)){ $this->handling_importer_option( $demo_selected['option'] ); $this->running_import_option = false; } } if(!isset($this->running_import_theme_mode)){ $this->handling_importer_theme_mode( $this->current_id ); $this->running_import_theme_mode = false; } if(!isset($this->importer_is_running)){ if( false !== has_action('LaStudio_Importer/after_import') ){ do_action( 'LaStudio_Importer/after_import', $demo_selected, $this->current_id, $this ); } $this->importer_is_running = false; } // Remove the settings to stop future reconnects. delete_option('_wxr_import_settings'); unset($this->running_import_slider); unset($this->running_import_widget); unset($this->running_import_option); unset($this->running_import_theme_mode); unset($this->importer_is_running); flush(); exit; } /** * Get the importer instance. * * @return WXR_Importer */ protected function get_importer() { $importer = new WXR_Importer( $this->get_import_options() ); $importer->set_logger( $this->logger ); return $importer; } /** * Get options for the importer. * * @return array Options to pass to WXR_Importer::__construct */ protected function get_import_options() { $options = array( 'fetch_attachments' => $this->fetch_attachments, 'default_author' => get_current_user_id(), ); /** * Filter the importer options used in the admin UI. * * @param array $options Options to pass to WXR_Importer::__construct */ return apply_filters( 'wxr_importer.admin.import_options', $options ); } /** * Decide whether or not the importer should attempt to download attachment files. * Default is true, can be filtered via import_allow_fetch_attachments. The choice * made at the import options screen must also be true, false here hides that checkbox. * * @return bool True if downloading attachments is allowed */ protected function allow_fetch_attachments() { return apply_filters( 'import_allow_fetch_attachments', true ); } /** * Decide whether or not the importer is allowed to create users. * Default is true, can be filtered via import_allow_create_users * * @return bool True if creating users is allowed */ protected function allow_create_users() { return apply_filters( 'import_allow_create_users', true ); } /** * Get mapping data from request data. * * Parses form request data into an internally usable mapping format. * * @param array $args Raw (UNSLASHED) POST data to parse. * @return array Map containing `mapping` and `slug_overrides` keys. */ protected function get_author_mapping( $args = array() ) { if ( ! isset( $args['imported_authors'] ) ) { return array( 'mapping' => array(), 'slug_overrides' => array(), ); } $map = isset( $args['user_map'] ) ? (array) $args['user_map'] : array(); $new_users = isset( $args['user_new'] ) ? $args['user_new'] : array(); $old_ids = isset( $args['imported_author_ids'] ) ? (array) $args['imported_author_ids'] : array(); // Store the actual map. $mapping = array(); $slug_overrides = array(); foreach ( (array) $args['imported_authors'] as $i => $old_login ) { $old_id = isset( $old_ids[$i] ) ? (int) $old_ids[$i] : false; if ( !empty( $map[$i] ) ) { $user = get_user_by( 'id', (int) $map[$i] ); if ( isset( $user->ID ) ) { $mapping[] = array( 'old_slug' => $old_login, 'old_id' => $old_id, 'new_id' => $user->ID, ); } } elseif ( !empty( $new_users[ $i ] ) ) { if ( $new_users[ $i ] !== $old_login ) { $slug_overrides[ $old_login ] = $new_users[ $i ]; } } } return compact( 'mapping', 'slug_overrides' ); } /** * Emit a Server-Sent Events message. * * @param mixed $data Data to be JSON-encoded and sent in the message. */ protected function emit_sse_message( $data ) { echo "event: message\n"; echo 'data: ' . wp_json_encode( $data ) . "\n\n"; // Extra padding. echo ':' . str_repeat(' ', 2048) . "\n\n"; flush(); } /** * Send message when a post has been imported. * * @param int $id Post ID. * @param array $data Post data saved to the DB. */ public function imported_post( $id, $data ) { $this->emit_sse_message( array( 'action' => 'updateDelta', 'type' => ( $data['post_type'] === 'attachment' ) ? 'media' : 'posts', 'delta' => 1, )); } /** * Send message when a comment has been imported. */ public function imported_comment() { $this->emit_sse_message( array( 'action' => 'updateDelta', 'type' => 'comments', 'delta' => 1, )); } /** * Send message when a term has been imported. */ public function imported_term() { $this->emit_sse_message( array( 'action' => 'updateDelta', 'type' => 'terms', 'delta' => 1, )); } /** * Send message when a user has been imported. */ public function imported_user() { $this->emit_sse_message( array( 'action' => 'updateDelta', 'type' => 'users', 'delta' => 1, )); } /** * Get data from a file * * @param string $file_path file path where the content should be saved. * @return string $data, content of the file or WP_Error object with error message. */ public static function data_from_file( $file_path ) { // Check if the file-system method is 'direct', if not display an error. if ( ! 'direct' === get_filesystem_method() ) { return self::return_direct_filesystem_error(); } // Verify WP file-system credentials. $verified_credentials = self::check_wp_filesystem_credentials(); if ( is_wp_error( $verified_credentials ) ) { return $verified_credentials; } // By this point, the $wp_filesystem global should be working, so let's use it to read a file. global $wp_filesystem; $data = $wp_filesystem->get_contents( $file_path ); if ( ! $data ) { return new WP_Error( 'failed_reading_file_from_server', sprintf( __( 'An error occurred while reading a file from your server! Tried reading file from path: %s%s.', LA_TEXTDOMAIN ), '<br>', $file_path ) ); } // Return the file data. return $data; } /** * Helper function: return the "no direct access file-system" error. * * @return WP_Error */ private static function return_direct_filesystem_error() { return new WP_Error( 'no_direct_file_access', sprintf( __( 'This WordPress page does not have %sdirect%s write file access. This plugin needs it in order to save the demo import xml file to the upload directory of your site. You can change this setting with these instructions: %s.', LA_TEXTDOMAIN ), '<strong>', '</strong>', '<a href="http://gregorcapuder.com/wordpress-how-to-set-direct-filesystem-method/" target="_blank">How to set <strong>direct</strong> filesystem method</a>' ) ); } /** * Helper function: check for WP file-system credentials needed for reading and writing to a file. * * @return boolean|WP_Error */ private static function check_wp_filesystem_credentials() { // Get user credentials for WP file-system API. $demo_import_page_url = wp_nonce_url( 'themes.php?page=theme_options', 'theme_options' ); $demo_import_page_url = ''; if ( false === ( $creds = request_filesystem_credentials( $demo_import_page_url, '', false, false, null ) ) ) { return new WP_error( 'filesystem_credentials_could_not_be_retrieved', __( 'An error occurred while retrieving reading/writing permissions to your server (could not retrieve WP filesystem credentials)!', LA_TEXTDOMAIN ) ); } // Now we have credentials, try to get the wp_filesystem running. if ( ! WP_Filesystem( $creds ) ) { return new WP_Error( 'wrong_login_credentials', __( 'Your WordPress login credentials don\'t allow to use WP_Filesystem!', LA_TEXTDOMAIN ) ); } return true; } /** * Imports widgets from a json file. * * @param string $data_file path to json file with WordPress widget export data. */ private function handling_importer_widgets( $file ) { $response = array( 'action' => 'ImportingWidget', 'error' => __( 'Widget import file could not be found.', LA_TEXTDOMAIN ) ); if( empty($file) || !file_exists($file) ) { $this->emit_sse_message( $response ); return; } $data = self::data_from_file( $file ); if ( is_wp_error( $data ) ) { $this->emit_sse_message( $response ); return; } $data = json_decode( $data ); // Import the widget data and save the results. $result = $this->import_widget_data( $data ); if ( is_wp_error( $result ) ) { $response['error'] = $result->get_error_message(); }else{ $this->logger->info(__('Widget has been importer !', LA_TEXTDOMAIN)); $response['error'] = __( 'Widget has been importer !', LA_TEXTDOMAIN); } $this->emit_sse_message( $response ); return; } /** * Import widget JSON data * * @global array $wp_registered_sidebars * @param object $data JSON widget data. * @return array $results */ private function import_widget_data( $data ) { global $wp_registered_sidebars; // Have valid data? If no data or could not decode. if ( empty( $data ) || ! is_object( $data ) ) { return new WP_Error( 'corrupted_widget_import_data', __( 'Widget import data could not be read. Please try a different file.', LA_TEXTDOMAIN ) ); } // Hook before import. do_action( 'LaStudio_Importer/widgets/before_import' ); $data = apply_filters( 'LaStudio_Importer/widgets/before_import_data', $data ); // Get all available widgets site supports. $available_widgets = $this->available_widgets(); // Get all existing widget instances. $widget_instances = array(); foreach ( $available_widgets as $widget_data ) { $widget_instances[ $widget_data['id_base'] ] = get_option( 'widget_' . $widget_data['id_base'] ); } // Begin results. $results = array(); // Loop import data's sidebars. foreach ( $data as $sidebar_id => $widgets ) { // Skip inactive widgets (should not be in export file). if ( 'wp_inactive_widgets' == $sidebar_id ) { continue; } // Check if sidebar is available on this site. Otherwise add widgets to inactive, and say so. if ( isset( $wp_registered_sidebars[ $sidebar_id ] ) ) { $sidebar_available = true; $use_sidebar_id = $sidebar_id; $sidebar_message_type = 'success'; $sidebar_message = ''; } else { $sidebar_available = false; $use_sidebar_id = 'wp_inactive_widgets'; // Add to inactive if sidebar does not exist in theme. $sidebar_message_type = 'error'; $sidebar_message = __( 'Sidebar does not exist in theme (moving widget to Inactive)', LA_TEXTDOMAIN ); } // Result for sidebar. $results[ $sidebar_id ]['name'] = ! empty( $wp_registered_sidebars[ $sidebar_id ]['name'] ) ? $wp_registered_sidebars[ $sidebar_id ]['name'] : $sidebar_id; // Sidebar name if theme supports it; otherwise ID. $results[ $sidebar_id ]['message_type'] = $sidebar_message_type; $results[ $sidebar_id ]['message'] = $sidebar_message; $results[ $sidebar_id ]['widgets'] = array(); // Loop widgets. foreach ( $widgets as $widget_instance_id => $widget ) { $fail = false; // Get id_base (remove -# from end) and instance ID number. $id_base = preg_replace( '/-[0-9]+$/', '', $widget_instance_id ); $instance_id_number = str_replace( $id_base . '-', '', $widget_instance_id ); // Does site support this widget? if ( ! $fail && ! isset( $available_widgets[ $id_base ] ) ) { $fail = true; $widget_message_type = 'error'; $widget_message = __( 'Site does not support widget', LA_TEXTDOMAIN ); // Explain why widget not imported. } // Filter to modify settings object before conversion to array and import. // Leave this filter here for backwards compatibility with manipulating objects (before conversion to array below). // Ideally the newer wie_widget_settings_array below will be used instead of this. $widget = apply_filters( 'LaStudio_Importer/widgets/widget_setting_object', $widget ); // Object. // Convert multidimensional objects to multidimensional arrays. // Some plugins like Jetpack Widget Visibility store settings as multidimensional arrays. // Without this, they are imported as objects and cause fatal error on Widgets page. // If this creates problems for plugins that do actually intend settings in objects then may need to consider other approach: https://wordpress.org/support/topic/problem-with-array-of-arrays. // It is probably much more likely that arrays are used than objects, however. $widget = json_decode( json_encode( $widget ), true ); // Filter to modify settings array. // This is preferred over the older wie_widget_settings filter above. // Do before identical check because changes may make it identical to end result (such as URL replacements). $widget = apply_filters( 'LaStudio_Importer/widgets/widget_setting_array', $widget ); // Does widget with identical settings already exist in same sidebar? if ( ! $fail && isset( $widget_instances[ $id_base ] ) ) { // Get existing widgets in this sidebar. $sidebars_widgets = get_option( 'sidebars_widgets' ); $sidebar_widgets = isset( $sidebars_widgets[ $use_sidebar_id ] ) ? $sidebars_widgets[ $use_sidebar_id ] : array(); // Check Inactive if that's where will go. // Loop widgets with ID base. $single_widget_instances = ! empty( $widget_instances[ $id_base ] ) ? $widget_instances[ $id_base ] : array(); foreach ( $single_widget_instances as $check_id => $check_widget ) { // Is widget in same sidebar and has identical settings? if ( in_array( "$id_base-$check_id", $sidebar_widgets ) && (array) $widget == $check_widget ) { $fail = true; $widget_message_type = 'warning'; $widget_message = __( 'Widget already exists', LA_TEXTDOMAIN ); // Explain why widget not imported. break; } } } // No failure. if ( ! $fail ) { // Add widget instance. $single_widget_instances = get_option( 'widget_' . $id_base ); // All instances for that widget ID base, get fresh every time. $single_widget_instances = ! empty( $single_widget_instances ) ? $single_widget_instances : array( '_multiwidget' => 1 ); // Start fresh if have to. $single_widget_instances[] = $widget; // Add it. // Get the key it was given. end( $single_widget_instances ); $new_instance_id_number = key( $single_widget_instances ); // If key is 0, make it 1. // When 0, an issue can occur where adding a widget causes data from other widget to load, and the widget doesn't stick (reload wipes it). if ( '0' === strval( $new_instance_id_number ) ) { $new_instance_id_number = 1; $single_widget_instances[ $new_instance_id_number ] = $single_widget_instances[0]; unset( $single_widget_instances[0] ); } // Move _multiwidget to end of array for uniformity. if ( isset( $single_widget_instances['_multiwidget'] ) ) { $multiwidget = $single_widget_instances['_multiwidget']; unset( $single_widget_instances['_multiwidget'] ); $single_widget_instances['_multiwidget'] = $multiwidget; } // Update option with new widget. update_option( 'widget_' . $id_base, $single_widget_instances ); // Assign widget instance to sidebar. $sidebars_widgets = get_option( 'sidebars_widgets' ); // Which sidebars have which widgets, get fresh every time. $new_instance_id = $id_base . '-' . $new_instance_id_number; // Use ID number from new widget instance. $sidebars_widgets[ $use_sidebar_id ][] = $new_instance_id; // Add new instance to sidebar. update_option( 'sidebars_widgets', $sidebars_widgets ); // Save the amended data. // After widget import action. $after_widget_import = array( 'sidebar' => $use_sidebar_id, 'sidebar_old' => $sidebar_id, 'widget' => $widget, 'widget_type' => $id_base, 'widget_id' => $new_instance_id, 'widget_id_old' => $widget_instance_id, 'widget_id_num' => $new_instance_id_number, 'widget_id_num_old' => $instance_id_number, ); do_action( 'LaStudio_Importer/widgets/after_single_widget_import', $after_widget_import ); // Success message. if ( $sidebar_available ) { $widget_message_type = 'success'; $widget_message = __( 'Imported', LA_TEXTDOMAIN ); } else { $widget_message_type = 'warning'; $widget_message = __( 'Imported to Inactive', LA_TEXTDOMAIN ); } } // Result for widget instance. $results[ $sidebar_id ]['widgets'][ $widget_instance_id ]['name'] = isset( $available_widgets[ $id_base ]['name'] ) ? $available_widgets[ $id_base ]['name'] : $id_base; // Widget name or ID if name not available (not supported by site). $results[ $sidebar_id ]['widgets'][ $widget_instance_id ]['title'] = ! empty( $widget['title'] ) ? $widget['title'] : __( '', LA_TEXTDOMAIN ); // Show "No Title" if widget instance is untitled. $results[ $sidebar_id ]['widgets'][ $widget_instance_id ]['message_type'] = $widget_message_type; $results[ $sidebar_id ]['widgets'][ $widget_instance_id ]['message'] = $widget_message; } } // Hook after import. do_action( 'LaStudio_Importer/widgets/after_import' ); // Return results. return apply_filters( 'LaStudio_Importer/widgets/import_results', $results ); } /** * Available widgets. * * Gather site's widgets into array with ID base, name, etc. * * @global array $wp_registered_widget_controls * @return array $available_widgets, Widget information */ private function available_widgets() { global $wp_registered_widget_controls; $widget_controls = $wp_registered_widget_controls; $available_widgets = array(); foreach ( $widget_controls as $widget ) { if ( ! empty( $widget['id_base'] ) && ! isset( $available_widgets[ $widget['id_base'] ] ) ) { $available_widgets[ $widget['id_base'] ]['id_base'] = $widget['id_base']; $available_widgets[ $widget['id_base'] ]['name'] = $widget['name']; } } return apply_filters( 'LaStudio_Importer/widgets/available_widgets', $available_widgets ); } private function handling_importer_slider( $file ) { if ( !empty( $file ) && file_exists( $file ) ) { if( class_exists('RevSlider') ) { $slider = new RevSlider(); $result = $slider->importSliderFromPost( true, true, $file ); if( is_wp_error( $result ) ) { $response['error'] = $result->get_error_message(); $this->logger->error( sprintf(__('ImportingSlider %s', LA_TEXTDOMAIN), $result->get_error_message()) ); }else{ $this->logger->info( __('Slider has been imported !', LA_TEXTDOMAIN) ); } } } } private function handling_importer_option( $file ) { if( empty( $file ) || !file_exists( $file ) ) { $this->emit_sse_message( array( 'action' => 'ImportingOption', 'error' => __( 'Access define!', LA_TEXTDOMAIN ) ) ); return; } $data = self::data_from_file( $file ); if( is_wp_error( $data ) ) { $this->logger->error( __('Option config not found!', LA_TEXTDOMAIN) ); return; } $data = json_decode( $data, true ); $data = maybe_unserialize( $data ); if( empty( $data ) || !is_array( $data ) ) { $this->emit_sse_message( array( 'action' => 'ImportingOption', 'error' => __( 'Options is null', LA_TEXTDOMAIN) ) ); return; } update_option( lastudio_get_cs_option_name(), $data ); $this->logger->info( __('Theme setting has been set', LA_TEXTDOMAIN) ); return; } private function handling_importer_theme_mode( $demo_id ) { $demo_data = $this->demo_data[ $demo_id ]; $menu_locations = array(); $menu_array = isset($demo_data['menu-locations']) ? $demo_data['menu-locations'] : array(); if(!empty($menu_array)){ foreach ($menu_array as $key => $menu){ $menu_object = get_term_by( 'name', esc_attr($menu), 'nav_menu' ); $menu_locations[$key] = isset($menu_object->term_id) ? $menu_object->term_id : ''; } } if(!empty($menu_locations)){ set_theme_mod( 'nav_menu_locations', $menu_locations); $this->logger->info( __('Menu Location has been set', LA_TEXTDOMAIN) ); } $pages = array(); $page_array = isset($demo_data['pages']) ? $demo_data['pages'] : array(); if(!empty($page_array)){ foreach($page_array as $key => $title){ $page = get_page_by_title( $title ); if ( isset( $page->ID ) ) { update_option( $key, $page->ID ); $pages[] = $page->ID; } } } if(!empty($pages)){ update_option( 'show_on_front', 'page' ); $this->logger->info( __('Home Page and Blog Page has been set!', LA_TEXTDOMAIN) ); } $options_name = $this->theme_name . '_imported_demos'; $imported_demos = get_option( $options_name ); if ( empty( $imported_demos ) ) { $imported_demos = array( $demo_id => $demo_data ); }else { $imported_demos[$demo_id] = $demo_data; } $imported_demos['active_import'] = $demo_id; update_option( $options_name, $imported_demos ); $this->logger->info( __('Active demo success !', LA_TEXTDOMAIN) ); $this->emit_sse_message( array( 'action' => 'complete', 'error' => false ) ); } public function modify_post_author_when_using_ajax($data, $meta, $comments, $terms){ $data['post_author'] = (int) get_current_user_id(); return $data; } }
mit
tagniam/Turn
src/Game.cpp
13845
#include <iostream> #include <ctime> #include <fstream> #include <string> #include <limits> #include "../include/Game.h" #include "../include/Common.h" #include "../include/Console.h" #include "../include/PlayerTypes/PlayerTypes.h" #include "../include/EnemyTypes/EnemyTypes.h" using namespace std; using namespace Common; // To avoid conflict with numeric_limits<streamsize>::max used in Game::GetChoice() #ifdef max #undef max #endif #define SKIP_TURN -2 void Game::MainMenu() { // Main menu. Loops until you start // a game or quit. for (int choice=-1; choice!=0;) { choice = GetChoice(MenuType::eMain); switch(choice) { case 1: StartGame(); break; case 2: HowToPlay(); break; case 0: break; } } } string Game::InitializePlayerName() { ClearScreen(); string name; cout << "What is your name?" << endl << endl << "> "; cin.ignore(); getline(cin, name); // Change to full name return name; } char Game::InitializePlayerGender() { char gender; do { ClearScreen(); cout << "What is your gender (M or F)?" << endl << endl << "> "; cin >> gender; gender = toupper(gender); } while (gender != 'M' && gender != 'F'); return gender; } int Game::InitializePlayerClass() { // Initializes the player's class through user choice. int player_class = 0; player_class = GetChoice(MenuType::ePlayerClass); SetPlayerClass(player_class); return player_class; } void Game::SetPlayerClass(int player_class) { // Sets the Player class according to player code given. switch (player_class) { case 1: // Player's class is a warrior. _Player = new Warrior; break; case 2: // Player's class is a rogue. _Player = new Rogue; break; case 3: // Player's class is a healer. _Player = new Healer; break; case 4: // Player's class is a debugger. // Used to easily defeat enemies. Only for development purposes. _Player = new Debugger; break; case 5: // You are Saitama. // Do I have to explain?? _Player = new Saitama; break; default: // If input does not equal any of the cases, the default class is a warrior. _Player = new Warrior; break; } } void Game::SetPlayerData() { /* Data initialized in order of: * class code * name * level * experience * health * arrows * bombs * potions * whetstones * weaponsharpness * coins */ ifstream ReadData; ReadData.open("data.txt"); // Runs if user has never played the game before or data is not found. if (!ReadData) { ReadData.close(); ofstream WriteData; WriteData.open("data.txt"); WriteData << InitializePlayerClass() << endl << InitializePlayerName() << endl << InitializePlayerGender() << endl << 1 << endl << 0 << endl << 100 << endl << 10 << endl << 1 << endl << 1 << endl << 1 << endl << 100 << endl << 0; WriteData.close(); } else { // Initializes player type from class code given in data.txt int player_class; ReadData >> player_class; SetPlayerClass(player_class); ReadData.close(); } } void Game::SetEnemy() { // Generates a random integer to determine class of the enemy. // The abstract class Enemy is morphed with one of its child classes. EnemyType selector = EnemyType(Common::RandomInt(0, etNumEnemyTypes - 1)); switch(selector) { case etSlimeball: // Enemy is a slimeball. _Enemy = new Slimeball; break; case etCrab: // Enemy is a crab. _Enemy = new Crab; break; case etGiantCrab: // Enemy is a giant crab. _Enemy = new GiantCrab; break; case etSquid: // Enemy is a squid. _Enemy = new Squid; break; case etGiantSquid: // Enemy is a giant squid. _Enemy = new GiantSquid; break; case etMimic: // Enemy is a Mimic _Enemy = new Mimic; break; case etLich: // Enemy is a Lich _Enemy = new Lich; break; case etMurloc: //Enemy is a Murloc _Enemy = new Murloc; break; case etPutnafer: // Enemy is a Putnafer _Enemy = new Putnafer; break; case etZombie: // Enemy is a Zombie _Enemy = new Zombie; break; case etVampire: // Enemy is a Vampire _Enemy = new Vampire; break; case etWerewolf: // Enemy is a Werewolf _Enemy = new Werewolf; break; case etGoblin: // Enemy is a Goblin _Enemy = new Goblin; break; case etGargoyle: // Enemy is a Goblin _Enemy = new Gargoyle; break; case etCerberus: // Enemy is a Cerberus _Enemy = new Cerberus; break; case etSkeleton: // Enemy is a Skeleton _Enemy = new Skeleton; break; case etSmallDragon: // Enemy is a Small Dragon _Enemy = new SmallDragon; break; case etSmallRat: // Enemy is a Small Rat _Enemy = new SmallRat; break; case etRatKing: // Enemy is a Rat King _Enemy = new RatKing; break; case etZabra: _Enemy = new Zabra; break; case etGremlin: //Enemy is a Gremlin _Enemy = new Gremlin; break; case etTimidGhost: //enemy is a TimidGhost _Enemy = new TimidGhost; break; case etDemon: //enymy is a Demon _Enemy = new Demon; break; case etDragon: //enemy is a Dragon _Enemy = new Dragon; break; default: // If the above cases do not match the selector for any reason, // the enemy defaults on the crab class. _Enemy = new Crab; break; } // Simply prints that the enemy's class was encountered. cout << _Enemy->GetIntro() << endl; Sleep(SLEEP_MS); ColourPrint(_Enemy->GetName(), Console::DarkGrey); cout << " encountered!" << endl << endl; Sleep(SLEEP_MS); } bool Game::PlayAgain() { // Returns a bool value to determine if the player wants to play again. char choice; cout << "Keep going? (y/n)" << endl << endl; choice = (char)input(); // Returns true if the player says yes (Y, y, 1). if (choice == 'y' || choice == 'Y' || choice == '1') { return true; } // Returns false otherwise, regardless of choice=='n'. return false; } void Game::Intermission() { // Saves game in case player unexpectedly quits (uses X instead of // in-game quit. _Player->SaveGame(); // Loops until the player starts another battle or they quit (IsPlaying=false). for (int choice=0; IsPlaying;) { ClearScreen(); cout << "*--------- Intermission ----------* " << endl << endl; _Player->DisplayInventory(); cout << "1) Start battle" << endl; cout << "2) Store" << endl; cout << "3) Gamble" << endl; cout << "4) Use Item" << endl; cout << "0) Quit" << endl << endl; choice = input(); switch(choice) { case 1: // Returns to StartGame()'s loop, calling Battle(). return; case 2: // Goes to the store where the player can buy items. /// Currently in working progress. _Store.StoreFront(_Player); break; case 3: // Goes to the gambling arena. // _Player is passed in to add items won to the player inventory. _Gambling.Gamble(_Player); break; case 4: _Player->UseItem(); _Player->SaveGame(); break; case 0: // Breaks the loop in StartGame(), going back to MainMenu(). IsPlaying=false; break; } } } void Game::StartGame() { // Starts the game by initializing values for a new game. IsPlaying=true; // SetPlayerData() initializes the variables in this end. ClearScreen(); SetPlayerData(); // This initializes the variables on the Player end. ClearScreen(); _Player->SetPlayerData(); // Loops while the game is still playing. // Alternates between battles and intermission (gambling, store, et) while(IsPlaying) { Intermission(); if (!IsPlaying) { break; } Battle(); } // Saves the player's data to an external file before quitting. _Player->SaveGame(); } void Game::Battle() { ClearScreen(); // Uses random integers to determine class of the enemy. SetEnemy(); // Loops the actual battle while playing. while(IsPlaying) { ClearScreen(); // Displays the name and health bar of the player and enemy. // The Enemy* argument is to display the enemy's // name. Explained more in _Player->DisplayHealthBar(). _Player->DisplayHUD(_Enemy); _Enemy->DisplayHUD(); int damagePlayer = _Player->Action(); // Player's turn to attack Enemy or choose other action. if (damagePlayer != SKIP_TURN) { _Enemy->TakeDamage(damagePlayer); // Pauses console and ignores user input for SLEEP_MS milliseconds. Sleep(SLEEP_MS); } // Leaves battle if player chooses to. if (!IsPlaying) { IsPlaying = true; return; } // Executes when the enemy's health is 0 or below. if (_Enemy->IsDead()) { // Adds drops to player's inventory from defeated enemy. _Player->AddToInventory(_Enemy->GetDrops()); // Adds points to player's experience. _Player->AddExperience(_Enemy->ReturnExperience()); // Replenishes player's health for the next round. _Player->ReplenishHealth(); // If player wants to battle again, it breaks the loop and uses tail recursion to play again. if (PlayAgain()) { break; } // Returns to StartGame()'s loop, and executes Intermission(). return; } // Enemy's turn to attack player. if (damagePlayer != SKIP_TURN) { _Player->TakeDamage(_Enemy->Action()); } Sleep(SLEEP_MS); // Executes when player's health is 0 or below. if (_Player->IsDead()) { // Player loses the amount of experience points gained when you defeat the enemy. _Player->LoseExperience(_Enemy->ReturnExperience()); // Replenishes player's health for the next round. _Player->ReplenishHealth(); if (PlayAgain()) { break; } return; } } Battle(); } void Game::HowToPlay() { GetChoice(MenuType::eHowToPlay); } int Game::GetChoice(MenuType menuType) { DisplayMenu(menuType); int choice = -1; while (!(cin >> choice)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid input. Please try again."; Sleep(SLEEP_MS); DisplayMenu(menuType); } return choice; } void Game::DisplayMenu(MenuType menuType) { ClearScreen(); switch (menuType) { case Game::eMain: cout << "========== TURN-BASED FIGHTING GAME ==========" << endl << endl << "1) Start Game" << endl << "2) How to play" << endl << "0) Exit" << endl << endl << "> "; break; case Game::ePlayerClass: cout << endl << "Which class do you want to play as?" << endl << "1) Warrior (high damage, low healing capabilities)" << endl << "2) Rogue (moderate damage, moderate healing capabilities)" << endl << "3) Healer (low damage, high healing capabilities)" << endl << "4) Debugger (INFINITE DAMAGE!!!!)" << endl << "5) Saitama (self-explanatory)" << endl << endl << endl << "> "; break; case Game::eHowToPlay: cout << "============== HOW TO PLAY ==============" << endl << endl << "Turn is a turn-based RPG game." << endl << "Create your character and start playing." << endl << "For playing you have to choose what to do by typing" << endl << "the corresponding number." << endl << "You can perform actions and use items." << endl << endl << "-- Actions --" << endl << "Attack: Regular attack" << endl << "Risk Attack: Attack deals more damage, but with a chance of missing" << endl << "Heal: Restore an amount of your HP" << endl << "Flee: Run away from battle" << endl << endl << "-- Items --" << endl << "Bombs: Deals 50HP to your opponent with no chance of missing" << endl << "Arrows: Deals 10-15HP to your opponent with no chance of missing" << endl << "Potion: Replenishes your HP to 100" << endl << "Whetstone: Restores your weapon's sharpness." << endl << endl << "Good luck and have fun!" << endl << endl << "0) Back" << endl << endl << "> "; break; default: break; } }
mit
gregsdennis/Manatee.Json
Manatee.Json/Path/IJsonPathOperator.cs
138
namespace Manatee.Json.Path { internal interface IJsonPathOperator { JsonArray Evaluate(JsonArray json, JsonValue root); } }
mit
arnegroskurth/Symgrid
Grid/DataSource/ArrayDataSource.php
6491
<?php namespace ArneGroskurth\Symgrid\Grid\DataSource; use ArneGroskurth\Symgrid\Grid\AbstractColumn; use ArneGroskurth\Symgrid\Grid\AbstractDataSource; use ArneGroskurth\Symgrid\Grid\ArraysTrait; use ArneGroskurth\Symgrid\Grid\ColumnList; use ArneGroskurth\Symgrid\Grid\Column\BoolColumn; use ArneGroskurth\Symgrid\Grid\Column\DateColumn; use ArneGroskurth\Symgrid\Grid\Column\DateTimeColumn; use ArneGroskurth\Symgrid\Grid\Column\NumericColumn; use ArneGroskurth\Symgrid\Grid\Column\StringColumn; use ArneGroskurth\Symgrid\Grid\DataFilter; use ArneGroskurth\Symgrid\Grid\DataOrder; use ArneGroskurth\Symgrid\Grid\DataPathTrait; use ArneGroskurth\Symgrid\Grid\DataRecord; use ArneGroskurth\Symgrid\Grid\Exception; class ArrayDataSource extends AbstractDataSource implements \Iterator { use ArraysTrait; use DataPathTrait; /** * @var array */ protected $data; /** * @var string */ protected $idPath; /** * @var int */ protected $startPosition; /** * @var int */ protected $currentPosition; /** * @var int */ protected $endPosition; /** * ArraySource constructor. * * @param array $data * @param string $idPath */ public function __construct(array $data, $idPath) { $this->data = $data; $this->idPath = $idPath; } /** * {@inheritdoc} */ public function load(ColumnList $columnList = null) { $this->startPosition = 0; $this->endPosition = count($this->data) - 1; return $this->getTotalCount(); } /** * {@inheritdoc} */ public function loadPage($page, $recordsPerPage, ColumnList $columnList = null) { $this->startPosition = $recordsPerPage * ($page - 1); $this->endPosition = min($recordsPerPage * $page - 1, $this->getTotalCount() - $this->startPosition) + 1; $this->rewind(); return $this->getLoadedCount(); } /** * {@inheritdoc} */ public function getColumnList() { if(empty($this->loadPage(1, 1))) { throw new Exception("Cannot generate column list from empty array data source."); } return $this->getColumnsByRecord($this->current()->getRecord()); } /** * @param $record * @param string[] $pathParts * * @return ColumnList */ protected function getColumnsByRecord($record, array $pathParts = array()) { $path = implode('.', $pathParts); $title = $this->getTitleByPath($pathParts); $columnList = new ColumnList(); if(is_string($record)) { $columnList->addColumn(new StringColumn($title, $path)); } elseif(is_int($record)) { $columnList->addColumn(new NumericColumn($title, $path, 0)); } elseif(is_float($record)) { $columnList->addColumn(new NumericColumn($title, $path, 2)); } elseif(is_bool($record)) { $columnList->addColumn(new BoolColumn($title, $path)); } elseif(is_object($record) && $record instanceof \DateTime) { // probably a date if($record->format('H:i:s') == '00:00:00') { $columnList->addColumn(new DateColumn($title, $path)); } // probably a date with time else { $columnList->addColumn(new DateTimeColumn($title, $path)); } } elseif(is_object($record) && $record instanceof \stdClass) { // use all fields as columns $columnList->append($this->getColumnsByRecord((array)$record, $pathParts)); } elseif(is_array($record) && !empty($record)) { // associative array given if($this->isAssociativeArray($record)) { foreach(array_keys($record) as $key) { $columnList->append($this->getColumnsByRecord($record[$key], $this->appendPathPart($pathParts, $key))); } } // check for consistent content elseif(!$this->arrayHasStringKeys($record)) { $nestedPath = $path . '*'; if($this->isFloatArray($record)) { $columnList->addColumn(new NumericColumn($title, $nestedPath)); } elseif($this->isIntegerArray($record)) { $columnList->addColumn(new NumericColumn($title, $nestedPath, 0)); } elseif($this->isStringArray($record)) { $columnList->addColumn(new StringColumn($title, $nestedPath)); } } } return $columnList; } /** * {@inheritdoc} */ public function getTotalCount(ColumnList $columnList = null) { return count($this->data); } /** * {@inheritdoc} */ public function getLoadedCount() { return $this->endPosition - $this->startPosition; } /** * {@inheritdoc} */ public function applyOrder(DataOrder $dataOrder = null) { throw new Exception("Data ordering not implemented for this data source."); } /** * {@inheritdoc} */ public function getAppliedOrder() { return null; } /** * {@inheritdoc} */ public function applyFilter(DataFilter $dataFilter) { throw new Exception("Data filtering not implemented for this data source."); } /** * {@inheritdoc} */ public function getAppliedFilters() { return array(); } /** * {@inheritdoc} */ public function getAggregation(AbstractColumn $column) { throw new Exception("Data aggregation not implemented for this data source."); } /** * {@inheritdoc} */ public function current() { return DataRecord::createByIdPath($this->data[$this->currentPosition], $this->idPath); } /** * {@inheritdoc} */ public function next() { ++$this->currentPosition; } /** * {@inheritdoc} */ public function key() { return $this->currentPosition; } /** * {@inheritdoc} */ public function valid() { return $this->currentPosition < $this->endPosition; } /** * {@inheritdoc} */ public function rewind() { $this->currentPosition = $this->startPosition; } }
mit
Phalanxia/Pastel-Dreams
app/main.js
547
requirejs(["config"], function() { requirejs([ // Libraries "underscore", "backbone", "marionette", "jquery", // Scripts "app", "client", // Maid Libraries "lib/maid/windowing" // Templates ], function (_, Backbone, Marionette, $, Maid, Client, windowing) { Client(); Maid.addRegions({ sidebar: "#sidebar", channelWrapper: "#channelWrapper" }); // Link handler $("a").on("click", function (e) { e.preventDefault(); Maid.gui.Shell.openExternal($(this).attr("href")); }); Maid.start(); }); });
mit
turingincomplete/MatchboxChip8
tests/interpreterTests.js
43764
var assert = require('assert'); var rewire = require('rewire'); var MatchboxChip8 = rewire('../src/MatchboxChip8'); describe('interpreter', function() { it('00E0 - should clear the display', function() { var testProgram = [ 0x00, 0xe0, ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.setPixel(0, 0, 1) interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; for(var x = 0; x < 64; x += 1) { for(var y = 0; y < 32; y += 1) { var pixel = interpreter.getPixel(x, y); assert.strictEqual(pixel, 0); } } }); it('00EE - should return from subroutine', function() { var testReturnAddress = 100; var testProgram = [ 0x00, 0xee, ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.pushStack(testReturnAddress); var oldStackTop = interpreter.stack[0]; var oldSP = interpreter.SP; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldStackTop, 'Program counter should equal old top of stack' ); assert.strictEqual( interpreter.SP, oldSP - 1, 'Stack pointer should be decremented by 1' ); }); it('1nnn - should jump to address', function() { var testTargetAddress = 0x123; var testProgram = [ 0x11, 0x23 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, testTargetAddress, 'Program counter should equal target address' ); }); it('2nnn - should call subroutine', function() { var testTargetAddress = 0x123; var testProgram = [ 0x21, 0x23 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); var oldPC = interpreter.PC; var oldSP = interpreter.SP; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.SP, oldSP + 1, 'Stack pointer should increase by 1' ); assert.strictEqual( interpreter.stack[0], oldPC + 2, 'Top of stack should equal old program counter value plus 2' ); assert.strictEqual( interpreter.PC, testTargetAddress, 'Program counter should equal target address' ); }); it('3xkk - should skip if immediate value equal (equal)', function() { var testRegisterNumber = 0xA; var testOperand = 0x10; var testProgram = [ 0x3a, 0x10 ]; var interpreter = new MatchboxChip8.Interpreter(); var oldPC = interpreter.PC; interpreter.registers[testRegisterNumber] = testOperand; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 4, 'Program counter should increase by 4' ); }); it('3xkk - should skip if immediate value equal (not equal)', function() { var testRegisterNumber = 0xA; var testOperand = 0x10; var testProgram = [ 0x3a, 0x10 ]; var interpreter = new MatchboxChip8.Interpreter(); var oldPC = interpreter.PC; interpreter.registers[testRegisterNumber] = testOperand + 1; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 2, 'Program counter should increase by 2' ); }); it('4xkk - should skip if immediate value not equal (equal)', function() { var testRegisterNumber = 0xA; var testOperand = 0x10; var testProgram = [ 0x4a, 0x10 ]; var interpreter = new MatchboxChip8.Interpreter(); var oldPC = interpreter.PC; interpreter.registers[testRegisterNumber] = testOperand; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 2, 'Program counter should increase by 2' ); }); it('4xkk - should skip if i\' value not equal (not equal)', function() { var testRegisterNumber = 0xA; var testOperand = 0x10; var testProgram = [ 0x4a, 0x10 ]; var interpreter = new MatchboxChip8.Interpreter(); var oldPC = interpreter.PC; interpreter.registers[testRegisterNumber] = testOperand + 1; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 4, 'Program counter should increase by 4' ); }); it('5xy0 - should skip if register value equal (equal)', function() { var registerXNum = 0xA; var registerYNum = 0x1; var registerXValue = registerYValue = 0x1; var testProgram = [ 0x5a, 0x10 ]; var interpreter = new MatchboxChip8.Interpreter(); var oldPC = interpreter.PC; interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 4, 'Program counter should increase by 4' ); }); it('5xy0 - should skip if register value equal (not equal)', function() { var registerXNum = 0xA; var registerYNum = 0x1; var registerXValue = 0x1; var registerYValue = 0x2; var testProgram = [ 0x5a, 0x10 ]; var interpreter = new MatchboxChip8.Interpreter(); var oldPC = interpreter.PC; interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 2, 'Program counter should increase by 2' ); }); it('6xkk - should load byte into register', function() { var registerXNum = 0x0; var byteValue = 0x11; var testProgram = [ 0x60, 0x11 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], byteValue, 'Register X value should equal byte value' ); }); it('7xkk - should add byte value to register', function() { var registerXNum = 0x0; var registerXValue = 0x1; var byteValue = 0x11; var testProgram = [ 0x70, 0x11 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], byteValue + registerXValue, 'Register X value should equal byte value + old value' ); }); it('7xkk - should add byte value to register (overflow)', function() { var registerXNum = 0x0; var registerXValue = 0x2; var byteValue = 0xFF; var testProgram = [ 0x70, 0xff ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], 0x1, 'Register X value should equal byte value + old value (wrapped)' ); }); it('8xy0 - should load register y into register x', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerXValue = 0x0; var registerYValue = 0xA; var testProgram = [ 0x80, 0x10 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], registerYValue, 'Register X value should equal register Y value' ); }); it('8xy1 - should OR register y into register x', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerXValue = 0xA; var registerYValue = 0xB; var testProgram = [ 0x80, 0x11 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], registerYValue | registerXValue, 'Register X value should equal ry OR rx' ); }); it('8xy2 - should AND register y into register x', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerXValue = 0xA; var registerYValue = 0xB; var testProgram = [ 0x80, 0x12 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], registerYValue & registerXValue, 'Register X value should equal ry AND rx' ); }); it('8xy3 - should XOR register y into register x', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerXValue = 0xA; var registerYValue = 0xB; var testProgram = [ 0x80, 0x13 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], registerYValue ^ registerXValue, 'Register X value should equal ry XOR rx' ); }); it('8xy4 - should ADD register y into register x (no carry)', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerXValue = 0x01; var registerYValue = 0x03; var testProgram = [ 0x80, 0x14 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], registerYValue + registerXValue, 'Register X value should equal ry ADD rx' ); assert.strictEqual( interpreter.registers[0xF], 0, 'Register 0xF value (carry bit) should equal 0' ); }); it('8xy4 - should ADD register y into register x (carry)', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerXValue = 0xFF; var registerYValue = 0x04; var testProgram = [ 0x80, 0x14 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], registerYValue - 1, 'Register X value should equal ry - 1' ); assert.strictEqual( interpreter.registers[0xF], 1, 'Register 0xF value (carry bit) should equal 1' ); }); it('8xy5 - should SUB register y from r\' x (no borrow)', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerXValue = 0x04; var registerYValue = 0x05; var testProgram = [ 0x80, 0x15 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], 0x01, 'Register X value should equal rx - ry' ); assert.strictEqual( interpreter.registers[0xF], 0, 'Register 0xF value (borrow bit) should equal 0' ); }); it('8xy5 - should SUB register y from r\' x (borrow)', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerXValue = 0x05; var registerYValue = 0x04; var testProgram = [ 0x80, 0x15 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], 0x01, 'Register X value should equal abs(rx - ry)' ); assert.strictEqual( interpreter.registers[0xF], 1, 'Register 0xF value (borrow bit) should equal 1' ); }); it('8xy6 - should bit shift right register x (no overflow)', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerYValue = 0x04; var testProgram = [ 0x80, 0x16 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], 0x02, 'Register X value should equal 2' ); assert.strictEqual( interpreter.registers[registerYNum], 0x04, 'Register Y value should equal 4' ); assert.strictEqual( interpreter.registers[0xF], 0, 'Register 0xF value (overflow bit) should equal 0' ); }); it('8xy6 - should bit shift right register x (overflow)', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerYValue = 0x05; var testProgram = [ 0x80, 0x16 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], 0x02, 'Register X value should equal 2' ); assert.strictEqual( interpreter.registers[registerYNum], 0x05, 'Register Y value should equal 5' ); assert.strictEqual( interpreter.registers[0xF], 1, 'Register 0xF value (overflow bit) should equal 1' ); }); it('8xy7 - should SUBN register y from r\' x (no borrow)', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerXValue = 0x05; var registerYValue = 0x04; var testProgram = [ 0x80, 0x17 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], 0x01, 'Register X value should equal rx - ry' ); assert.strictEqual( interpreter.registers[0xF], 1, 'Register 0xF value (borrow bit) should equal 1' ); }); it('8xy7 - should SUBN register y from r\' x (borrow)', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerXValue = 0x04; var registerYValue = 0x05; var testProgram = [ 0x80, 0x17 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], 0x01, 'Register X value should equal abs(rx - ry)' ); assert.strictEqual( interpreter.registers[0xF], 0, 'Register 0xF value (borrow bit) should equal 0' ); }); it('8xyE - should bit shift left register x (no overflow)', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerYValue = 0x7f; var testProgram = [ 0x80, 0x1e ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], 0xfe, 'Register X value should equal 0xfe' ); assert.strictEqual( interpreter.registers[registerYNum], 0x7f, 'Register Y value should equal 0x7f' ); assert.strictEqual( interpreter.registers[0xF], 0, 'Register 0xF value (overflow bit) should equal 0' ); }); it('8xyE - should bit shift left register x (overflow)', function() { var registerXNum = 0x0; var registerYNum = 0x1; var registerYValue = 0x80; var testProgram = [ 0x80, 0x1e ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], 0x00, 'Register X value should equal 0x00' ); assert.strictEqual( interpreter.registers[registerYNum], 0x80, 'Register Y value should equal 0x80' ); assert.strictEqual( interpreter.registers[0xF], 1, 'Register 0xF value (overflow bit) should equal 1' ); }); it('9xy0 - should skip if r\'x != r\'y (equal)', function() { var registerXNum = 0xA; var registerYNum = 0x1; var registerXValue = 0x1; var registerYValue = 0x1; var testProgram = [ 0x9a, 0x10 ]; var interpreter = new MatchboxChip8.Interpreter(); var oldPC = interpreter.PC; interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 2, 'Program counter should increase by 2' ); }); it('9xy0 - should skip if r\'x != r\'y (not equal)', function() { var registerXNum = 0xA; var registerYNum = 0x1; var registerXValue = 0x2; var registerYValue = 0x1; var testProgram = [ 0x9a, 0x10 ]; var interpreter = new MatchboxChip8.Interpreter(); var oldPC = interpreter.PC; interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 4, 'Program counter should increase by 4' ); }); it('Annn - should set ri to nnn', function() { var value = 0x123; var testProgram = [ 0xa1, 0x23 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.I, value, 'Register I should equal value' ); }); it('Bnnn - should jump to r\'0 + nnn', function() { var value = 0x123; var register0Value = 0x2; var testProgram = [ 0xb1, 0x23 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.registers[0] = register0Value; interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, register0Value + value, 'PC should equal register 0 value + nnn value' ); }); it('Cxkk - should set r\'x to rand(0-255) AND kk', function() { var testRandNum = 0x02; MatchboxChip8.__with__({ randRange: function(min, max) { return testRandNum; } })(function () { var registerXNum = 0x0; var value = 0x0F; var testProgram = [ 0xc0, 0x0f ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], 0x02, 'r\'0 should equal 0x02' ); }); }); it('Dxyn - should draw n byte sprite from I at x y', function() { var I = 0x0; var registerXNum = 0x0; var registerXValue = 0x1; var registerYNum = 0x1; var registerYValue = 0x2; var n = 0x8; var testProgram = [ 0xd0, 0x15 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); //Set an overlapping but not colliding bit interpreter.setPixel(2, 4, 1); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.I = I; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; var expectedPixels = [ [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0] ]; var resultPixels = []; for (var xCoord = 0; xCoord < expectedPixels[0].length; xCoord += 1) { var row = []; for(var yCoord = 0; yCoord < expectedPixels.length; yCoord += 1) { row.push(interpreter.getPixel(yCoord, xCoord)); } resultPixels.push(row); } var expectedPixelsStr = JSON.stringify(expectedPixels); var resultPixelsStr = JSON.stringify(resultPixels); assert.strictEqual( expectedPixelsStr, resultPixelsStr, '0 sprite should be drawn' ); assert.strictEqual( interpreter.registers[0xF], 0, 'Collision bit should not be set' ); }); it('Dxyn - should draw n byte sprite from I at x y (wrap)', function() { var I = 0x0; var registerXNum = 0x0; var registerXValue = 0x3e; var registerYNum = 0x1; var registerYValue = 0x2; var n = 0x8; var testProgram = [ 0xd0, 0x15 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; interpreter.registers[registerYNum] = registerYValue; interpreter.I = I; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; var expectedPixels = [ [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0] ]; var resultPixels = []; for (var xCoord = 0; xCoord < expectedPixels[0].length; xCoord += 1) { var row = []; for(var yCoord = 0; yCoord < expectedPixels.length; yCoord += 1) { row.push(interpreter.getPixel(yCoord, xCoord)); } resultPixels.push(row); } var expectedPixelsStr = JSON.stringify(expectedPixels); var resultPixelsStr = JSON.stringify(resultPixels); assert.strictEqual( expectedPixelsStr, resultPixelsStr, 'Wrapped 0 sprite should be drawn' ); }); it('Dxyn - should draw sprites with collision', function() { var testProgram = [ 0xD0, 0x15, 0x60, 0x02, 0xD0, 0x15 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; var expectedPixels = [ [1, 1, 0, 0, 1, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0, 0], [1, 0, 1, 1, 0, 1, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0] ]; var resultPixels = []; for (var xCoord = 0; xCoord < expectedPixels[0].length; xCoord += 1) { var row = []; for(var yCoord = 0; yCoord < expectedPixels.length; yCoord += 1) { row.push(interpreter.getPixel(yCoord, xCoord)); } resultPixels.push(row); } var expectedPixelsStr = JSON.stringify(expectedPixels); var resultPixelsStr = JSON.stringify(resultPixels); assert.strictEqual( expectedPixelsStr, resultPixelsStr, 'XORed sprite should be drawn' ) assert.strictEqual( interpreter.registers[0xF], 1, 'Collision bit should be set' ); ; }); it('Ex9E - should skip if key is pressed (pressed)', function() { var registerXNum = 5; var registerXValue = 1; var testProgram = [ 0xe5, 0x9e ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; interpreter.keyDown(registerXValue); var oldPC = interpreter.PC; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 4, 'PC should equal old value + 4' ); }); it('Ex9E - should skip if key is pressed (not pressed)', function() { var registerXNum = 5; var registerXValue = 1; var testProgram = [ 0xe0, 0x9e ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; var oldPC = interpreter.PC; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 2, 'PC should equal old value + 2' ); }); it('ExA1 - should skip if key is not pressed (pressed)', function() { var registerXNum = 5; var registerXValue = 1; var testProgram = [ 0xe5, 0xa1 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; interpreter.keyDown(registerXValue); var oldPC = interpreter.PC; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 2, 'PC should equal old value + 2' ); }); it('ExA1 - should skip if key is not pressed (not pressed)', function() { var registerXNum = 5; var registerXValue = 1; var testProgram = [ 0xe5, 0xa1 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; interpreter.keyDown(registerXValue); interpreter.keyUp(registerXValue); var oldPC = interpreter.PC; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.PC, oldPC + 4, 'PC should equal old value + 4' ); }); it('Fx07 - should put delay timer value into r\'x', function() { var registerXNum = 5; var delayTimerValue = 10; var testProgram = [ 0xf5, 0x07 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.DT = delayTimerValue; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.registers[registerXNum], delayTimerValue, 'Register x should equal delay timer value' ); }); it('Fx0A - should wait for keypress and store value in r\'x', function() { var testRegisterNum = 0; var registerXNum = 1; var keyCode = 0x5; var testProgram = [ 0xf1, 0x0a, 0x60, 0xff ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.step(); interpreter.step(); var testRegisterValueAfterWait = interpreter.registers[ testRegisterNum ]; interpreter.keyDown(keyCode); interpreter.step(); assert.strictEqual( interpreter.registers[registerXNum], keyCode, 'Register x should equal keycode' ); assert.strictEqual( interpreter.registers[ testRegisterNum ], 0, 'Test register should equal 0' ); }); it('should decrement timer registers at 60hz', function() { var dt = 120; var st = 50; var startTime = 1000; var secondsPassed = 1; var testProgram = [ 0x00, 0xe0, 0x00, 0xe0 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); MatchboxChip8.__with__({ currentTime: function() { return startTime; } })(function () { interpreter.step(); }); interpreter.DT = dt; interpreter.ST = st; MatchboxChip8.__with__({ currentTime: function() { return startTime + secondsPassed; } })(function () { interpreter.step(); }); assert.strictEqual( interpreter.DT, 60, 'Delay timer should decrease by 60' ); assert.strictEqual( interpreter.ST, 0, 'Sound time should cap at 0' ); }); it('Fx15 - should set delay timer to register x', function() { var registerXNum = 1; var registerXValue = 10; var testProgram = [ 0xf1, 0x15 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.DT, registerXValue, 'Delay timer should equal register x value' ); }); it('Fx18 - should set sound timer to register x', function() { var registerXNum = 1; var registerXValue = 10; var testProgram = [ 0xf1, 0x18 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.ST, registerXValue, 'Sound timer should equal register x value' ); }); it('Fx1E - should add register x into I', function() { var registerXNum = 1; var registerXValue = 0x1; var I = 0x1; var testProgram = [ 0xf1, 0x1e ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; interpreter.I = I; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.I, 0x2, 'Register I should equal 2' ); }); it('Fx1E - should add register x into I (overflow)', function() { var registerXNum = 1; var registerXValue = 0x3; var I = 0xFFFF; var testProgram = [ 0xf1, 0x1e ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; interpreter.I = I; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.I, 0x2, 'Register I should equal 2' ); }); it('Fx29 - should load the address of bitmap char into r\'i', function() { var registerXNum = 1; var registerXValue = 0xf; var testProgram = [ 0xf1, 0x29 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( interpreter.I, 0xf * 5, 'Register I should equal 0xf * 5' ); }); it('Fx33 - should store BCD of r\'x in r\'i...', function() { var registerXNum = 0x1; var registerXValue = 0xFF; var testProgram = [ 0xf1, 0x33 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[registerXNum] = registerXValue; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; var I = interpreter.I; assert.strictEqual( interpreter.RAM[I], 0x2, 'RAM[i] should equal BCD of 2' ); assert.strictEqual( interpreter.RAM[I + 1], 0x5, 'RAM[i + 1] should equal BCD of 5' ); assert.strictEqual( interpreter.RAM[I + 2], 0x5, 'RAM[i + 2] should equal BCD of 5' ); }); it('Fx55 - should dump r\' values 0-x into memory at r\'i', function() { var I = 0x210; var registerXNum = 0x3; var register0Value = 0x0; var register1Value = 0x1; var register2Value = 0x2; var register3Value = 0x3; var testProgram = [ 0xf3, 0x55 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.registers[0x0] = register0Value; interpreter.registers[0x1] = register1Value; interpreter.registers[0x2] = register2Value; interpreter.registers[0x3] = register3Value; interpreter.I = I; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; var expectedArray = [ 0x0, 0x1, 0x2, 0x3 ]; var resultArray = [ interpreter.RAM[I], interpreter.RAM[I + 1], interpreter.RAM[I + 2], interpreter.RAM[I + 3] ]; assert.strictEqual( JSON.stringify(expectedArray), JSON.stringify(resultArray) ); assert.strictEqual( interpreter.I, I + registerXNum + 1, 'Register I should equal I + Vx + 1' ); }); it('Fx65 - Should load registers from RAM from r\'i', function() { var I = 0x210; var registerXNum = 0x3; var IValue = 0x0; var I1Value = 0x1; var I2Value = 0x2; var I3Value = 0x3; var testProgram = [ 0xf3, 0x65 ]; var interpreter = new MatchboxChip8.Interpreter(); interpreter.loadInstructions(testProgram); interpreter.RAM[I] = IValue; interpreter.RAM[I + 1] = I1Value; interpreter.RAM[I + 2] = I2Value; interpreter.RAM[I + 3] = I3Value; interpreter.I = I; for(var i = 0; i < testProgram.length / 2; i += 1) { interpreter.step(); }; assert.strictEqual( IValue, interpreter.registers[0x0], 'Register 0 value should equal value at I' ); assert.strictEqual( I1Value, interpreter.registers[0x1], 'Register 1 value should equal value at I + 1' ); assert.strictEqual( I2Value, interpreter.registers[0x2], 'Register 2 value should equal value at I + 2' ); assert.strictEqual( I3Value, interpreter.registers[0x3], 'Register 3 value should equal value at I + 3' ); assert.strictEqual( interpreter.I, I + registerXNum + 1, 'Register I should equal I + Vx + 1' ); }); });
mit
thecodefish/WebDriverModels
WebDriverModels.Tests/Properties/AssemblyInfo.cs
1454
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WebDriverModels.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebDriverModels.Tests")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c30f409e-aea4-4128-b0e8-00f16419b29d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
finagram/finagram
src/main/scala/ru/finagram/api/json/AnswerSerializer.scala
2410
package ru.finagram.api.json import org.json4s.JsonAST.{ JInt, JObject } import org.json4s.JsonDSL._ import org.json4s.{ DefaultFormats, Extraction, Formats, JValue, Serializer, TypeInfo } import ru.finagram.api._ object AnswerSerializer extends Serializer[Answer] { private val AnswerClass = classOf[Answer] override def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Answer] = { case (TypeInfo(AnswerClass, _), json: JObject) => json.values match { case v if v.contains("parseMode") && "Markdown".equalsIgnoreCase(v("parseMode").toString) => json.extract[MarkdownAnswer] case v if v.contains("parseMode") && "HTML".equalsIgnoreCase(v("parseMode").toString) => json.extract[HtmlAnswer] case v if v.contains("text") => json.extract[FlatAnswer] case v if v.contains("photo") => json.extract[PhotoAnswer] case v if v.contains("sticker") => json.extract[StickerAnswer] } } override def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { case a: FlatAnswer => JTextAnswer(a) ~~ ("text" -> a.text) case a: MarkdownAnswer => JTextAnswer(a) ~~ ("text" -> a.text) ~~ ("parseMode" -> "Markdown") case a: HtmlAnswer => JTextAnswer(a) ~~ ("text" -> a.text) ~~ ("parseMode" -> "HTML") case a: PhotoAnswer => if (a.caption.isEmpty) JAnswer(a) ~~ ("photo" -> a.photo) else JAnswer(a) ~~ ("photo" -> a.photo) ~~ ("caption" -> a.caption.get) case a: StickerAnswer => JAnswer(a) ~~ ("sticker" -> a.sticker) } private def JTextAnswer(a: TextAnswer): JObject = { if (a.disableWebPagePreview.isDefined) { JAnswer(a) ~~ ("disableWebPagePreview" -> a.disableWebPagePreview.get) } else { JAnswer(a) } } private def JAnswer(a: Answer): JObject = { var jobj = JObject("chatId" -> JInt(a.chatId)) jobj = if (a.disableNotification.isEmpty) jobj else jobj ~~ ("disableNotification" -> a.disableNotification.get) jobj = if (a.replyMarkup.isEmpty) jobj else jobj ~~ ("replyMarkup" -> json(a.replyMarkup.get)) jobj = if (a.replyToMessageId.isEmpty) jobj else jobj ~~ ("replyToMessageId" -> a.replyToMessageId.get) jobj } private def json(obj: AnyRef): JValue = { implicit val formats = DefaultFormats Extraction.decompose(obj) } }
mit
ErikVerheul/jenkins
core/src/main/java/jenkins/model/lazy/AbstractLazyLoadRunMap.java
19309
/* * The MIT License * * Copyright (c) 2012, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jenkins.model.lazy; import hudson.model.Job; import hudson.model.Run; import hudson.model.RunMap; import java.io.File; import java.io.IOException; import java.util.AbstractMap; import java.util.Collections; import java.util.Comparator; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; import static jenkins.model.lazy.AbstractLazyLoadRunMap.Direction.ASC; import static jenkins.model.lazy.AbstractLazyLoadRunMap.Direction.DESC; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * {@link SortedMap} that keeps build records by their build numbers, in the descending order * (newer ones first.) * * <p> * The main thing about this class is that it encapsulates the lazy loading logic. * That is, while this class looks and feels like a normal {@link SortedMap} from outside, * it actually doesn't have every item in the map instantiated yet. As items in the map get * requested, this class {@link #retrieve(File) retrieves them} on demand, one by one. * * <p> * The lookup is done by using the build number as the key (hence the key type is {@link Integer}). * * <p> * This class makes the following assumption about the on-disk layout of the data: * * <ul> * <li>Every build is stored in a directory, named after its number. * </ul> * * <p> * Some of the {@link SortedMap} operations are weakly implemented. For example, * {@link #size()} may be inaccurate because we only count the number of directories that look like * build records, without checking if they are loadable. But these weaknesses aren't distinguishable * from concurrent modifications, where another thread deletes a build while one thread iterates them. * * <p> * Some of the {@link SortedMap} operations are inefficiently implemented, by * {@linkplain #all() loading all the build records eagerly}. We hope to replace * these implementations by more efficient lazy-loading ones as we go. * * <p> * Object lock of {@code this} is used to make sure mutation occurs sequentially. * That is, ensure that only one thread is actually calling {@link #retrieve(File)} and * updating {@link jenkins.model.lazy.AbstractLazyLoadRunMap.Index#byNumber}. * * @author Kohsuke Kawaguchi * @since 1.485 */ public abstract class AbstractLazyLoadRunMap<R> extends AbstractMap<Integer,R> implements SortedMap<Integer,R> { /** * Used in {@link #all()} to quickly determine if we've already loaded everything. */ private boolean fullyLoaded; /** * Currently visible index. * Updated atomically. Once set to this field, the index object may not be modified. */ private volatile Index index = new Index(); private LazyLoadRunMapEntrySet<R> entrySet = new LazyLoadRunMapEntrySet<>(this); /** * Historical holder for map. * * TODO all this mess including {@link #numberOnDisk} could probably be simplified to a single {@code TreeMap<Integer,BuildReference<R>>} * where a null value means not yet loaded and a broken entry just uses {@code NoHolder}. * * The idiom is that you put yourself in a synchronized block, {@linkplain #copy() make a copy of this}, * update the copy, then set it to {@link #index}. */ private class Index { /** * Stores the mapping from build number to build, for builds that are already loaded. * * If we have known load failure of the given ID, we record that in the map * by using the null value (not to be confused with a non-null {@link BuildReference} * with null referent, which just means the record was GCed.) */ private final TreeMap<Integer,BuildReference<R>> byNumber; private Index() { byNumber = new TreeMap<>(Collections.reverseOrder()); } private Index(Index rhs) { byNumber = new TreeMap<>(rhs.byNumber); } } /** * Build numbers found on disk, in the ascending order. */ // copy on write private volatile SortedIntList numberOnDisk = new SortedIntList(0); /** * Base directory for data. * In effect this is treated as a final field, but can't mark it final * because the compatibility requires that we make it settable * in the first call after the constructor. */ protected File dir; @Restricted(NoExternalUse.class) // subclassing other than by RunMap does not guarantee compatibility protected AbstractLazyLoadRunMap(File dir) { initBaseDir(dir); } @Restricted(NoExternalUse.class) protected void initBaseDir(File dir) { assert this.dir==null; this.dir = dir; if (dir!=null) loadNumberOnDisk(); } /** * @return true if {@link AbstractLazyLoadRunMap#AbstractLazyLoadRunMap} was called with a non-null param, or {@link RunMap#load(Job, RunMap.Constructor)} was called */ @Restricted(NoExternalUse.class) public final boolean baseDirInitialized() { return dir != null; } /** * Updates base directory location after directory changes. * This method should be used on jobs renaming, etc. * @param dir Directory location * @since 1.546 */ public final void updateBaseDir(File dir) { this.dir = dir; } /** * Let go of all the loaded references. * * This is a bit more sophisticated version of forcing GC. * Primarily for debugging and testing lazy loading behaviour. * @since 1.507 */ public synchronized void purgeCache() { index = new Index(); fullyLoaded = false; loadNumberOnDisk(); } private void loadNumberOnDisk() { String[] kids = dir.list(); if (kids == null) { // the job may have just been created kids = EMPTY_STRING_ARRAY; } SortedIntList list = new SortedIntList(kids.length / 2); for (String s : kids) { try { list.add(Integer.parseInt(s)); } catch (NumberFormatException e) { // this isn't a build dir } } list.sort(); numberOnDisk = list; } @Override public Comparator<? super Integer> comparator() { return Collections.reverseOrder(); } @Override public boolean isEmpty() { return search(Integer.MAX_VALUE, DESC)==null; } @Override public Set<Entry<Integer, R>> entrySet() { assert baseDirInitialized(); return entrySet; } /** * Returns a read-only view of records that has already been loaded. */ public SortedMap<Integer,R> getLoadedBuilds() { return Collections.unmodifiableSortedMap(new BuildReferenceMapAdapter<>(this, index.byNumber)); } /** * @param fromKey * Biggest build number to be in the returned set. * @param toKey * Smallest build number-1 to be in the returned set (-1 because this is exclusive) */ @Override public SortedMap<Integer, R> subMap(Integer fromKey, Integer toKey) { // TODO: if this method can produce a lazy map, that'd be wonderful // because due to the lack of floor/ceil/higher/lower kind of methods // to look up keys in SortedMap, various places of Jenkins rely on // subMap+firstKey/lastKey combo. R start = search(fromKey, DESC); if (start==null) return EMPTY_SORTED_MAP; R end = search(toKey, ASC); if (end==null) return EMPTY_SORTED_MAP; for (R i=start; i!=end; ) { i = search(getNumberOf(i)-1,DESC); assert i!=null; } return Collections.unmodifiableSortedMap(new BuildReferenceMapAdapter<>(this, index.byNumber.subMap(fromKey, toKey))); } @Override public SortedMap<Integer, R> headMap(Integer toKey) { return subMap(Integer.MAX_VALUE, toKey); } @Override public SortedMap<Integer, R> tailMap(Integer fromKey) { return subMap(fromKey, Integer.MIN_VALUE); } @Override public Integer firstKey() { R r = newestBuild(); if (r==null) throw new NoSuchElementException(); return getNumberOf(r); } @Override public Integer lastKey() { R r = oldestBuild(); if (r==null) throw new NoSuchElementException(); return getNumberOf(r); } public R newestBuild() { return search(Integer.MAX_VALUE, DESC); } public R oldestBuild() { return search(Integer.MIN_VALUE, ASC); } @Override public R get(Object key) { if (key instanceof Integer) { int n = (Integer) key; return get(n); } return super.get(key); } public R get(int n) { return getByNumber(n); } /** * Checks if the specified build exists. * * @param number the build number to probe. * @return {@code true} if there is an run for the corresponding number, note that this does not mean that * the corresponding record will load. * @since 2.14 */ public boolean runExists(int number) { return numberOnDisk.contains(number); } /** * Finds the build #M where M is nearby the given 'n'. * * <p> * * * @param n * the index to start the search from * @param d * defines what we mean by "nearby" above. * If EXACT, find #N or return null. * If ASC, finds the closest #M that satisfies M ≥ N. * If DESC, finds the closest #M that satisfies M ≤ N. */ public @CheckForNull R search(final int n, final Direction d) { switch (d) { case EXACT: return getByNumber(n); case ASC: for (int m : numberOnDisk) { if (m < n) { // TODO could be made more efficient with numberOnDisk.find continue; } R r = getByNumber(m); if (r != null) { return r; } } return null; case DESC: // TODO again could be made more efficient ListIterator<Integer> iterator = numberOnDisk.listIterator(numberOnDisk.size()); while(iterator.hasPrevious()) { int m = iterator.previous(); if (m > n) { continue; } R r = getByNumber(m); if (r != null) { return r; } } return null; default: throw new AssertionError(); } } public R getById(String id) { return getByNumber(Integer.parseInt(id)); } public R getByNumber(int n) { Index snapshot = index; if (snapshot.byNumber.containsKey(n)) { BuildReference<R> ref = snapshot.byNumber.get(n); if (ref==null) return null; // known failure R v = unwrap(ref); if (v!=null) return v; // already in memory // otherwise fall through to load } synchronized (this) { if (index.byNumber.containsKey(n)) { // JENKINS-22767: recheck inside lock BuildReference<R> ref = index.byNumber.get(n); if (ref == null) { return null; } R v = unwrap(ref); if (v != null) { return v; } } return load(n, null); } } /** * @return the highest recorded build number, or 0 if there are none */ @Restricted(NoExternalUse.class) public synchronized int maxNumberOnDisk() { return numberOnDisk.max(); } protected final synchronized void proposeNewNumber(int number) throws IllegalStateException { if (number <= maxNumberOnDisk()) { throw new IllegalStateException("JENKINS-27530: cannot create a build with number " + number + " since that (or higher) is already in use among " + numberOnDisk); } } public R put(R value) { return _put(value); } protected R _put(R value) { return put(getNumberOf(value), value); } @Override public synchronized R put(Integer key, R r) { int n = getNumberOf(r); Index copy = copy(); BuildReference<R> ref = createReference(r); BuildReference<R> old = copy.byNumber.put(n,ref); index = copy; if (!numberOnDisk.contains(n)) { SortedIntList a = new SortedIntList(numberOnDisk); a.add(n); a.sort(); numberOnDisk = a; } entrySet.clearCache(); return unwrap(old); } private R unwrap(BuildReference<R> ref) { return ref!=null ? ref.get() : null; } @Override public synchronized void putAll(Map<? extends Integer,? extends R> rhs) { Index copy = copy(); for (R r : rhs.values()) { BuildReference<R> ref = createReference(r); copy.byNumber.put(getNumberOf(r),ref); } index = copy; } /** * Loads all the build records to fully populate the map. * Calling this method results in eager loading everything, * so the whole point of this class is to avoid this call as much as possible * for typical code path. * * @return * fully populated map. */ /*package*/ TreeMap<Integer,BuildReference<R>> all() { if (!fullyLoaded) { synchronized (this) { if (!fullyLoaded) { Index copy = copy(); for (Integer number : numberOnDisk) { if (!copy.byNumber.containsKey(number)) load(number, copy); } index = copy; fullyLoaded = true; } } } return index.byNumber; } /** * Creates a duplicate for the COW data structure in preparation for mutation. */ private Index copy() { return new Index(index); } /** * Tries to load the record #N. * * @return null if the data failed to load. */ private R load(int n, Index editInPlace) { assert Thread.holdsLock(this); assert dir != null; R v = load(new File(dir, String.valueOf(n)), editInPlace); if (v==null && editInPlace!=null) { // remember the failure. // if editInPlace==null, we can create a new copy for this, but not sure if it's worth doing, // TODO should we also update numberOnDisk? editInPlace.byNumber.put(n, null); } return v; } /** * @param editInPlace * If non-null, update this data structure. * Otherwise do a copy-on-write of {@link #index} */ private R load(File dataDir, Index editInPlace) { assert Thread.holdsLock(this); try { R r = retrieve(dataDir); if (r==null) return null; Index copy = editInPlace!=null ? editInPlace : new Index(index); BuildReference<R> ref = createReference(r); BuildReference<R> old = copy.byNumber.put(getNumberOf(r), ref); assert old == null || old.get() == null : "tried to overwrite " + old + " with " + ref; if (editInPlace==null) index = copy; return r; } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load "+dataDir,e); } return null; } /** * Subtype to provide {@link Run#getNumber()} so that this class doesn't have to depend on it. */ protected abstract int getNumberOf(R r); /** * Subtype to provide {@link Run#getId()} so that this class doesn't have to depend on it. */ protected String getIdOf(R r) { return String.valueOf(getNumberOf(r)); } /** * Allow subtype to capture a reference. */ protected BuildReference<R> createReference(R r) { return new BuildReference<>(getIdOf(r),r); } /** * Parses {@code R} instance from data in the specified directory. * * @return * null if the parsing failed. * @throws IOException * if the parsing failed. This is just like returning null * except the caller will catch the exception and report it. */ protected abstract R retrieve(File dir) throws IOException; public synchronized boolean removeValue(R run) { Index copy = copy(); int n = getNumberOf(run); BuildReference<R> old = copy.byNumber.remove(n); SortedIntList a = new SortedIntList(numberOnDisk); a.removeValue(n); numberOnDisk = a; this.index = copy; entrySet.clearCache(); return old != null; } /** * Replaces all the current loaded Rs with the given ones. */ public synchronized void reset(TreeMap<Integer,R> builds) { Index i = new Index(); for (R r : builds.values()) { BuildReference<R> ref = createReference(r); i.byNumber.put(getNumberOf(r),ref); } this.index = i; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object o) { return o==this; } public enum Direction { ASC, DESC, EXACT } private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final SortedMap EMPTY_SORTED_MAP = Collections.unmodifiableSortedMap(new TreeMap()); static final Logger LOGGER = Logger.getLogger(AbstractLazyLoadRunMap.class.getName()); }
mit
julianmendez/desktop-search
search-core/src/main/java/com/semantic/lucene/fields/image/PixelSizeField.java
979
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.semantic.lucene.fields.image; import com.semantic.lucene.util.IFieldProperty; import org.apache.lucene.document.Document; import org.apache.lucene.document.IntPoint; import org.apache.lucene.document.StoredField; /** * complete image size in pixel (datatype - int) * @author Christian Plonka (cplonka81@gmail.com) */ public class PixelSizeField implements IFieldProperty<Integer> { public static final String NAME = "image_pixel_size"; @Override public Class<Integer> getType() { return Integer.class; } @Override public String getName() { return NAME; } @Override public void add(Document doc, Integer value) { doc.add(new IntPoint(getName(), value)); doc.add(new StoredField(getName(), value)); } }
mit
npakai/enhavo
src/Enhavo/Bundle/NewsletterBundle/Strategy/DoubleOptInStrategy.php
6842
<?php /** * DoubleOptInStrategy.php * * @since 21/09/16 * @author gseidel */ namespace Enhavo\Bundle\NewsletterBundle\Strategy; use Enhavo\Bundle\NewsletterBundle\Form\Resolver; use Enhavo\Bundle\NewsletterBundle\Model\SubscriberInterface; use Enhavo\Bundle\NewsletterBundle\Storage\LocalStorage; use Enhavo\Bundle\NewsletterBundle\Storage\StorageResolver; use Enhavo\Bundle\NewsletterBundle\Storage\StorageInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class DoubleOptInStrategy extends AbstractStrategy { /** * @var LocalStorage */ private $localStorage; /** * @var StorageResolver */ private $storageResolver; /** * @var Resolver */ private $formResolver; /** * DoubleOptInStrategy constructor. * @param array$options * @param array $typeOptions * @param LocalStorage $localStorage * @param StorageResolver $storageResolver * @param Resolver $formResolver */ public function __construct($options, $typeOptions, LocalStorage $localStorage, StorageResolver $storageResolver, Resolver $formResolver) { parent::__construct($options, $typeOptions); $this->localStorage = $localStorage; $this->storageResolver = $storageResolver; $this->formResolver = $formResolver; } public function addSubscriber(SubscriberInterface $subscriber) { $subscriber->setCreatedAt(new \DateTime()); $subscriber->setActive(false); $this->setToken($subscriber); $this->localStorage->saveSubscriber($subscriber); $this->notifySubscriber($subscriber, $subscriber->getType()); return 'subscriber.form.message.double_opt_in'; } public function activateSubscriber(SubscriberInterface $subscriber, $type) { $subscriber->setActive(true); $subscriber->setToken(null); $this->localStorage->saveSubscriber($subscriber); $this->getSubscriberManager()->saveSubscriber($subscriber, $type); $this->notifyAdmin($subscriber, $type); $this->confirmSubscriber($subscriber, $subscriber->getType()); } private function notifySubscriber(SubscriberInterface $subscriber, $type) { $notify = $this->getTypeOption('notify', $type, true); if($notify) { $link = $this->getRouter()->generate('enhavo_newsletter_subscribe_activate', [ 'token' => $subscriber->getToken(), 'type' => $subscriber->getType() ], UrlGeneratorInterface::ABSOLUTE_URL); $template = $this->getTypeOption('template', $type, 'EnhavoNewsletterBundle:Subscriber:Email/double-opt-in.html.twig'); $from = $this->getTypeOption('from', $type, 'no-reply@enhavo.com'); $senderName = $this->getTypeOption('sender_name', $type, 'enahvo'); $message = new \Swift_Message(); $message->setSubject($this->getSubject()) ->setFrom($from, $senderName) ->setTo($subscriber->getEmail()) ->setBody($this->renderTemplate($template, [ 'subscriber' => $subscriber, 'link' => $link ]), 'text/html'); $this->sendMessage($message); } } private function confirmSubscriber(SubscriberInterface $subscriber, $type) { $notify = $this->getTypeOption('confirm', $type, true); if($notify) { // TODO add unsubscribe/change subscription link $template = $this->getTypeOption('confirmation_template', $type, 'EnhavoNewsletterBundle:Subscriber:Email/confirmation.html.twig'); $from = $this->getTypeOption('from', $type, 'no-reply@enhavo.com'); $senderName = $this->getTypeOption('sender_name', $type, 'enahvo'); $message = new \Swift_Message(); $message->setSubject($this->getSubject()) ->setFrom($from, $senderName) ->setTo($subscriber->getEmail()) ->setBody($this->renderTemplate($template, [ 'subscriber' => $subscriber ]), 'text/html'); $this->sendMessage($message); } } private function notifyAdmin(SubscriberInterface $subscriber, $type) { $notify = $this->getTypeOption('admin_notify', $type, false); if($notify) { $template = $this->getTypeOption('admin_template', $type, 'EnhavoNewsletterBundle:Subscriber:Email/notify-admin.html.twig'); $from = $this->getTypeOption('from', $$type, 'no-reply@enhavo.com'); $senderName = $this->getTypeOption('sender_name', $type, 'enahvo'); $to = $this->getTypeOption('admin_email', $type, 'no-reply@enhavo.com'); $message = new \Swift_Message(); $message->setSubject($this->getAdminSubject($type)) ->setFrom($from, $senderName) ->setTo($to) ->setBody($this->renderTemplate($template, [ 'subscriber' => $subscriber ]), 'text/html'); $this->sendMessage($message); } } private function getAdminSubject($type) { $subject = $this->getTypeOption('admin_subject', $type, 'Newsletter Subscription'); $translationDomain = $this->getTypeOption('admin_translation_domain', $type, null); return $this->container->get('translator')->trans($subject, [], $translationDomain); } public function exists(SubscriberInterface $subscriber) { $checkExists = $this->getTypeOption('check_exists',$subscriber->getType(), false); if ($checkExists) { if ($this->localStorage->exists($subscriber)) { return true; } /** @var StorageInterface $storage */ $storage = $this->storageResolver->resolve($subscriber->getType()); if ($storage->exists($subscriber)) { return true; } } return false; } public function handleExists(SubscriberInterface $subscriber) { $subscriber = $this->localStorage->getSubscriber($subscriber->getEmail()); if(!$subscriber->isActive()) { $this->setToken($subscriber); $this->notifySubscriber($subscriber, $subscriber->getType()); return 'subscriber.form.error.sent_again'; } return 'subscriber.form.error.exists'; } public function getActivationTemplate($type) { return $this->getTypeOption('activation_template', $type, 'EnhavoNewsletterBundle:Subscriber:activate.html.twig'); } private function getRouter() { return $this->container->get('router'); } public function getType() { return 'double_opt_in'; } }
mit
positive-js/mosaic
packages/mosaic/sidepanel/sidepanel-config.ts
1110
import { InjectionToken } from '@angular/core'; /** Injection token that can be used to access the data that was passed in to a sidepanel. */ export const MC_SIDEPANEL_DATA = new InjectionToken<any>('McSidepanelData'); export enum McSidepanelPosition { Right = 'right', Left = 'left', Top = 'top', Bottom = 'bottom' } export class McSidepanelConfig<D = any> { /** ID for the sidepanel. If omitted, a unique one will be generated. */ id?: string; /** Data being injected into the child component. */ data?: D | null = null; position?: McSidepanelPosition = McSidepanelPosition.Right; /** Whether the sidepanel has a backdrop. */ hasBackdrop?: boolean = true; backdropClass?: string; /** When we open multiple sidepanels, backdrop appears only once, except cases then this flag is true. */ requiredBackdrop?: boolean = false; /** Whether the user can use escape or clicking outside to close the sidepanel. */ disableClose?: boolean = false; /** Custom class for the overlay pane. */ overlayPanelClass?: string | string[] = ''; }
mit
LeonardoCiaccio/Awesome.Bookmarklets
bookmarklets/dailymotion.downloader/dailymotion.downloader.js
2866
/* Recupera i links per il download su Dailymotion */ ( function(){ "use strict"; var reSearch = /http(?:s?):\\\/\\\/www\.dailymotion\.com\\\/cdn\\\/[a-zA-Z\-_0-9]{9,16}\\\/video\\\/[a-zA-Z\-_0-9]{3,12}\.[a-z0-9]{3,4}\?auth\=[a-zA-Z\-_0-9]{9,60}/g, reFormat = /[A-Z]{1,3}[0-9]{2,4}\-[0-9]{2,4}x[0-9]{2,4}/g, reSite = /^http(?:s?):\/\/www\.dailymotion\.com\/video\//g, all = document.getElementsByTagName( "html" )[ 0 ].innerHTML.match( reSearch ), response = [], kill = function(){ alert( "This script have some problems, visit 'https://leonardociaccio.github.io/Awesome.Bookmarklets/' for new updates !" ); return false; }, success = function(){ alert( "Download links insert in to 'Information Tab' !" ); return false; }, noTarget = function(){ alert( "Use this bookmarklet on 'www.dailymotion.com/video/.....'" ); return false; }, _sanitizeName = function( name, replacer ){ replacer = replacer || "+"; return name.replace( /[^a-z 0-9]+/gi, "" ).replace( / /gi, replacer ); }, _getTitle = function( replacer ){ return ( document.title ) ? _sanitizeName( document.title, replacer ) : _sanitizeName( "Dailymotion Video", replacer ); }, dInfo = "<em><b>If after click download won't start use rigth click and 'Save as ...'</b></em>"; // Siamo sulla pagina giusta ? if( !reSite.test( document.location.href ) )return noTarget(); // Se non abbiamo i link generiamo un errore if( !all )return kill(); // Operazioni di pulizia for( var i = 0; i < all.length; i++ ){ var tmp = all[ i ].toString().replace( /\\/g, "" ), tsp = tmp.match( reFormat ); tsp = ( !tsp ) ? "Video " + ( i + 1 ) : tsp[ 0 ].toString() ; response.push( "<a href='" + tmp + "' title='" + _getTitle( "_" ) + "' download='" + _getTitle( "_" ) + "'>" + tsp + "</a>" ); } // Voglio inserlo nelle informazioni, se non lo trovo genero un errore var description = document.getElementById( "video_description" ); if( !description )return kill(); // Dedichiamo lo spazio per i download description.setAttribute( "style", "max-height:2000px!important" ); // Backup delle descrizioni var cc = description.innerHTML; // Aggiorniamo le descrizioni description.innerHTML = "<b>Download :</b><p>" + response.join( "</p><p>" ) + "</p><p>" + dInfo + "</p><hr><p>" + cc + "</p>"; // Compatibilità browser return success(); } )();
mit
nrser/qb
lib/qb/execution.rb
1988
# encoding: UTF-8 # frozen_string_literal: true # Requirements # ======================================================================= # Stdlib # ----------------------------------------------------------------------- # Deps # ----------------------------------------------------------------------- # Need mutable props mixin require 'nrser/props/immutable/instance_variables' # Need {Time#iso8601_for_idiots} require 'nrser/core_ext/time' # Project / Package # ----------------------------------------------------------------------- # Refinements # ======================================================================= # Declarations # ======================================================================= # Definitions # ======================================================================= # An object that encapsulates an execution of the QB program. # class QB::Execution # Constants # ======================================================================== # Mixins # ======================================================================== include NRSER::Props::Mutable::InstanceVariables # Class Methods # ======================================================================== # Props # ======================================================================== # @!attribute [r] prop :started_at, type: Time, writer: false, default: -> { Time.current } prop :pid, type: Fixnum, source: -> { Process.pid } prop :id, type: String, source: -> { "#{ self.started_at }-pid_#{ self.pid }" } # Construction # ======================================================================== # Instantiate a new `QB::Execution`. def initialize values = {} initialize_props values end # #initialize # Instance Methods # ======================================================================== end # class QB::Execution
mit
TeamworkGuy2/JTreeWalker
src/twg2/treeLike/IndexedTreeConsumer.java
265
package twg2.treeLike; /** * @param <T> the tree branch element type * @author TeamworkGuy2 * @since 2015-5-27 */ @FunctionalInterface public interface IndexedTreeConsumer<T> { public void accept(T branch, int index, int size, int depth, T parentBranch); }
mit
mbj/request
spec/unit/request/protocol/class_methods/get_spec.rb
685
require 'spec_helper' describe Request::Protocol, '.get' do let(:object) { described_class } subject { object.get(input) } context 'with "http"' do let(:input) { 'http' } it { should eql(Request::Protocol::HTTP) } end context 'with "https"' do let(:input) { 'https' } it { should eql(Request::Protocol::HTTPS) } end context 'with "ftp"' do let(:input) { 'ftp' } it 'should raise error' do # jruby has different message format expectation = begin {}.fetch('ftp') rescue KeyError => error error end expect { subject }.to raise_error(KeyError, expectation.message) end end end
mit
dougkoellmer/dougkoellmer_com
project/src/com/dougkoellmer/server/entities/ServerGrid.java
790
package com.dougkoellmer.server.entities; import java.util.logging.Logger; import com.dougkoellmer.shared.homecells.S_HomeCell; import swarm.server.entities.BaseServerGrid; import swarm.shared.json.A_JsonFactory; import swarm.shared.json.I_JsonObject; public class ServerGrid extends BaseServerGrid { private static final Logger s_logger = Logger.getLogger(ServerGrid.class.getName()); public ServerGrid() { this.m_cellHeight = this.m_cellWidth = S_HomeCell.DEFAULT_CELL_SIZE; this.m_cellPadding = S_HomeCell.CELL_PADDING; this.expandToSize(S_HomeCell.GRID_SIZE, S_HomeCell.GRID_SIZE); } @Override public void writeJson(I_JsonObject json_out, A_JsonFactory factory) { // do nothing cause we already know grid properties on the client through shared constants. } }
mit
zekewang918/QuitSmoking
bbs/source/plugin/mobile/api/1/seccode.php
1818
<?php /** * [Discuz!] (C)2001-2099 Comsenz Inc. * This is NOT a freeware, use is subject to license terms * * $Id: seccode.php 27959 2012-02-17 09:52:22Z monkey $ */ if(!defined('IN_MOBILE_API')) { exit('Access Denied'); } include_once 'misc.php'; class mobile_api { function common() { global $_G; require_once libfile('function/seccode'); $seccode = make_seccode($_GET['sechash']); if(!$_G['setting']['nocacheheaders']) { @header("Expires: -1"); @header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE); @header("Pragma: no-cache"); } require_once libfile('class/seccode'); $type = in_array($_G['setting']['seccodedata']['type'], array(2, 3)) ? 0 : $_G['setting']['seccodedata']['type']; $code = new seccode(); $code->code = $seccode; $code->type = $type; $code->width = $_G['setting']['seccodedata']['width']; $code->height = $_G['setting']['seccodedata']['height']; $code->background = $_G['setting']['seccodedata']['background']; $code->adulterate = $_G['setting']['seccodedata']['adulterate']; $code->ttf = $_G['setting']['seccodedata']['ttf']; $code->angle = $_G['setting']['seccodedata']['angle']; $code->warping = $_G['setting']['seccodedata']['warping']; $code->scatter = $_G['setting']['seccodedata']['scatter']; $code->color = $_G['setting']['seccodedata']['color']; $code->size = $_G['setting']['seccodedata']['size']; $code->shadow = $_G['setting']['seccodedata']['shadow']; $code->animator = 0; $code->fontpath = DISCUZ_ROOT.'./static/image/seccode/font/'; $code->datapath = DISCUZ_ROOT.'./static/image/seccode/'; $code->includepath = DISCUZ_ROOT.'./source/class/'; $code->display(); } function output() {} } ?>
mit
goodzsq/cocos_template
src/lib/cocos/component/DrawRect.js
1309
/** * DrawingBoard */ var Component = cc.Component.extend({ ctor: function(option){ this._super(); this.setName(option.name || 'DrawRect'); this._data = {}; }, onEnter: function(){ this._super(); var owner = this.getOwner(); this.drawNode = cc.DrawNode.create(); this.drawNode.zIndex = 99999; owner.addChild(this.drawNode); this.pos1 = cc.p(0,0); this.pos2 = cc.p(0,0); owner.addTouchEventListener(function(sender, type){ if(!this._data) return; if(type == 0){ this.drawing = true; var p = owner.getTouchBeganPosition(); this._data.x = p.x; this._data.y = p.y; this._data.width = 0; this._data.height = 0; }else if(type == 1){ var p = owner.getTouchMovePosition(); this._data.width = p.x - this._data.x; this._data.height = p.y - this._data.y; this.draw(); }else{ this.drawing = false; } }, this); }, setData: function(data){ this._data = data; this.draw(); }, draw: function(){ this.drawNode.clear(); var p1 = {x:this._data.x, y:this._data.y}; var p2 = {x:p1.x + this._data.width, y:p1.y + this._data.height}; this.drawNode.drawRect(p1, p2); } }); Component.create = function(option){ return new Component(option); } module.exports = Component;
mit
rkusa/hierarchical-router
test/client.js
2693
/*global suite, test, teardown */ var expect = require('chai').expect var router = require('./app/app') var stack = [] router.on('execute', function(path) { stack.push(path) }) teardown(function() { stack = [] }) suite('Client-Side', function() { test('initialize properly', function(done) { router.start('GET', '/a') router.on('started', function() { expect(window.history.state).to.be.ok expect(window.history.state.method).to.equal('GET') expect(window.history.state.path).to.equal('/a') expect(stack).to.have.lengthOf(0) done() }) }) test('pushState', function(done) { navigateTo('/a/b')(function() { expect(window.location.pathname).to.equal('/a/b') done() }) }) test('redirect', function(done) { var executed = false var root = router.get('/target', function(cont) { executed = true cont() }) root.get('/redirect', function(cont) { cont.redirect('../') }) router.on('navigated', function navigated(path) { expect(path).to.equal('/target/redirect') // expect(window.location.pathname).to.equal(expected || path) router.removeListener('navigated', navigated) router.removeAllListeners('pushState') router.on('pushState', function navigated(path) { expect(path).to.equal('/target') expect(window.location.pathname).to.equal(path) router.removeListener('pushState', navigated) expect(stack).to.eql([ '/target', '/target/redirect', '/target' ]) done() }) }) navigateTo('/target/redirect')() }) }) function navigateTo(path, method) { return function(done) { router.on('pushState', function navigated(to) { var pos if ((pos = path.indexOf('?')) !== -1) { path = path.substr(0, pos) } expect(path).to.equal(to) expect(window.location.pathname).to.equal(path) router.removeListener('pushState', navigated) done() }) var a = document.createElement('a') a.href = path document.body.appendChild(a) a.click() } } var Runnable = Mocha.Runnable var run = Runnable.prototype.run var co = require('co') /** * Override the Mocha function runner and enable generator support with co. * * @param {Function} fn */ Runnable.prototype.run = function (fn) { if (this.fn.toString().match(/wrapGenerator/) /*&& this.fn.constructor.name === 'GeneratorFunction'*/) { this.fn = co(this.fn()); this.sync = !(this.async = true); } return run.call(this, fn); }; require('./common')(router, navigateTo) require('./routing')(router, navigateTo)
mit
yonjah/hapi-flow-server
modules/runTimeout.js
682
'use strict'; // return a function that runs func in a minimum fixed timeout, // function will not be called until previous call is complete. module.exports = (function runTimeout (func, timeout) { var running = false, timer = 0, cb = function () { running =false; }, runner = function () { timer = clearTimeout(timer); if (running) { //didn't finish last call, try again after timeout timer = setTimeout(runner, timeout); return; } running = true; func().finally(cb); return; }; return (function timeoutRunner () { if (timer) { //do nothing since timer is already active return ; } timer = setTimeout(runner, timeout); }); });
mit
Klaital/HeatFlow
src/ublas_testing.cpp
484
#include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> #include <iostream> using namespace boost::numeric::ublas; /* "y = Ax" example */ int main() { vector<double> x (2); x(0) = 1; x(1) = 2; matrix<double> A(2,2); A(0,0) = 0; A(0,1) = 1; A(1,0) = 2; A(1,1) = 3; std::cout << A << std::endl; vector<double> y = prod(A, x); std::cout << y << std::endl; return 0; }
mit
berrygoudswaard/cakephp
src/Controller/Component/PaginatorComponent.php
15501
<?php /** * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) * @link https://cakephp.org CakePHP(tm) Project * @since 2.0.0 * @license https://opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Controller\Component; use Cake\Controller\Component; use Cake\Datasource\QueryInterface; use Cake\Datasource\RepositoryInterface; use Cake\Network\Exception\NotFoundException; use Cake\Utility\Hash; /** * This component is used to handle automatic model data pagination. The primary way to use this * component is to call the paginate() method. There is a convenience wrapper on Controller as well. * * ### Configuring pagination * * You configure pagination when calling paginate(). See that method for more details. * * @link https://book.cakephp.org/3.0/en/controllers/components/pagination.html */ class PaginatorComponent extends Component { /** * Default pagination settings. * * When calling paginate() these settings will be merged with the configuration * you provide. * * - `maxLimit` - The maximum limit users can choose to view. Defaults to 100 * - `limit` - The initial number of items per page. Defaults to 20. * - `page` - The starting page, defaults to 1. * - `whitelist` - A list of parameters users are allowed to set using request * parameters. Modifying this list will allow users to have more influence * over pagination, be careful with what you permit. * * @var array */ protected $_defaultConfig = [ 'page' => 1, 'limit' => 20, 'maxLimit' => 100, 'whitelist' => ['limit', 'sort', 'page', 'direction'] ]; /** * Events supported by this component. * * @return array */ public function implementedEvents() { return []; } /** * Handles automatic pagination of model records. * * ### Configuring pagination * * When calling `paginate()` you can use the $settings parameter to pass in pagination settings. * These settings are used to build the queries made and control other pagination settings. * * If your settings contain a key with the current table's alias. The data inside that key will be used. * Otherwise the top level configuration will be used. * * ``` * $settings = [ * 'limit' => 20, * 'maxLimit' => 100 * ]; * $results = $paginator->paginate($table, $settings); * ``` * * The above settings will be used to paginate any Table. You can configure Table specific settings by * keying the settings with the Table alias. * * ``` * $settings = [ * 'Articles' => [ * 'limit' => 20, * 'maxLimit' => 100 * ], * 'Comments' => [ ... ] * ]; * $results = $paginator->paginate($table, $settings); * ``` * * This would allow you to have different pagination settings for `Articles` and `Comments` tables. * * ### Controlling sort fields * * By default CakePHP will automatically allow sorting on any column on the table object being * paginated. Often times you will want to allow sorting on either associated columns or calculated * fields. In these cases you will need to define a whitelist of all the columns you wish to allow * sorting on. You can define the whitelist in the `$settings` parameter: * * ``` * $settings = [ * 'Articles' => [ * 'finder' => 'custom', * 'sortWhitelist' => ['title', 'author_id', 'comment_count'], * ] * ]; * ``` * * Passing an empty array as whitelist disallows sorting altogether. * * ### Paginating with custom finders * * You can paginate with any find type defined on your table using the `finder` option. * * ``` * $settings = [ * 'Articles' => [ * 'finder' => 'popular' * ] * ]; * $results = $paginator->paginate($table, $settings); * ``` * * Would paginate using the `find('popular')` method. * * You can also pass an already created instance of a query to this method: * * ``` * $query = $this->Articles->find('popular')->matching('Tags', function ($q) { * return $q->where(['name' => 'CakePHP']) * }); * $results = $paginator->paginate($query); * ``` * * ### Scoping Request parameters * * By using request parameter scopes you can paginate multiple queries in the same controller action: * * ``` * $articles = $paginator->paginate($articlesQuery, ['scope' => 'articles']); * $tags = $paginator->paginate($tagsQuery, ['scope' => 'tags']); * ``` * * Each of the above queries will use different query string parameter sets * for pagination data. An example URL paginating both results would be: * * ``` * /dashboard?articles[page]=1&tags[page]=2 * ``` * * @param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\QueryInterface $object The table or query to paginate. * @param array $settings The settings/configuration used for pagination. * @return \Cake\Datasource\ResultSetInterface Query results * @throws \Cake\Network\Exception\NotFoundException */ public function paginate($object, array $settings = []) { $query = null; if ($object instanceof QueryInterface) { $query = $object; $object = $query->repository(); } $alias = $object->alias(); $options = $this->mergeOptions($alias, $settings); $options = $this->validateSort($object, $options); $options = $this->checkLimit($options); $options += ['page' => 1, 'scope' => null]; $options['page'] = (int)$options['page'] < 1 ? 1 : (int)$options['page']; list($finder, $options) = $this->_extractFinder($options); /* @var \Cake\Datasource\RepositoryInterface $object */ if (empty($query)) { $query = $object->find($finder, $options); } else { $query->applyOptions($options); } $cleanQuery = clone $query; $results = $query->all(); $numResults = count($results); $count = $numResults ? $cleanQuery->count() : 0; $defaults = $this->getDefaults($alias, $settings); unset($defaults[0]); $page = $options['page']; $limit = $options['limit']; $pageCount = (int)ceil($count / $limit); $requestedPage = $page; $page = max(min($page, $pageCount), 1); $request = $this->_registry->getController()->request; $order = (array)$options['order']; $sortDefault = $directionDefault = false; if (!empty($defaults['order']) && count($defaults['order']) == 1) { $sortDefault = key($defaults['order']); $directionDefault = current($defaults['order']); } $paging = [ 'finder' => $finder, 'page' => $page, 'current' => $numResults, 'count' => $count, 'perPage' => $limit, 'prevPage' => $page > 1, 'nextPage' => $count > ($page * $limit), 'pageCount' => $pageCount, 'sort' => key($order), 'direction' => current($order), 'limit' => $defaults['limit'] != $limit ? $limit : null, 'sortDefault' => $sortDefault, 'directionDefault' => $directionDefault, 'scope' => $options['scope'], ]; if (!$request->getParam('paging')) { $request->params['paging'] = []; } $request->params['paging'] = [$alias => $paging] + (array)$request->getParam('paging'); if ($requestedPage > $page) { throw new NotFoundException(); } return $results; } /** * Extracts the finder name and options out of the provided pagination options * * @param array $options the pagination options * @return array An array containing in the first position the finder name and * in the second the options to be passed to it */ protected function _extractFinder($options) { $type = !empty($options['finder']) ? $options['finder'] : 'all'; unset($options['finder'], $options['maxLimit']); if (is_array($type)) { $options = (array)current($type) + $options; $type = key($type); } return [$type, $options]; } /** * Merges the various options that Pagination uses. * Pulls settings together from the following places: * * - General pagination settings * - Model specific settings. * - Request parameters * * The result of this method is the aggregate of all the option sets combined together. You can change * config value `whitelist` to modify which options/values can be set using request parameters. * * @param string $alias Model alias being paginated, if the general settings has a key with this value * that key's settings will be used for pagination instead of the general ones. * @param array $settings The settings to merge with the request data. * @return array Array of merged options. */ public function mergeOptions($alias, $settings) { $defaults = $this->getDefaults($alias, $settings); $request = $this->_registry->getController()->request; $scope = Hash::get($settings, 'scope', null); $query = $request->getQueryParams(); if ($scope) { $query = Hash::get($request->getQueryParams(), $scope, []); } $request = array_intersect_key($query, array_flip($this->_config['whitelist'])); return array_merge($defaults, $request); } /** * Get the settings for a $model. If there are no settings for a specific model, the general settings * will be used. * * @param string $alias Model name to get settings for. * @param array $settings The settings which is used for combining. * @return array An array of pagination settings for a model, or the general settings. */ public function getDefaults($alias, $settings) { if (isset($settings[$alias])) { $settings = $settings[$alias]; } $defaults = $this->getConfig(); $maxLimit = isset($settings['maxLimit']) ? $settings['maxLimit'] : $defaults['maxLimit']; $limit = isset($settings['limit']) ? $settings['limit'] : $defaults['limit']; if ($limit > $maxLimit) { $limit = $maxLimit; } $settings['maxLimit'] = $maxLimit; $settings['limit'] = $limit; return $settings + $defaults; } /** * Validate that the desired sorting can be performed on the $object. Only fields or * virtualFields can be sorted on. The direction param will also be sanitized. Lastly * sort + direction keys will be converted into the model friendly order key. * * You can use the whitelist parameter to control which columns/fields are available for sorting. * This helps prevent users from ordering large result sets on un-indexed values. * * If you need to sort on associated columns or synthetic properties you will need to use a whitelist. * * Any columns listed in the sort whitelist will be implicitly trusted. You can use this to sort * on synthetic columns, or columns added in custom find operations that may not exist in the schema. * * @param \Cake\Datasource\RepositoryInterface $object Repository object. * @param array $options The pagination options being used for this request. * @return array An array of options with sort + direction removed and replaced with order if possible. */ public function validateSort(RepositoryInterface $object, array $options) { if (isset($options['sort'])) { $direction = null; if (isset($options['direction'])) { $direction = strtolower($options['direction']); } if (!in_array($direction, ['asc', 'desc'])) { $direction = 'asc'; } $options['order'] = [$options['sort'] => $direction]; } unset($options['sort'], $options['direction']); if (empty($options['order'])) { $options['order'] = []; } if (!is_array($options['order'])) { return $options; } $inWhitelist = false; if (isset($options['sortWhitelist'])) { $field = key($options['order']); $inWhitelist = in_array($field, $options['sortWhitelist'], true); if (!$inWhitelist) { $options['order'] = []; return $options; } } $options['order'] = $this->_prefix($object, $options['order'], $inWhitelist); return $options; } /** * Prefixes the field with the table alias if possible. * * @param \Cake\Datasource\RepositoryInterface $object Repository object. * @param array $order Order array. * @param bool $whitelisted Whether or not the field was whitelisted * @return array Final order array. */ protected function _prefix(RepositoryInterface $object, $order, $whitelisted = false) { $tableAlias = $object->alias(); $tableOrder = []; foreach ($order as $key => $value) { if (is_numeric($key)) { $tableOrder[] = $value; continue; } $field = $key; $alias = $tableAlias; if (strpos($key, '.') !== false) { list($alias, $field) = explode('.', $key); } $correctAlias = ($tableAlias === $alias); if ($correctAlias && $whitelisted) { // Disambiguate fields in schema. As id is quite common. if ($object->hasField($field)) { $field = $alias . '.' . $field; } $tableOrder[$field] = $value; } elseif ($correctAlias && $object->hasField($field)) { $tableOrder[$tableAlias . '.' . $field] = $value; } elseif (!$correctAlias && $whitelisted) { $tableOrder[$alias . '.' . $field] = $value; } } return $tableOrder; } /** * Check the limit parameter and ensure it's within the maxLimit bounds. * * @param array $options An array of options with a limit key to be checked. * @return array An array of options for pagination */ public function checkLimit(array $options) { $options['limit'] = (int)$options['limit']; if (empty($options['limit']) || $options['limit'] < 1) { $options['limit'] = 1; } $options['limit'] = max(min($options['limit'], $options['maxLimit']), 1); return $options; } }
mit
Waavi/url-shortener
tests/FactoryTest.php
889
<?php namespace Waavi\UrlShortener\Test; class FactoryTest extends TestCase { /** * @test */ public function it_creates_google_driver() { $factory = $this->app['urlshortener.factory']; $driver = $factory->make('google'); $this->assertInstanceOf(\Waavi\UrlShortener\Drivers\Google::class, $driver); } /** * @test */ public function it_creates_bitly_driver() { $factory = $this->app['urlshortener.factory']; $driver = $factory->make('bitly'); $this->assertInstanceOf(\Waavi\UrlShortener\Drivers\Bitly::class, $driver); } /** * @test */ public function it_throws_exception_on_invalid_name() { $this->expectException('InvalidArgumentException'); $factory = $this->app['urlshortener.factory']; $driver = $factory->make('random'); } }
mit
ArcticWarriors/snobot-2017
RobotCode/snobot2017/src/com/snobot2017/joystick/IOperatorJoystick.java
1267
package com.snobot2017.joystick; import com.snobot.lib.modules.IJoystick; /** * Joystick for interacting with the Gear Boss * * @author jbnol * */ public interface IOperatorJoystick extends IJoystick { enum GearBossPositions { NONE, UP, DOWN } /** * Is the catch rope button pressed? * * @return true if pressed */ boolean isCatchRope(); /** * Is the climb button pressed? * * @return true if pressed */ boolean isClimb(); /** * Is the green light toggle on? * * @return whether the green lights should be on */ boolean greenLightOn(); /** * Should the green light be on? * * @return True if the light should be on */ boolean blueLightOn(); /** * Returns UP if up button is pressed, DOWN, if down button is pressed, and * NONE, if neither buttons are pressed * * @return UP to move Gear Boss up, DOWN to move Gear Boss down, and NONE to * do nothing */ GearBossPositions moveGearBossToPosition(); /** * Indicates the joystick should be rumbling * * @param aRumble * True to rumble */ void setShouldRumble(boolean aRumble); }
mit
drazenzadravec/projects
nice/sdk/json/Skills/UpdateCampaignResponse.js
41
var UpdateCampaignResponse_Skills = { };
mit
plyschik/s3blog
src/AppBundle/Entity/Tag.php
4065
<?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * @ORM\Table(name="tag") * @ORM\Entity(repositoryClass="AppBundle\Repository\TagRepository") * @UniqueEntity(fields={"name"}, message="dashboard.tags.uniqueName") */ class Tag { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\ManyToOne(targetEntity="User", inversedBy="tags", cascade={"persist"}) * @ORM\JoinColumn(name="user_id", referencedColumnName="id") */ private $user; /** * @var string * * @ORM\Column(type="string", length=64) */ private $slug; /** * @var string * * @ORM\Column(type="string", length=32, unique=true) * * @Assert\NotBlank() * @Assert\Length(min=4, max=32) */ private $name; /** * @ORM\Column(type="datetime") * @Gedmo\Timestampable(on="create") */ private $createdAt; /** * @ORM\Column(type="datetime") * @Gedmo\Timestampable(on="update") */ private $updatedAt; /** * @ORM\ManyToMany(targetEntity="Post", mappedBy="tags") */ private $posts; /** * Constructor */ public function __construct() { $this->posts = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set slug * * @param string $slug * * @return Tag */ public function setSlug($slug) { $this->slug = $slug; return $this; } /** * Get slug * * @return string */ public function getSlug() { return $this->slug; } /** * Set name * * @param string $name * * @return Tag */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set createdAt * * @param \DateTime $createdAt * * @return Tag */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; return $this; } /** * Get createdAt * * @return \DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * Set updatedAt * * @param \DateTime $updatedAt * * @return Tag */ public function setUpdatedAt($updatedAt) { $this->updatedAt = $updatedAt; return $this; } /** * Get updatedAt * * @return \DateTime */ public function getUpdatedAt() { return $this->updatedAt; } /** * Set user * * @param \AppBundle\Entity\User $user * * @return Tag */ public function setUser(\AppBundle\Entity\User $user = null) { $this->user = $user; return $this; } /** * Get user * * @return \AppBundle\Entity\User */ public function getUser() { return $this->user; } /** * Add post * * @param \AppBundle\Entity\Post $post * * @return Tag */ public function addPost(\AppBundle\Entity\Post $post) { $this->posts[] = $post; return $this; } /** * Remove post * * @param \AppBundle\Entity\Post $post */ public function removePost(\AppBundle\Entity\Post $post) { $this->posts->removeElement($post); } /** * Get posts * * @return \Doctrine\Common\Collections\Collection */ public function getPosts() { return $this->posts; } }
mit
andelf/rust-sdl2_gfx
src/sdl2_gfx/lib.rs
288
/*! A binding for SDL2_gfx. */ extern crate libc; extern crate num; extern crate sdl2; extern crate sdl2_sys as sys; extern crate c_vec; // Setup linking for all targets. #[link(name="SDL2_gfx")] extern {} pub mod primitives; pub mod rotozoom; pub mod framerate; pub mod imagefilter;
mit
tpolecat/doobie
modules/core/src/test/scala/doobie/util/YoloSuite.scala
657
// Copyright (c) 2013-2020 Rob Norris and Contributors // This software is licensed under the MIT License (MIT). // For more information see LICENSE or https://opensource.org/licenses/MIT package doobie package util import cats.effect.IO import doobie.util.yolo._ class YoloSuite extends munit.FunSuite { // Kind of a bogus test; just checking for compilation test("YOLO checks should compile for Query, Query0, Update, Update0") { lazy val dontRun = { val y = new Yolo[IO](null); import y._ (null : Query0[Int]).check (null : Query[Int, Int]).check Update0("", None).check Update[Int]("", None).check } } }
mit
laserlemon/periscope
spec/support/adapters/active_record/database_cleaner.rb
221
require File.expand_path("../connection", __FILE__) require "database_cleaner" DatabaseCleaner["active_record"].strategy = :truncation RSpec.configure do |config| config.before do DatabaseCleaner.clean end end
mit
rahuldhawani/whatsOnGmail
app/components/version/version-directive.js
203
'use strict'; angular.module('gmailChat.version.version-directive', []) .directive('appVersion', ['version', function(version) { return function(scope, elm, attrs) { elm.text(version); }; }]);
mit
rcos/Observatory3
Gruntfile.js
22225
// Generated on 2016-03-12 using generator-angular-fullstack 3.4.0 'use strict'; module.exports = function (grunt) { var localConfig; try { localConfig = require('./server/config/local.env'); } catch(e) { localConfig = {}; } // Load grunt tasks automatically, when needed require('jit-grunt')(grunt, { express: 'grunt-express-server', useminPrepare: 'grunt-usemin', ngtemplates: 'grunt-angular-templates', cdnify: 'grunt-google-cdn', protractor: 'grunt-protractor-runner', buildcontrol: 'grunt-build-control', bower: 'grunt-bower-task', auto_install: 'grunt-auto-install', istanbul_check_coverage: 'grunt-mocha-istanbul', ngconstant: 'grunt-ng-constant' }); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Define the configuration for all the tasks grunt.initConfig({ // Project settings pkg: grunt.file.readJSON('package.json'), yeoman: { // configurable paths client: require('./bower.json').appPath || 'client', server: 'server', dist: 'dist' }, changed: { options: { cache: '.changed_cache' } }, express: { options: { port: process.env.PORT || 9000 }, dev: { options: { script: '<%= yeoman.server %>', debug: true } }, prod: { options: { script: '<%= yeoman.dist %>/<%= yeoman.server %>' } } }, open: { server: { url: 'http://localhost:<%= express.options.port %>' } }, bower: { options: { targetDir: 'client/bower_components', layout: 'byType', install: true, verbose: false, cleanTargetDir: false, cleanBowerDir: false, bowerOptions: {} }, all: { src: ['bower.json','.bowerrc'], } }, auto_install: { all:{ local: {}, subdir: { options: { bower: false } }, src: ['package.json'], } }, watch: { installBower: { files: ['bower.json','.bowerrc'], tasks: ['changed:bower'] }, bower: { files: ['bower.json'], tasks: ['wiredep'] }, installNPM: { files: ['package.json'], tasks: ['changed:auto_install'] }, babel: { files: ['<%= yeoman.client %>/{app,components}/**/!(*.spec|*.mock).js'], tasks: ['newer:babel:client'] }, ngconstant: { files: ['<%= yeoman.server %>/config/environment/shared.js'], tasks: ['ngconstant'] }, injectJS: { files: [ '<%= yeoman.client %>/{app,components}/**/!(*.spec|*.mock).js', '!<%= yeoman.client %>/app/app.js' ], tasks: ['injector:scripts'] }, injectCss: { files: ['<%= yeoman.client %>/{app,components}/**/*.css'], tasks: ['injector:css'] }, mochaTest: { files: ['<%= yeoman.server %>/**/*.{spec,integration}.js'], tasks: ['env:test', 'mochaTest'] }, jsTest: { files: ['<%= yeoman.client %>/{app,components}/**/*.{spec,mock}.js'], tasks: ['newer:jshint:all', 'wiredep:test', 'karma'] }, injectLess: { files: ['<%= yeoman.client %>/{app,components}/**/*.less'], tasks: ['injector:less'] }, less: { files: ['<%= yeoman.client %>/{app,components}/**/*.less'], tasks: ['less', 'postcss'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { files: [ '{.tmp,<%= yeoman.client %>}/{app,components}/**/*.{css,html}', '{.tmp,<%= yeoman.client %>}/{app,components}/**/!(*.spec|*.mock).js', '<%= yeoman.client %>/assets/images/{,*//*}*.{png,jpg,jpeg,gif,webp,svg}' ], options: { livereload: true } }, express: { files: ['<%= yeoman.server %>/**/*.{js,json}'], tasks: ['express:dev', 'wait'], options: { livereload: true, spawn: false //Without this option specified express won't be reloaded } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '<%= yeoman.client %>/.jshintrc', reporter: require('jshint-stylish') }, server: { options: { jshintrc: '<%= yeoman.server %>/.jshintrc' }, src: ['<%= yeoman.server %>/**/!(*.spec|*.integration).js'] }, serverTest: { options: { jshintrc: '<%= yeoman.server %>/.jshintrc-spec' }, src: ['<%= yeoman.server %>/**/*.{spec,integration}.js'] }, all: ['<%= yeoman.client %>/{app,components}/**/!(*.spec|*.mock|app.constant).js'], test: { src: ['<%= yeoman.client %>/{app,components}/**/*.{spec,mock}.js'] } }, jscs: { options: { config: ".jscsrc" }, main: { files: { src: [ '<%= yeoman.client %>/app/**/*.js', '<%= yeoman.server %>/**/*.js' ] } } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/!(.git*|.openshift|Procfile)**' ] }] }, server: '.tmp' }, // Add vendor prefixed styles postcss: { options: { map: true, processors: [ require('autoprefixer')({browsers: ['last 2 version']}) ] }, dist: { files: [{ expand: true, cwd: '.tmp/', src: '{,*/}*.css', dest: '.tmp/' }] } }, // Debugging with node inspector 'node-inspector': { custom: { options: { 'web-host': 'localhost' } } }, // Use nodemon to run server in debug mode with an initial breakpoint nodemon: { debug: { script: '<%= yeoman.server %>', options: { nodeArgs: ['--debug-brk'], env: { PORT: process.env.PORT || 9000 }, callback: function (nodemon) { nodemon.on('log', function (event) { console.log(event.colour); }); // opens browser on initial server start nodemon.on('config:update', function () { setTimeout(function () { require('open')('http://localhost:8080/debug?port=5858'); }, 500); }); } } } }, // Automatically inject Bower components into the app and karma.conf.js wiredep: { options: { exclude: [ /bootstrap.js/, '/json3/', '/es5-shim/', /font-awesome\.css/, /bootstrap\.css/, /bootstrap-social\.css/ ] }, client: { src: '<%= yeoman.client %>/index.html', ignorePath: '<%= yeoman.client %>/', }, test: { src: './karma.conf.js', devDependencies: true } }, // Renames files for browser caching purposes filerev: { dist: { src: [ '<%= yeoman.dist %>/<%= yeoman.client %>/!(bower_components){,*/}*.{js,css}', '<%= yeoman.dist %>/<%= yeoman.client %>/assets/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' ] } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: ['<%= yeoman.client %>/index.html'], options: { dest: '<%= yeoman.dist %>/<%= yeoman.client %>' } }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { html: ['<%= yeoman.dist %>/<%= yeoman.client %>/{,!(bower_components)/**/}*.html'], css: ['<%= yeoman.dist %>/<%= yeoman.client %>/!(bower_components){,*/}*.css'], js: ['<%= yeoman.dist %>/<%= yeoman.client %>/!(bower_components){,*/}*.js'], options: { assetsDirs: [ '<%= yeoman.dist %>/<%= yeoman.client %>', '<%= yeoman.dist %>/<%= yeoman.client %>/assets/images' ], // This is so we update image references in our ng-templates patterns: { css: [ [/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the CSS to reference our revved images'] ], js: [ [/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images'] ] } } }, // The following *-min tasks produce minified files in the dist folder imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.client %>/assets/images', src: '{,*/}*.{png,jpg,jpeg,gif,svg}', dest: '<%= yeoman.dist %>/<%= yeoman.client %>/assets/images' }] } }, // Allow the use of non-minsafe AngularJS files. Automatically makes it // minsafe compatible so Uglify does not destroy the ng references ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat', src: '**/*.js', dest: '.tmp/concat' }] } }, // Dynamically generate angular constant `appConfig` from // `server/config/environment/shared.js` ngconstant: { options: { name: 'observatory3App.constants', dest: '<%= yeoman.client %>/app/app.constant.js', deps: [], wrap: true, configPath: '<%= yeoman.server %>/config/environment/shared' }, app: { constants: function() { return { appConfig: require('./' + grunt.config.get('ngconstant.options.configPath')) }; } } }, // Package all the html partials into a single javascript payload ngtemplates: { options: { // This should be the name of your apps angular module module: 'observatory3App', htmlmin: { collapseBooleanAttributes: true, collapseWhitespace: true, removeAttributeQuotes: true, removeEmptyAttributes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true }, usemin: 'app/app.js' }, main: { cwd: '<%= yeoman.client %>', src: ['{app,components}/**/*.html'], dest: '.tmp/templates.js' }, tmp: { cwd: '.tmp', src: ['{app,components}/**/*.html'], dest: '.tmp/tmp-templates.js' } }, // Replace Google CDN references cdnify: { dist: { html: ['<%= yeoman.dist %>/<%= yeoman.client %>/*.html'] } }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.client %>', dest: '<%= yeoman.dist %>/<%= yeoman.client %>', src: [ '*.{ico,png,txt}', '.htaccess', 'bower_components/**/*', 'assets/images/{,*/}*.{webp}', 'assets/fonts/**/*', 'index.html' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/<%= yeoman.client %>/assets/images', src: ['generated/*'] }, { expand: true, dest: '<%= yeoman.dist %>', src: [ 'package.json', '<%= yeoman.server %>/**/*', '!<%= yeoman.server %>/config/local.env.sample.js' ] }] }, styles: { expand: true, cwd: '<%= yeoman.client %>', dest: '.tmp/', src: ['{app,components}/**/*.css'] } }, buildcontrol: { options: { dir: '<%= yeoman.dist %>', commit: true, push: true, connectCommits: false, message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%' }, heroku: { options: { remote: 'heroku', branch: 'master' } }, openshift: { options: { remote: 'openshift', branch: 'master' } } }, // Run some tasks in parallel to speed up the build process concurrent: { pre: [ 'injector:less', 'ngconstant' ], server: [ 'newer:babel:client', 'less', ], test: [ 'newer:babel:client', 'less', ], debug: { tasks: [ 'nodemon', 'node-inspector' ], options: { logConcurrentOutput: true } }, dist: [ 'newer:babel:client', 'less', 'imagemin' ] }, // Test settings karma: { unit: { configFile: 'karma.conf.js', singleRun: true } }, mochaTest: { options: { reporter: 'spec', require: 'mocha.conf.js', timeout: 5000 // set default mocha spec timeout }, unit: { src: ['<%= yeoman.server %>/**/*.spec.js'] }, integration: { src: ['<%= yeoman.server %>/**/*.integration.js'] } }, mocha_istanbul: { unit: { options: { excludes: ['**/*.{spec,mock,integration}.js'], reporter: 'spec', require: ['mocha.conf.js'], mask: '**/*.spec.js', coverageFolder: 'coverage/server/unit' }, src: '<%= yeoman.server %>' }, integration: { options: { excludes: ['**/*.{spec,mock,integration}.js'], reporter: 'spec', require: ['mocha.conf.js'], mask: '**/*.integration.js', coverageFolder: 'coverage/server/integration' }, src: '<%= yeoman.server %>' } }, istanbul_check_coverage: { default: { options: { coverageFolder: 'coverage/**', check: { lines: 80, statements: 80, branches: 80, functions: 80 } } } }, protractor: { options: { configFile: 'protractor.conf.js' }, chrome: { options: { args: { browser: 'chrome' } } } }, env: { test: { NODE_ENV: 'test' }, prod: { NODE_ENV: 'production' }, all: localConfig }, // Compiles ES6 to JavaScript using Babel babel: { options: { sourceMap: true, optional: [ 'es7.classProperties' ] }, client: { files: [{ expand: true, cwd: '<%= yeoman.client %>', src: ['{app,components}/**/!(*.spec).js'], dest: '.tmp' }] }, server: { options: { optional: ['runtime'] }, files: [{ expand: true, cwd: '<%= yeoman.server %>', src: [ '**/*.js', '!config/local.env.sample.js' ], dest: '<%= yeoman.dist %>/<%= yeoman.server %>' }] } }, // Compiles Less to CSS less: { server: { files: { '.tmp/app/app.css' : '<%= yeoman.client %>/app/app.less' } } }, injector: { options: {}, // Inject application script files into index.html (doesn't include bower) scripts: { options: { transform: function(filePath) { var yoClient = grunt.config.get('yeoman.client'); filePath = filePath.replace('/' + yoClient + '/', ''); filePath = filePath.replace('/.tmp/', ''); return '<script src="' + filePath + '"></script>'; }, sort: function(a, b) { var module = /\.module\.(js|ts)$/; var aMod = module.test(a); var bMod = module.test(b); // inject *.module.js first return (aMod === bMod) ? 0 : (aMod ? -1 : 1); }, starttag: '<!-- injector:js -->', endtag: '<!-- endinjector -->' }, files: { '<%= yeoman.client %>/index.html': [ [ '<%= yeoman.client %>/{app,components}/**/!(*.spec|*.mock).js', '!{.tmp,<%= yeoman.client %>}/app/app.{js,ts}' ] ] } }, // Inject component less into app.less less: { options: { transform: function(filePath) { var yoClient = grunt.config.get('yeoman.client'); filePath = filePath.replace('/' + yoClient + '/app/', ''); filePath = filePath.replace('/' + yoClient + '/components/', '../components/'); return '@import \'' + filePath + '\';'; }, starttag: '// injector', endtag: '// endinjector' }, files: { '<%= yeoman.client %>/app/app.less': [ '<%= yeoman.client %>/{app,components}/**/*.less', '!<%= yeoman.client %>/app/app.less' ] } }, // Inject component css into index.html css: { options: { transform: function(filePath) { var yoClient = grunt.config.get('yeoman.client'); filePath = filePath.replace('/' + yoClient + '/', ''); filePath = filePath.replace('/.tmp/', ''); return '<link rel="stylesheet" href="' + filePath + '">'; }, starttag: '<!-- injector:css -->', endtag: '<!-- endinjector -->' }, files: { '<%= yeoman.client %>/index.html': [ '<%= yeoman.client %>/{app,components}/**/*.css' ] } } }, execute: { seed: { src: ['./server/config/seed.js'] } }, }); // Used for delaying livereload until after server has restarted grunt.registerTask('wait', function () { grunt.log.ok('Waiting for server reload...'); var done = this.async(); setTimeout(function () { grunt.log.writeln('Done waiting!'); done(); }, 1500); }); grunt.registerTask('express-keepalive', 'Keep grunt running', function() { this.async(); }); grunt.registerTask('serve', function (target) { if (target === 'dist') { return grunt.task.run(['changed:bower', 'changed:auto_install','build', 'env:all', 'env:prod', 'express:prod', 'wait', 'open', 'express-keepalive']); } if (target === 'debug') { return grunt.task.run([ 'clean:server', 'env:all', 'changed:bower', 'changed:auto_install', 'concurrent:pre', 'concurrent:server', 'injector', 'wiredep:client', 'postcss', 'concurrent:debug' ]); } grunt.task.run([ 'clean:server', 'env:all', 'changed:bower', 'changed:auto_install', 'concurrent:pre', 'concurrent:server', 'injector', 'wiredep:client', 'postcss', 'express:dev', 'wait', 'open', 'watch' ]); }); grunt.registerTask('server', function () { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run(['serve']); }); grunt.registerTask('test', function(target, option) { if (target === 'server') { return grunt.task.run([ 'env:all', 'env:test', 'mochaTest:unit', 'mochaTest:integration' ]); } else if (target === 'integration'){ return grunt.task.run([ 'env:all', 'env:test', 'mochaTest:integration' ]); } else if (target === 'client') { return grunt.task.run([ 'clean:server', 'env:all', 'concurrent:pre', 'concurrent:test', 'injector', 'postcss', 'wiredep:test', 'karma' ]); } else if (target === 'e2e') { if (option === 'prod') { return grunt.task.run([ 'build', 'env:all', 'env:prod', 'express:prod', 'protractor' ]); } else { return grunt.task.run([ 'clean:server', 'env:all', 'env:test', 'concurrent:pre', 'concurrent:test', 'injector', 'wiredep:client', 'postcss', 'express:dev', 'protractor' ]); } } else if (target === 'coverage') { if (option === 'unit') { return grunt.task.run([ 'env:all', 'env:test', 'mocha_istanbul:unit' ]); } else if (option === 'integration') { return grunt.task.run([ 'env:all', 'env:test', 'mocha_istanbul:integration' ]); } else if (option === 'check') { return grunt.task.run([ 'istanbul_check_coverage' ]); } else { return grunt.task.run([ 'env:all', 'env:test', 'mocha_istanbul', 'istanbul_check_coverage' ]); } } else grunt.task.run([ 'test:server', 'test:client' ]); }); grunt.registerTask('build', [ 'changed:bower', 'changed:auto_install', 'clean:dist', 'concurrent:pre', 'concurrent:dist', 'injector', 'wiredep:client', 'useminPrepare', 'postcss', 'ngtemplates', 'concat', 'ngAnnotate', 'copy:dist', 'babel:server', 'cdnify', 'cssmin', 'uglify', 'filerev', 'usemin' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); grunt.registerTask('seed', [ 'execute:seed' ]); };
mit
Autlo/stdlib
test/int.js
427
'use strict'; var assert = require('assert'); var int = require('../src/int'); describe('Int', function () { describe('#toHex', function () { it('Should pad hex string with zeros if needed', function () { assert.strictEqual(int.toHex(1), '01'); }); it('Should convert integer to hexadecimal', function () { assert.strictEqual(int.toHex(20), '14'); }); }); });
mit
anthonyreilly/NetCoreForce
src/NetCoreForce.Models/SfContentVersionHistory.cs
3586
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Content Version History ///<para>SObject Name: ContentVersionHistory</para> ///<para>Custom Object: False</para> ///</summary> public class SfContentVersionHistory : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "ContentVersionHistory"; } } ///<summary> /// Content Version ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// ContentVersion ID /// <para>Name: ContentVersionId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "contentVersionId")] [Updateable(false), Createable(false)] public string ContentVersionId { get; set; } ///<summary> /// ReferenceTo: ContentVersion /// <para>RelationshipName: ContentVersion</para> ///</summary> [JsonProperty(PropertyName = "contentVersion")] [Updateable(false), Createable(false)] public SfContentVersion ContentVersion { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Changed Field /// <para>Name: Field</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "field")] [Updateable(false), Createable(false)] public string Field { get; set; } ///<summary> /// Datatype /// <para>Name: DataType</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "dataType")] [Updateable(false), Createable(false)] public string DataType { get; set; } ///<summary> /// Old Value /// <para>Name: OldValue</para> /// <para>SF Type: anyType</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "oldValue")] [Updateable(false), Createable(false)] public string OldValue { get; set; } ///<summary> /// New Value /// <para>Name: NewValue</para> /// <para>SF Type: anyType</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "newValue")] [Updateable(false), Createable(false)] public string NewValue { get; set; } } }
mit
cuckata23/wurfl-data
data/sie_cf6c_ver1.php
186
<?php return array ( 'id' => 'sie_cf6c_ver1', 'fallback' => 'sie_cf62_ver1', 'capabilities' => array ( 'model_name' => 'CF6C', 'streaming_real_media' => 'none', ), );
mit
kocsismate/php-di-container-benchmarks
src/Fixture/B/FixtureB231.php
99
<?php declare(strict_types=1); namespace DiContainerBenchmarks\Fixture\B; class FixtureB231 { }
mit
MazaloOksana/MovieSerch
MovieSearch/MovieSearch/App_Start/FilterConfig.cs
265
using System.Web; using System.Web.Mvc; namespace MovieSearch { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
mit
ovac/hubtel-payment
tests/Unit/Api/ApiTest.php
6594
<?php /** * @package OVAC/Hubtel-Payment * @link https://github.com/ovac/hubtel-payment * * @author Ariama O. Victor (OVAC) <contact@ovac4u.com> * @link http://ovac4u.com * * @license https://github.com/ovac/hubtel-payment/blob/master/LICENSE * @copyright (c) 2017, RescopeNet, Inc */ namespace OVAC\HubtelPayment\Tests\Unit\Api; use GuzzleHttp\HandlerStack; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\Psr7\Response; use OVAC\HubtelPayment\Api\Api; use OVAC\HubtelPayment\Config; use OVAC\HubtelPayment\Exception\UnauthorizedException; use OVAC\HubtelPayment\Pay; use PHPUnit\Framework\TestCase; class ApiTest extends TestCase { /** * The OVAC/Hubtel-Payment Pay config. * * @var \OVAC\Hubtel\Config */ protected $config; protected function setUp() { $this->config = new Config( $accountNumber = 12345, $clientId = 'someClientId', $clientSecret = 'someClientSecret' ); } public function test_api_constructor_must_receive_config_type_constructor() { $this->expectException('TypeError'); $mock = $this->getMockBuilder(Api::class) ->setConstructorArgs([1]) ->getMockForAbstractClass(); } public function test_api_constructor_must_take_in_arguement() { $this->expectException('ArgumentCountError'); $mock = $this->getMockForAbstractClass(Api::class); } public function test_api_constructor_accepts_config_in_constructor() { $mock = $this->getMockBuilder(Api::class) ->setConstructorArgs([$this->config]) ->getMockForAbstractClass(); $this->assertAttributeEquals($this->config, 'config', $mock); $this->assertInstanceOf(Api::class, $mock->injectConfig($this->config), 'it should return Api::class instance'); } public function test_api_set_and_get_base_url() { $mock = $this->getMockBuilder(Api::class) ->setConstructorArgs([$this->config]) ->getMockForAbstractClass(); $mock->setBaseUrl('http://whateverurl.com'); $this->assertEquals($mock->getBaseUrl(), 'http://whateverurl.com', 'it should update baseUrl'); } public function test_api_http_methods() { $path = '/some_path'; $parameters = ['hello' => 'world']; $mock = $this->getMockBuilder(Api::class) ->disableOriginalConstructor() ->setMethods(['execute']) ->getMockForAbstractClass(); $mock->expects($this->exactly(7)) ->method('execute') ->withConsecutive( [$this->equalTo('get'), $this->equalTo($path), $this->equalTo($parameters)], [$this->equalTo('post'), $this->equalTo($path), $this->equalTo($parameters)], [$this->equalTo('put'), $this->equalTo($path), $this->equalTo($parameters)], [$this->equalTo('delete'), $this->equalTo($path), $this->equalTo($parameters)], [$this->equalTo('patch'), $this->equalTo($path), $this->equalTo($parameters)], [$this->equalTo('head'), $this->equalTo($path), $this->equalTo($parameters)], [$this->equalTo('options'), $this->equalTo($path), $this->equalTo($parameters)] ); $mock->_get($path, $parameters); $mock->_post($path, $parameters); $mock->_put($path, $parameters); $mock->_delete($path, $parameters); $mock->_patch($path, $parameters); $mock->_head($path, $parameters); $mock->_options($path, $parameters); } public function test_api_execute_methods_requires_config() { $this->expectException('RuntimeException'); $path = '/some_path'; $parameters = ['hello' => 'world']; $mock = $this->getMockBuilder(Api::class) ->disableOriginalConstructor() ->setMethods(['getClient']) ->getMockForAbstractClass(); $mock->_get($path, $parameters); } public function test_api_execute_throws_ClientException_if_server_gives_error() { $this->expectException(UnauthorizedException::class); $httpMock = new MockHandler([ new Response(401, ['X-Foo' => 'Bar']), ]); $handler = HandlerStack::create($httpMock); $path = '/some_path'; $parameters = ['hello' => 'world']; $mock = $this->getMockBuilder(Api::class) ->setConstructorArgs([$this->config]) ->setMethods(['createHandler']) ->getMockForAbstractClass(); $mock->expects($this->once()) ->method('createHandler') ->will($this->returnValue($handler)); $mock->_get($path, $parameters); } public function test_api_execute_test_successful_call() { $path = '/some_path'; $parameters = ['hello' => 'world']; $httpMock = new MockHandler([ new Response(200, ['X-Foo' => 'Bar'], json_encode($parameters)), ]); $handler = HandlerStack::create($httpMock); $mock = $this->getMockBuilder(Api::class) ->setConstructorArgs([$this->config]) ->setMethods(['createHandler']) ->getMockForAbstractClass(); $mock->expects($this->once()) ->method('createHandler') ->will($this->returnValue($handler)); $response = $mock->_get($path, $parameters); $this->assertSame(json_encode($response), json_encode($parameters)); } public static function callProtectedMethod($object, $method, array $args = array()) { $class = new \ReflectionClass(get_class($object)); $method = $class->getMethod($method); $method->setAccessible(true); return $method->invokeArgs($object, $args); } public function test_api_createHandler_method() { $mock = $this->getMockBuilder(Api::class) ->setConstructorArgs([$this->config]) ->getMockForAbstractClass(); $handlerStack = self::callProtectedMethod($mock, 'createHandler', [$this->config]); self::assertInstanceOf(HandlerStack::class, $handlerStack); } public function test_inject_config() { $mock = $this->getMockBuilder(Api::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); $mock->injectConfig($this->config); $this->assertSame($this->config, $mock->getConfig(), 'it should inject the configuration on the api'); } }
mit
codeborne/selenide
src/test/java/com/codeborne/selenide/conditions/NotTest.java
2863
package com.codeborne.selenide.conditions; import com.codeborne.selenide.CheckResult; import com.codeborne.selenide.Condition; import com.codeborne.selenide.Driver; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.openqa.selenium.WebElement; import static com.codeborne.selenide.CheckResult.Verdict.ACCEPT; import static com.codeborne.selenide.CheckResult.Verdict.REJECT; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class NotTest { Condition originalCondition = mock(Condition.class); Not notCondition; @BeforeEach void commonMockCalls() { // constructor call when(originalCondition.getName()).thenReturn("original condition name"); notCondition = new Not(originalCondition, false); } @AfterEach void verifyNoMoreInteractions() { // constructor call verify(originalCondition).getName(); Mockito.verifyNoMoreInteractions(originalCondition); } @Test void getName() { assertThat(notCondition.getName()).isEqualTo("not original condition name"); } @Test void actualValue() { Driver driver = mock(Driver.class); WebElement webElement = mock(WebElement.class); when(originalCondition.check(any(Driver.class), any(WebElement.class))) .thenReturn(new CheckResult(REJECT, "original condition actual value")); CheckResult checkResult = notCondition.check(driver, webElement); assertThat(checkResult.actualValue).isEqualTo("original condition actual value"); assertThat(checkResult.verdict).isEqualTo(ACCEPT); verify(originalCondition).check(driver, webElement); } @Test void applyFalse() { Driver driver = mock(Driver.class); WebElement webElement = mock(WebElement.class); when(originalCondition.check(any(Driver.class), any(WebElement.class))).thenReturn(new CheckResult(ACCEPT, "displayed")); assertThat(notCondition.check(driver, webElement)).isEqualTo(new CheckResult(REJECT, "displayed")); verify(originalCondition).check(driver, webElement); } @Test void applyTrue() { Driver driver = mock(Driver.class); WebElement webElement = mock(WebElement.class); when(originalCondition.check(any(Driver.class), any(WebElement.class))).thenReturn(new CheckResult(REJECT, "hidden")); assertThat(notCondition.check(driver, webElement)).isEqualTo(new CheckResult(ACCEPT, "hidden")); verify(originalCondition).check(driver, webElement); } @Test void hasToString() { when(originalCondition.toString()).thenReturn("original condition toString"); assertThat(notCondition).hasToString("not original condition toString"); } }
mit
instructure/ims-lti
lib/ims/lti/serializers/membership_service/membership_serializer.rb
213
module IMS::LTI::Serializers::MembershipService class MembershipSerializer < IMS::LTI::Serializers::Base set_attribute :id, key: :@id set_attributes :status, :role has_serializable :member end end
mit
djedi23/meteor-presentation
server/init.js
1027
Meteor.startup(function(){ if (! modules.collections.Presentations.findOne({name:'mypresentation'})) { modules.collections.Presentations.insert({ name: 'mypresentation', steps: [ {id:"s1", x:-1000, y:-1500, md: "rrezy: reactive prezentation", style:"clean", worldStyle:"clear" }, {id:"s2", x:0, y:-1500, "rotate":"270", "scale":"3", "rotateY":"45", md: "Don't you think that presentations given **in modern browsers** shouldn't **copy the limits** of 'classic' slide decks?", "interaction" : { "type" : "quiz", "data" : { "question" : "Question:", "responses" : [ { "k" : "r1", "l" : "reponse 1" }, { "k" : "r2", "l" : "reponse 2" } ] }} }, {id:"s3", x:1000, y:-1500, style:"clean", worldStyle:"blue", md: "Would you like to **impress your audience** with **stunning visualization** of your talk?" } ] }); } });
mit
neonbug/meexo-common
src/assets/admin_assets/js/ckeditor/config.js
411
/** * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.forcePasteAsPlainText = true; config.removePlugins = 'pastefromword'; };
mit
promlow/books-and-tutorials
accel-cpp/5/fail.cpp
380
#include "fail.h" #include "grade.h" using std::list; list<Student_info> extract_fails(list<Student_info>& students) { list<Student_info> fails; list<Student_info>::iterator iter = students.begin(); while (iter != students.end()) { if (fgrade(*iter)) { fails.push_back(*iter); iter = students.erase(iter); } else ++iter; } return fails; }
mit
postfix/gocrud
helper/helper.go
1465
package helper import ( "net/http" "github.com/manishrjain/gocrud/api" "github.com/manishrjain/gocrud/req" "github.com/manishrjain/gocrud/x" ) type Entity struct { Id string `json:"id,omitempty"` Kind string `json:"kind,omitempty"` Data map[string]interface{} `json:"data,omitempty"` Child *Entity `json:"child,omitempty"` Source string `json:"source,omitempty"` } type Helper struct { ctx *req.Context } func (h *Helper) SetContext(c *req.Context) { h.ctx = c } func (h *Helper) CreateOrUpdate(w http.ResponseWriter, r *http.Request) { var e Entity if ok := x.ParseRequest(w, r, &e); !ok { return } if e.Child != nil { if len(e.Child.Id) > 0 { x.SetStatus(w, x.E_INVALID_REQUEST, "Child cannot have id specified") return } } if len(e.Id) == 0 || len(e.Kind) == 0 { x.SetStatus(w, x.E_INVALID_REQUEST, "No id or kind specified") return } if len(e.Source) == 0 { x.SetStatus(w, x.E_INVALID_REQUEST, "No source specified") return } n := api.Get(e.Kind, e.Id).SetSource(e.Source) for key, val := range e.Data { n.Set(key, val) } if e.Child != nil { c := n.AddChild(e.Child.Kind) if len(e.Child.Source) > 0 { c.SetSource(e.Child.Source) } for key, val := range e.Child.Data { c.Set(key, val) } } if err := n.Execute(h.ctx); err != nil { x.SetStatus(w, x.E_ERROR, err.Error()) return } x.SetStatus(w, x.E_OK, "Stored") }
mit
oriondean/typescript-angular-bitcoin-exchange
client/src/app/order-depth/order-depth-order.ts
104
export class OrderDepthOrder { constructor(public price: number, public quantity: number) { } }
mit
devkimchi/HAL-Swagger-Sample
src/HalSwaggerSample.HalApiApp/App_Start/WebApiConfig.cs
1355
using System; using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; using Owin; namespace HalSwaggerSample.HalApiApp { /// <summary> /// This represents the config entity for Web API. /// </summary> public static class WebApiConfig { /// <summary> /// Configures the Web API. /// </summary> /// <param name="builder"> /// The <see cref="IAppBuilder" /> instance. /// </param> /// <param name="container"> /// The <see cref="IContainer" /> instance. /// </param> public static void Configure(IAppBuilder builder, IContainer container) { if (builder == null) { throw new ArgumentNullException("builder"); } if (container == null) { throw new ArgumentNullException("container"); } var config = new HttpConfiguration() { DependencyResolver = new AutofacWebApiDependencyResolver(container), }; // Routes config.MapHttpAttributeRoutes(); // HAL config.ConfigHal(); // Swagger config.ConfigSwagger(); builder.UseWebApi(config); } } }
mit
endjin/Endjin.Licensing
Solutions/Endjin.Licensing.Demo.ClientApp/Properties/AssemblyInfo.cs
1497
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Endjin.Licensing.Demo.ClientApp")] [assembly: AssemblyDescription("Example Client App demonstrating how to create custom validation rules & exceptions.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Endjin Limited")] [assembly: AssemblyProduct("Endjin.Licensing.Demo.ClientApp")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1d96414c-5945-4db5-9744-a2d5097473db")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
txstate-etc/attendance
app/models/membership.rb
3839
class Membership < ActiveRecord::Base attr_accessible :active, :sourcedid belongs_to :site, :inverse_of => :memberships belongs_to :user, :inverse_of => :memberships has_many :userattendances, :dependent => :destroy has_and_belongs_to_many :sections, :after_add => :react_to_recordedstatus_change, :after_remove => :react_to_lost_section has_and_belongs_to_many :siteroles, :after_add => :react_to_recordedstatus_change after_update :react_to_status_change def react_to_status_change if self.active_changed? && self.record_attendance? self.total_meetings.each do |m| Userattendance.record_attendance(m.id, self.id, default_atype.id) if m.starttime > Time.zone.now end end true end after_create :react_to_new_memberships def react_to_new_memberships return true unless self.record_attendance? now = Time.zone.now self.total_meetings.each do |m| # all past meetings are set to the created_default (probably 'Excused' or something like that) # all future meetings are set to the default based on their membership status Userattendance.record_attendance(m.id, self.id, m.starttime >= now ? default_atype.id : Attendancetype.created_default.id) end true end def react_to_recordedstatus_change(siterole) if self.record_attendance? mtgs = self.total_meetings untouchables = {} Userattendance.where(:meeting_id => mtgs.map(&:id), :membership_id => self.id).each do |ua| untouchables[ua.meeting_id.to_s+ua.membership_id.to_s] = true; end now = Time.zone.now mtgs.each do |m| if m.starttime > now || !untouchables[m.id.to_s+self.id.to_s] Userattendance.record_attendance(m.id, self.id, m.starttime >= now ? default_atype.id : Attendancetype.created_default.id) end end end end def react_to_lost_section(section) Userattendance.includes(:meeting => :section).where(:meetings => { :section_id => section.id }).where('meetings.starttime > ?', Time.zone.now).destroy_all(:membership_id => self.id) end def remove_from_section(section) Userattendance.includes(:meeting => :section).where(:meetings => { :section_id => section.id }).destroy_all(:membership_id => self.id) self.sections.destroy(section) if self.sections.empty? self.destroy end end def total_meetings recorded_sections.map(&:valid_meetings).flatten end def set_permissions? siteroles.any? { |sr| sr.set_permissions? } end def record_attendance? siteroles.any? { |sr| sr.record_attendance? } end def take_attendance? siteroles.any? { |sr| sr.take_attendance? } end def edit_gradesettings? siteroles.any? { |sr| sr.edit_gradesettings? } end def default_atype self.active ? Attendancetype.default : Attendancetype.inactive_default end def valid_attendances(section) @valid_attendances ||= {} @valid_attendances[section.id] ||= userattendances.includes(:meeting => :section).where(:meetings => { :cancelled => false, :deleted => false, :section_id => section }) end def recorded_attendances(section) @recorded_attendances ||= {} @recorded_attendances[section.id] ||= valid_attendances(section).where('meetings.starttime < ?', Time.zone.now).order('meetings.starttime') end def appearances(section) @appearances ||= {} @appearances[section.id] ||= recorded_attendances(section).select { |ua| !ua.cached_attendancetype.absent } end def last_attended(section) appearances(section).map(&:meeting).map(&:starttime).max end def recorded_meetings(section) @valid_meetings ||= {} @valid_meetings[section.id] ||= section.valid_meetings.where('starttime < ?', Time.zone.now) end def recorded_sections sections || [site.default_section] end end
mit
apita1973/oauthexample
api.go
2092
package main import ( "errors" "fmt" "io/ioutil" "log" "net/http" "code.google.com/p/gcfg" "github.com/codegangsta/martini" "golang.org/x/net/context" "golang.org/x/oauth2" ) type Config struct { Oauth struct { ClientID string ClientSecret string } } var ( cfg Config conf *oauth2.Config state = "secret_state" ) func init() { err := gcfg.ReadFileInto(&cfg, "conf.gcfg") if err != nil { log.Fatalf("Trouble reading config: %s", err) } conf = &oauth2.Config{ ClientID: cfg.Oauth.ClientID, ClientSecret: cfg.Oauth.ClientSecret, Scopes: []string{"https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/userinfo.profile"}, Endpoint: oauth2.Endpoint{ AuthURL: "https://accounts.google.com/o/oauth2/auth", TokenURL: "https://accounts.google.com/o/oauth2/token", }, RedirectURL: "https://localhost:8001/oauth2callback", } } func GetAuthCodeUrl() string { url := conf.AuthCodeURL(state, oauth2.AccessTypeOnline) return url } func GetUserInfo(w http.ResponseWriter, r *http.Request, params martini.Params) string { token, err := GetToken(r, params) if err != nil { return err.Error() } info, err := RequestUserInfo(token.AccessToken) if err != nil { return err.Error() } return info } func RequestUserInfo(token string) (string, error) { reqUrl := "https://www.googleapis.com/oauth2/v1/userinfo?alt=json" req := fmt.Sprintf("%s&access_token=%s", reqUrl, token) response, err := http.Get(req) if err != nil { return "", err } defer response.Body.Close() info, err := ioutil.ReadAll(response.Body) if err != nil { return "", err } return string(info), nil } func GetToken(r *http.Request, params martini.Params) (*oauth2.Token, error) { qs := r.URL.Query() if qs.Get("state") != state { return nil, errors.New("State returned from auth server does not match!") } code := qs.Get("code") if code == "" { return nil, errors.New("Unable to acquire code!") } token, err := conf.Exchange(context.TODO(), code) if err != nil { return nil, err } return token, nil }
mit
azer/domloader
build/domloader-v1.0rc9.js
28639
var domloader = (function(globals,undefined){ var jsbuild = (function(){ var cache = {}; function Module(){ this.exports = null; this.fileName = null; this.id = null; this.workingDir = null; this.wrapper = null; }; Module.prototype.call = function(){ this.exports = {}; return this.wrapper.call(null, this.exports, this, partial(require, [ this.workingDir ], null), globals); }; function defineModule(path,modwrapper){ var module = new Module(); module.wrapper = modwrapper; module.fileName = path; module.id = getId( module.fileName ); module.workingDir = getDir( module.fileName ); cache[module.fileName] = module; return module; }; function getDir(path){ return path.replace(/\/?[^\/]*$/,""); } function getId(path){ var name = path.match(/\/?([\w_-]+)\.js$/); name && ( name = name[1] ); return name; }; function getModuleByFilename(filename){ return cache[filename]; } function partial(fn,init_args,scope){   !init_args && ( init_args = [] );   return function(){     var args = Array.prototype.slice.call(init_args,0);     Array.prototype.push.apply(args,arguments);     return fn.apply(scope,args);   }; }; function resolvePath(path,wd){   if(path.substring(0,1) == '/' || /^\w+\:\/\//.test(path)) return path;   /\/$/.test(wd) && ( wd = wd.substring(0,wd.length-1) );   /^\.\//.test(path) && ( path = path.substring(2,path.length) );   if(path.substring(0,3)=='../'){     var lvl = path.match(/^(?:\.\.\/)+/)[0].match(/\//g).length;     wd = wd.replace(new RegExp("(\\/?\\w+){"+lvl+"}$"),'');     path = path.replace(new RegExp("(\\.\\.\\/){"+lvl+"}"),'');   };       return ( wd && wd+'/' || '' )+path; }; function require(workingDir,path){ !/\.js(\?.*)?$/.test(path) && ( path = path+'.js' ); var uri = resolvePath(path,workingDir), mod = cache[uri]; if(!mod) throw new Error('Cannot find module "'+path+'". (Working Dir:'+workingDir+', URI:'+uri+' )') mod.exports==null && mod.call(); return mod.exports; }; return { "Module":Module, "cache":cache, "defineModule":defineModule, "getDir":getDir, "getId":getId, "getModuleByFilename":getModuleByFilename, "partial":partial, "resolvePath":resolvePath, "require":require }; })(); return { '_jsbuild_':jsbuild, 'require':jsbuild.partial(jsbuild.require,['']) }; })(this); domloader._jsbuild_.defineModule("libs/utils.js",function(exports,module,require,globals,undefined){ var globals = this, dom = this.document, logger = require('./logger'); /** * Create new DOM node with nodeType set to 1, in concordance with global namespace */ var createElement = exports.createElement = function createElement(tagName){ return dom.documentElement.getAttribute('xmlns') && dom.createElementNS(dom.documentElement.getAttribute('xmlns'),tagName) || dom.createElement(tagName); } /** * Extract directory path from passed uri/url */ var dir = exports.dir = function dir(path){ return path.replace(/\/?[^\/]+$/,""); } /** * Provide simple inheritance by setting prototype and constructor of given subclass. */ var extend = exports.extend = function extend(subclass,superclass){ subclass.prototype = new superclass; subclass.prototype.constructor = subclass; }; var getFileNameExt = exports.getFileNameExt = function getFileNameExt(filename){ var match = filename.match(/\.(\w+)(?:\#.*)?$/); return match && match[1] || ''; } /** * Import the javascript document located in specified URL. */ var includeScript = exports.includeScript = function includeScript(url,callback,errback){ logger.debug('Trying to include the javascript file at "'+url+'"'); var el = createElement('script'); el.setAttribute('src',url); el.setAttribute('type','text/javascript'); //el.setAttribute('async',true); el.onload = el.onreadystatechange = function(){ if( this.readyState && this.readyState!='complete' && this.readyState!='loaded') return; logger.info('Loaded the javascript file at "'+url+'"'); callback(); }; el.onerror = el.onunload = function(){ var errmsg = 'Could not load the javascript file at "'+url+'"'; logger.error(errmsg); errback(errmsg); }; dom.getElementsByTagName('head')[0].appendChild(el); return el; }; /** * Test whether given URI is a relative path or not */ var isRelativePath = exports.isRelativePath = function isRelativePath(path){ return path && !path.match(/^\w+\:\/\//) && path.substring(0,1) != '/'; } /** * Returns the first index at which a given element can be found in the array, or -1 if it is not present. */ var getIndex = exports.getIndex = function getIndex(list,el){ if(list.indexOf) return list.indexOf(el); for(var i=-1,len=list.length; ++i<len;){ if( list[i] == el ) return i; } return -1; }; /** * Create and return a wrapper function executing given function with specified scope and arguments */ var partial = exports.partial = function partial(fn,init_args,scope){   !init_args && ( init_args = [] );   return function(){     var args = Array.prototype.slice.call(init_args,0);     Array.prototype.push.apply(args,arguments);     return fn.apply(scope,args);   }; }; /** * Depart the element located on specified index from given array */ var remove = exports.remove = function remove(list,index){ return index == -1 && list || list.slice(0,index).concat( list.slice(index+1) ); } /** * Take a string formatted namespace path and return latest object in the path which is existing and a list including names of the nonexistent ones in given order. * * Usage Examples: * >>> window.foo * { 'foo':314 } * >>> domloader.resolveNSPath( 'foo.bar' ); * { 'parentObject':{ 'foo':314 }, 'childrenNames':['bar'] } * >>> window.foo.bar = { 'bar':156 }; * >>> domloader.resolveNSPath( 'foo.bar.baz.qux.quux.corge.grault' ); * { 'parentObject':{ 'bar':156 }, 'childrenNames':['baz','qux','quux','corge','grault'] } */ var resolveNSPath = exports.resolveNSPath = function resolveNSPath(nspath,parentObject){ logger.debug('Resolving NS',nspath); var names = nspath && nspath.split('.') || []; var childName = null; parentObject = parentObject || globals; while( childName = names[0] ){ if( ! ( childName in parentObject ) ) break; parentObject = parentObject[ childName ]; names.splice(0,1); }; logger.info(' Resolved "',nspath,'" parentObject:',parentObject,'childrenNames',names.join(', ')); return { 'parentObject':parentObject, 'childrenNames':names }; }; }); domloader._jsbuild_.defineModule("libs/logger.js",function(exports,module,require,globals,undefined){ var enabled = exports.enabled = require('../config').debug, prefix = exports.prefix = 'DOMLoader', levels = exports.levels = ['debug','info','warn','error','critical']; var log = exports.log = function log(level){ if(!enabled || !this.console) return; var fn = console[level] || console.log; Array.prototype.splice.call(arguments, 0,1,prefix+' - '+level.toUpperCase()+' - '); return fn.apply(console, arguments ); }; for(var i = -1, len=levels.length; ++i < len; ) { var level = levels[i]; exports[level] = (function(level){ return function(){ Array.prototype.splice.call(arguments, 0,0,levels[level]); return log.apply(null,arguments); } })(i); }; }); domloader._jsbuild_.defineModule("libs/request.js",function(exports,module,require,globals,undefined){ var Observable = require('./observable').Observable, extend = require('./utils').extend, logger = require("./logger"); /** * An observable&cross browser wrapper of XMLHttpRequest class */ var Request = exports.Request = function Request(url){ Observable.prototype.constructor.call( this ); logger.debug('Initializing new HTTP request to',url); this.callbacks.load = []; this.callbacks.error = []; var req = this._req_ = typeof XMLHttpRequest != 'undefined' && new XMLHttpRequest || (function(){ try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {} throw new Error("This browser does not support XMLHttpRequest."); })(); var loadEmitter = this.getEmitter('load'); var errorEmitter = this.getEmitter('error'); req.open('GET',url,true); req.onreadystatechange = function(){ logger.info( ' Request state has changed', '(:url', url, ':readyState', req.readyState + ')' ); req.readyState == 4 && ( req.status == 200 ? loadEmitter(req) : errorEmitter(new Error("Could not load "+url+", readystate:"+req.readyState+" status:"+req.status)) ); }; }; extend( Request, Observable ); Request.prototype.send = function(){ this._req_.send(null); } }); domloader._jsbuild_.defineModule("libs/observable.js",function(exports,module,require,globals,undefined){ /** * Observable Class - By Azer Koculu <azerkoculu@gmail.com> (MIT Licensed) * * Represents observable objects which can have many subscribers in different subjects and have a property named "callbacks", storing observation subjects. * To emit events and solve the scope problem being encountered during observation chaining in a simple way, Observable objects also have getEmitter method * returning a function calling subscribers asynchronously for specified subject. */ var Observable = exports.Observable = function Observable(){   this.callbacks = {}; }; /** * Return a function calling subscribers asynchronously for specified subject. */ Observable.prototype.getEmitter = function(eventName){ if( !this.callbacks.hasOwnProperty(eventName) ) throw new Error("Invalid Event Name: "+eventName); var subscribers = this.callbacks[eventName]; return function(){ var args = Array.prototype.slice.call(arguments,0); for(var i = -1, len=subscribers.length; ++i < len; ) { if( typeof subscribers[i] != "function" ){ throw new Error('Invalid subscriber. Subject:'+eventName+', Index:'+i); } setTimeout((function(fn){ return function(){ fn.apply(null,args); }; })(subscribers[i]), 10 ); }; }; }; }); domloader._jsbuild_.defineModule("config.js",function(exports,module,require,globals,undefined){ exports.debug = true; exports.version = "1.0"; }); domloader._jsbuild_.defineModule("index.js",function(exports,module,require,globals,undefined){ var Dependency = require('./dependency').Dependency, utils = require("./libs/utils"), states = require("./states"), logger = require('./libs/logger'), dir = utils.dir, extend = utils.extend, getIndex = utils.getIndex, remove = utils.remove, resolveNSPath = utils.resolveNSPath; /** * Represent, store and load several DOM dependencies, initialize required namespace if needed */ var Index = exports.Index = function Index(){ Dependency.prototype.constructor.call(this); this.dependencies = []; this.ns = null; // this.wd = dir(location.href); }; extend( Index, Dependency ); Index.prototype.load = function(){ this.state = states.LOADING; var self = this; logger.debug('Loading Index','src:',this.src); var unloaded = this.dependencies.slice(0), self = this, loadEmitter = this.getEmitter('load'), errorEmitter = this.getEmitter('error'); logger.debug(unloaded); for(var i = -1, len=this.dependencies.length; ++i < len; ){ var dp = this.dependencies[i]; dp.callbacks.load.push((function(dp){ return function(){ logger.info(' Loaded:',dp.src); unloaded = remove( unloaded, getIndex(unloaded, dp) ); unloaded.length == 0 && loadEmitter(); } })(dp)); dp.callbacks.error.push(errorEmitter); try { logger.debug(' Loading Dependency',dp.src); dp.load(); }catch(exc){ logger.critical(exc.message); errorEmitter(exc); break; } }; unloaded.length == 0 && loadEmitter(); }; Index.prototype.setNS = function(){ logger.debug('Setting namespace of Index','src:',this.src,'ns:',this.ns); for(var path in this.ns){ logger.debug(' NS Path:',path); var res = resolveNSPath(path), parentObject = res.parentObject, key = null; while( key = res.childrenNames[0] ){ if( res.childrenNames.length == 1 ){ logger.debug(' Setting NS Property','key:',key,'Parent:',parentObject); parentObject[ key ] = this.ns[ path ]; break; } parentObject = parentObject[ key ] = {}; res.childrenNames.splice(0,1); } } }; }); domloader._jsbuild_.defineModule("domloader.js",function(exports,module,require,globals,undefined){ var config = require('./config'), createIndexFile = require("./indexfile").create, partial = require("./libs/utils").partial, dir = require('./libs/utils').dir; domloader.version = config.version; /** * Shortcut to initialize, import and load index documents. */ var load = exports.load = globals.domloader.load = function load(src,callback,errback){ var ind = createIndexFile({ 'src':src }); callback && ind.callbacks.load.push(callback); errback && ind.callbacks.error.push(errback); ind.load(); return ind; }; }); domloader._jsbuild_.defineModule("indexfile.js",function(exports,module,require,globals,undefined){ var Index = require('./index').Index, Request = require('./libs/request').Request, getFileNameExt = require('./libs/utils').getFileNameExt, maps = require('./maps'), utils = require("./libs/utils"), logger = require('./libs/logger'); var create = exports.create = function create(content,index){ var src = content['src']; logger.debug('Creating new IndexFile instance for the file at src:"'+src+'"'); var ind = maps.getConstructorByFormat(src).apply(null,arguments); ind.wd = utils.dir(src); logger.info(' Set WD as '+ind.wd) return ind; }; maps.types.widget = maps.types.application = maps.types.index = create; /** * Represents an external document containing dependency information */ var IndexFile = exports.IndexFile = function IndexFile(){ Index.prototype.constructor.call(this); this.content = null; this.src = null; this.callbacks.loadFile = []; }; utils.extend( IndexFile, Index ); IndexFile.prototype.importFileContent = function(){ logger.debug('Importing content of IndexFile instance, "'+this.src+'"'); this.ns = this.content['namespace']; for(var i = -1, len=this.content.dependencies.length; ++i < len; ){ var el = this.content.dependencies[i]; typeof el == 'string' && (el = { "src":el }); constructor = el.hasOwnProperty('type') && maps.getConstructorByType(el['type']) || maps.getConstructorByFormat(el['src']); utils.isRelativePath(el['src']) && this.wd && ( el['src'] = this.wd + '/' + el['src'] ); this.dependencies.push( constructor(el,this) ); }; }; IndexFile.prototype.load = function(){ this.callbacks.loadFile.push(utils.partial(function(req){ this.parseFile(req); this.importFileContent(); this.setNS(); Index.prototype.load.call(this); },[],this)); this.loadFile(); } IndexFile.prototype.loadFile = function(){ logger.debug('Loading index file "'+this.src+'"'); var req = new Request(this.src); req.callbacks.load.push( this.getEmitter('loadFile') ); req.callbacks.error.push( this.getEmitter('error') ); req.send(); return req; } IndexFile.prototype.parseFile = function(req){ this.content = req.responseText; } }); domloader._jsbuild_.defineModule("jsfile.js",function(exports,module,require,globals,undefined){ var Dependency = require('./dependency').Dependency, utils = require("./libs/utils"), maps = require('./maps'), logger= require('./libs/logger'), extend = utils.extend, includeScript = utils.includeScript; var create = exports.create = function create(content,index){ var jsf = new JSFile(); jsf.src = content['src']; return jsf; }; maps.formats.js = maps.types.js = maps.types.module = maps.types.script = create; /** * Represents a single Javascript file dependency */ var JSFile = exports.JSFile = function JSFile(){ Dependency.prototype.constructor.call(this); this.src = null; logger.info('Initialized new JSFile instance'); } extend( JSFile, Dependency ); JSFile.prototype.load = function(){ logger.debug('Trying to load JSFile "'+this.src+'"'); includeScript( this.src, this.getEmitter('load'), this.getEmitter('error') ); } }); domloader._jsbuild_.defineModule("objectdp.js",function(exports,module,require,globals,undefined){ var Dependency = require('./dependency').Dependency, utils = require("./libs/utils"), maps = require('./maps'), states = require('./states'), extend = utils.extend, includeScript = utils.includeScript, resolveNSPath = utils.resolveNSPath; var create = exports.create = function create(content,index){ var odp = new ObjectDp(); odp.name = content['name']; odp.src = content['src']; if( content.hasOwnProperty('properties') ){ for(var i = -1, len= content['properties'].length; ++i < len; ){ var propContent = content['properties'][i], prop = { 'name':propContent.name }; propContent.hasOwnProperty('match') && ( prop['match'] = new RegExp(propContent['match']) ); odp.properties.push(prop); }; } return odp; } maps.types.object = create; /** * Represents an object name and javascript module which will be loaded when global object doesn't contain a property with the name. */ var ObjectDp = exports.ObjectDp = function ObjectDp(){ Dependency.prototype.constructor.call(this); this.name = null; this.src = null; this.properties = []; } extend( ObjectDp, Dependency ); ObjectDp.prototype.refreshState = function(){ var nres = resolveNSPath( this.name ), loaded = nres.childrenNames.length == 0; for(var i = -1, len=this.properties.length; ++i < len && loaded;){ var prop = this.properties[i]; loaded = nres.parentObject.hasOwnProperty(prop.name) && ( !prop.match || prop.match.test(nres.parentObject[prop.name]) ); }; this.state = loaded && states.LOAD || states.UNINITIALIZED; } ObjectDp.prototype.load = function(){ this.refreshState(); var loadEmitter = this.getEmitter('load'), errorEmitter = this.getEmitter('error'); if( this.state != states.LOAD ){ includeScript(this.src,loadEmitter,errorEmitter); } else { loadEmitter(); } } }); domloader._jsbuild_.defineModule("states.js",function(exports,module,require,globals,undefined){ /** * State Objects */ var names = ["UNINITIALIZED", "LOADING", "LOAD", "ERROR"]; for(var i = -1, len=names.length; ++i < len; ) { exports[names[i]] = new Object(i); }; }); domloader._jsbuild_.defineModule("maps.js",function(exports,module,require,globals,undefined){ var getFileNameExt = require('./libs/utils').getFileNameExt, logger = require('./libs/logger'); var formats = exports.formats = {}; var modules = exports.modules = { 'css':['./stylesheet'], 'js':[ './jsfile' ], 'json':['./ext/json/jsonindex'], 'module':[ './jsfile' ], 'object':['./objectdp'], 'script':[ './jsfile' ], 'style':['./stylesheet'], 'stylesheet':['./stylesheet'], 'xml':['./ext/xml/xmlindex'] }; var types = exports.types = {}; var loadModules = exports.loadModules = function loadModules(key){ logger.debug('Trying to load modules associated with key "'+key+'"'); if(!modules.hasOwnProperty(key) || modules[key].length == 0) throw new Error('Found no module mapped to "'+key+'"'); var module_paths = modules[key]; for(var i = -1, len=module_paths.length; ++i < len; ){ require(module_paths[i]); }; }; var getConstructorByFormat = exports.getConstructorByFormat = function getConstructorByFormat(filename){ logger.debug('Returning the constructor associated with extension of passed filename "'+filename+'"'); var ext = getFileNameExt(filename); if(!formats.hasOwnProperty(ext)){ try { logger.warn('Extension "'+ext+'" is not mapped to any format constructor'); loadModules(ext); } catch(exc){ logger.critical(exc.message); throw new Error('Could not initialize the constructor associated with the detected dependency format of '+filename) } } return formats[ext]; }; var getConstructorByType = exports.getConstructorByType = function getConstructorByType(typeName){ logger.debug('Trying to return the constructor associated with specified type "'+typeName+'"'); if(!types.hasOwnProperty(typeName)){ try { logger.warn('Type "'+typeName+'" is not mapped to any format constructor'); loadModules(typeName); } catch(exc) { logger.critical(exc.message); throw new Error('Could not initialize the constructor associated with the dependency type of '+typeName) } } return types[typeName]; } }); domloader._jsbuild_.defineModule("stylesheet.js",function(exports,module,require,globals,undefined){ var Dependency = require("./dependency").Dependency, utils = require("./libs/utils"), maps = require('./maps'); var create = exports.create = function create(content){ var css = new Stylesheet(); css.src = content['src']; return css; }; maps.formats.css = maps.types.stylesheet = maps.types.css = maps.types.style = create; /** * Represent a CSS dependency. Doesn't support load and import events. */ var Stylesheet = exports.Stylesheet = function Stylesheet(){ Dependency.prototype.constructor.call(this); this.src = null; } utils.extend( Stylesheet, Dependency ); Stylesheet.prototype.load = function(){ var el = utils.createElement('link'); el.setAttribute('rel','stylesheet'); el.setAttribute('href',this.src+'?'+Number(new Date())); globals.document.getElementsByTagName('head')[0].appendChild( el ); this.getEmitter('load')(); }; }); domloader._jsbuild_.defineModule("dependency.js",function(exports,module,require,globals,undefined){ var cacheForce = require('./config').debug, extend = require('./libs/utils').extend, states = require("./states"), Observable = require("libs/observable").Observable, logger = require('./libs/logger'); /** * Generic DOM dependency class */ var Dependency = exports.Dependency = function Dependency(){ Observable.prototype.constructor.call(this); this.cacheForce = cacheForce; this.callbacks.error = []; this.callbacks.load = []; this.state = states.UNINITIALIZED; var self = this; this.callbacks.error.push(function(){ self.state = states.ERROR; }); this.callbacks.load.push(function(){ self.state = states.LOAD; }); logger.info('Created new dependency instance.'); }; extend(Dependency,Observable); Dependency.prototype.load = function(){ throw new Error('Not Implemented'); }; }); domloader._jsbuild_.defineModule("ext/json/utils.js",function(exports,module,require,globals,undefined){ var logger = require('../../../libs/logger'); var parse = exports.parse = function(source){ logger.debug('Trying to parse "'+source.substring(0,20).replace(/\s/g,' ')+'..." to JSON'); return this.JSON ? JSON.parse(source) : (new Function('return '+source))(); } }); domloader._jsbuild_.defineModule("ext/json/jsonindex.js",function(exports,module,require,globals,undefined){ var IndexFile = require('../../indexfile').IndexFile, maps = require('../../maps'), utils = require('../../libs/utils'), parse = require('./utils').parse, logger = require('../../libs/logger'), extend = utils.extend, dir = utils.dir, partial = utils.partial; var create = exports.create = function create(content,index){ var src = content['src']; logger.debug('Creating new JSONIndex instance, filename:'+src); var ind = new JSONIndex(); ind.src = src; ind.wd = dir(src); return ind; }; maps.formats.json = create; var JSONIndex = exports.JSONIndex = function JSONIndex(){ IndexFile.prototype.constructor.call( this ); }; extend( JSONIndex, IndexFile ); JSONIndex.prototype.parseFile = function(req){ logger.debug('Trying to parse the file at "'+this.src+'" to JS objects'); this.content = parse( req.responseText ); } }); domloader._jsbuild_.defineModule("ext/xml/utils.js",function(exports,module,require,globals,undefined){ /** * Execute given XPath expression on specified XML node. Works with the browsers support W3C's spec and IE+. */ var query = exports.query = function query(node,exp){ var found = []; var node = node.ownerDocument && node.ownerDocument.documentElement || ( node.documentElement || node.firstChild || node ); if( this.XPathEvaluator ){ var xpe = new XPathEvaluator(); var ns_resolver = xpe.createNSResolver(node); var result = xpe.evaluate(exp, node, ns_resolver, 0, null), n; while(n = result.iterateNext()){ found.push(n); } } else if ("selectNodes" in node){ node.ownerDocument.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'"); node.ownerDocument.setProperty("SelectionLanguage", "XPath"); found = node.selectNodes(exp); } else { throw new Error("Browser doesn't support XPath evalution"); } return found; }; var queryNode = exports.queryNode = function queryNode(node){   return function(expr){     return query( node, '//*[local-name()="widget" or local-name()="application" or local-name()="index"]'+( expr||'' ) );   } }; }); domloader._jsbuild_.defineModule("ext/xml/xmlindex.js",function(exports,module,require,globals,undefined){ var IndexFile = require('../../indexfile').IndexFile, maps = require('../../maps'), utils = require('../../libs/utils'), logger = require('../../libs/logger'), parseJSON = require('../json/utils').parse, queryNode = require('./utils').queryNode, partial = utils.partial, extend = utils.extend, dir = utils.dir, isRelativePath = utils.isRelativePath; var create = exports.create = function create(content,index){ var src = content['src']; logger.debug('Creating new XMLIndex instance, filename:'+src); var ind = new XMLIndex(); ind.src = src; ind.wd = dir(src); return ind; }; maps.formats.xml = create; var XMLIndex = exports.XMLIndex = function(){ IndexFile.prototype.constructor.call( this ); } extend( XMLIndex, IndexFile ); XMLIndex.prototype.parseFile = function(req){ logger.debug('Trying to parse the file at "'+this.src+'" to JS objects'); var ctx = req.responseXML, select = queryNode(ctx), deps = [], depElements = select('/dependencies/*'), name = ctx.documentElement.getAttribute('name'), version = ctx.documentElement.getAttribute('version'), ns = null, nsElements = select('/namespace'), nsContent = null; if(nsElements.length){ logger.info(' Namespace definition(s) found.'); nsContent = nsElements[0].childNodes[0].nodeValue;         !/^\{/.test( nsContent ) && ( nsContent = "{"+nsContent+"}" ); logger.debug(' Parsing JSON NS definition: '+nsContent); ns = parseJSON( nsContent ); logger.info(' Done:',ns) } this.content = { 'namespace':ns, 'dependencies':deps }; name && ( this.content['name'] = name ); version && ( this.content['version'] = version ); for(var i = -1, len=depElements.length; ++i < len; ){ var dp = { "type":null, "src":null }, el = depElements[i]; dp['type'] = el.tagName; dp['src'] = el.getAttribute('src'); logger.debug(' Parsing Dependency Element (:type "'+el.tagName+'" :src "'+el.getAttribute('src')+'")'); switch(dp['type']){ case 'object': logging.info(' Found object element, parsing its properties.');   dp['name'] = el.getAttribute('name'); dp['properties'] = [];   var properties = el.getElementsByTagName('property');   for(var t = -1, tlen=properties.length; ++t < tlen; ){     var el = properties[t];     var prop = {};     prop.name = el.getAttribute("name");     el.getAttribute("match") && ( prop.match = new RegExp(el.getAttribute("match")) );     dp.properties.push(prop);   }; break; } deps.push(dp); }; } }); domloader._jsbuild_.getModuleByFilename("domloader.js").call();
mit
antonhedstrom/node-spnl-logger
public/assets/js/screens/scr.userprofile.js
1090
define([ 'app', 'marionette', 'tpl!./templates/main', // Models '../models/user.model', // Views '../views/userprofile', '../views/user-menu' ], function( App, Marionette, MainTemplate, // Models UserModel, // Views UserProfileView, UserMenuView ) { var Layout = Backbone.Marionette.LayoutView.extend({ template: MainTemplate, regions: { header: 'header', content: '.content' }, initialize: function(options) { if ( !App.models.user ) { App.models.user = new UserModel(); } this.userModel = App.models.user; }, onRender: function() { var usermenuView = new UserMenuView({ model: this.userModel, activeMenuItem: 'profile' }); var userProfileView = new UserProfileView({ model: this.userModel }); this.header.show(usermenuView); this.content.show(userProfileView); }, loadData: function() { this.userModel.fetch(); }, destroy: function() { this.userModel = null; } }); return Layout; });
mit
kenkov/kovlang-corpus
scripts/chartype.py
11907
#! /usr/bin/env python # coding:utf-8 import unicodedata import re class CharException(TypeError): def __init__(self, sent): self.sent = sent def __str__(self): return "need a single Unicode character as parameter\ : {}".format(self.sent) class CharTypeException(TypeError): def __init__(self, sent): self.sent = sent def __str__(self): return "need a halfwidth katakana character\ as a parameter: {}".format(self.sent) class VoicedTypeException(TypeError): def __init__(self, sent): self.sent = sent def __str__(self): return "need a halfwidth katakana character\ which can be used as voiced or semi-voiced: {}".format(self.sent) class Chartype(object): u''' Chartype クラス ''' def __init__(self): pass def _typename(self, st): ''' :param st: ユニコード型の文字列 :type st: ユニコード型 :rtype: string :return: 文字の種類を表す文字列 :except IOError: IOError がでる。 ''' if self.is_hiragana(st): return 'HIRAGANA' elif self.is_katakana(st): return 'KATAKANA' elif self.is_halfwidthkatakana(st): return 'HANKAKUKATAKANA' elif self.is_kanji(st): return 'KANJI' elif self.is_latinsmall(st): return 'LATINSMALL' elif self.is_latincapital(st): return 'LATINCAPITAL' elif self.is_digit(st): return 'DIGIT' elif self.is_kuten(st): return 'KUTEN' elif self.is_touten(st): return 'TOUTEN' def _is_type(self, typ, st, start, end): ''' ''' try: return unicodedata.name(st)[start: end] == typ except TypeError as ex: raise CharException(st) from ex def is_hiragana(self, st): u""" ひらがなかどうかを判定する :param unicode st: ユニコード型の文字列 :rtype: bool >>> ch = Chartype() >>> ch.is_hiragana(u'あ') True >>> ch.is_hiragana(u'ア') False """ return self._is_type('HIRAGANA', st, 0, 8) def is_katakana(self, st): u""" カタカナかどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_katakana(u'ア') True >>> ch.is_katakana(u'あ') False """ return self._is_type('KATAKANA', st, 0, 8) def is_halfwidthkatakana(self, st): u""" 半角カタカナかどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_halfwidthkatakana(u'ア') True >>> ch.is_halfwidthkatakana(u'ア') False """ return self._is_type('HALFWIDTH KATAKANA', st, 0, 18) def is_kanji(self, st): u""" 漢字かどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_kanji(u'漢') True >>> ch.is_kanji(u'か') False """ return self._is_type('CJK', st, 0, 3) def is_latinsmall(self, st): u""" [a-z]* かどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_latinsmall(u'a') True >>> ch.is_latinsmall(u'あ') False """ return self._is_type('LATIN SMALL', st, 0, 11) def is_latincapital(self, st): u""" [A-Z]* かどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_latincapital(u'A') True >>> ch.is_latincapital(u'a') False """ return self._is_type('LATIN CAPITAL', st, 0, 13) def is_digit(self, st): u""" 数値かどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_digit(u'1') True >>> ch.is_digit(u'a') False """ return self._is_type('DIGIT', st, 0, 5) def is_kuten(self, st): u""" 『。』または『.』に一致するかどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_kuten(u'。') True >>> ch.is_kuten(u'.') True """ return self._is_type('IDEOGRAPHIC FULL STOP', st, 0, 21) or \ self._is_type('FULLWIDTH FULL STOP', st, 0, 19) or \ self._is_type('FULL STOP', st, 0, 9) def is_touten(self, st): u""" 『、』または『.』に一致するかどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_touten(u'、') True >>> ch.is_touten(u',') True """ return self._is_type('IDEOGRAPHIC COMMA', st, 0, 17) or \ self._is_type('FULLWIDTH COMMA', st, 0, 15) or \ self._is_type('COMMA', st, 0, 5) # 上を組み合わせて新しいメソッドをつくる def is_latin(self, st): ''' ラテン文字列かどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_latin(u'a') True >>> ch.is_latin(u'A') True >>> ch.is_latin(u'1') False ''' return self.is_latinsmall(st) or self.is_latincapital(st) def is_ascii(self, st): ''' アスキー文字列かどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_ascii(u'a') True >>> ch.is_ascii(u'A') True >>> ch.is_ascii(u'1') True ''' return self.is_digit(st) or self.is_latin(st) def is_kutouten(self, st): u''' 句読点かどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_kutouten(u'。') True >>> ch.is_kutouten(u'.') True >>> ch.is_kutouten(u'、') True >>> ch.is_kutouten(u',') True ''' return self.is_kuten(st) or self.is_touten(st) def is_nihongo(self, st): u''' 日本語かどうかを判定する :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_nihongo(u'あ') True >>> ch.is_nihongo(u'a') False ''' return self.is_hiragana(st) or \ self.is_katakana(st) or \ self.is_halfwidthkatakana(st) or \ self.is_kanji(st) or \ self.is_kuten(st) or \ self.is_touten(st) def otherwise(self, st): u""" 上の関数でTrueになる文字以外の文字 :param unicode st: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.otherwise(u'!') True >>> ch.otherwise(u'!') True """ return not (self.is_hiragana(st) or self.is_katakana(st) or self.is_halfwidthkatakana(st) or self.is_kanji(st) or self.is_latinsmall(st) or self.is_latincapital(st) or self.is_digit(st) or self.is_kuten(st) or self.is_touten(st)) def is_sametype(self, st1, st2): u''' st1 とst2 が同じ文字列かどうかを判定する :param unicode st1: ユニコード型の文字列 :param unicode st2: ユニコード型の文字列 :rtype bool: >>> ch = Chartype() >>> ch.is_sametype(u'あ', u'あ') True >>> ch.is_sametype(u'あ', u'い') True ''' return self._typename(st1) == self._typename(st2) def hiragana2katakana(self, char): """ひらがなをカタカナに変換する""" if not self.is_hiragana(char): raise CharTypeException(char) name = re.sub(r"^HIRAGANA\s", "KATAKANA ", unicodedata.name(char)) return unicodedata.lookup(name) def katakana2hiragana(self, char): """カタカナを平仮名に変換する""" if not self.is_katakana(char): raise CharTypeException(char) name = re.sub(r"^KATAKANA\s", "HIRAGANA ", unicodedata.name(char)) return unicodedata.lookup(name) def half2full(self, char): u"""半角カタカナ char を全角カタカナに変換する""" # voiced and semi-voiced sound mark voiced = { "カ": "ガ", "キ": "ギ", "ク": "グ", "ケ": "ゲ", "コ": "ゴ", "サ": "ザ", "シ": "ジ", "ス": "ズ", "セ": "ゼ", "ソ": "ゾ", "タ": "ダ", "チ": "ヂ", "ツ": "ヅ", "テ": "デ", "ト": "ド", "ハ": "バ", "ヒ": "ビ", "フ": "ブ", "ヘ": "ベ", "ホ": "ボ", } semivoiced = { "ハ": "パ", "ヒ": "ピ", "フ": "プ", "ヘ": "ペ", "ホ": "ポ", } w0_name = unicodedata.name(char[0]) # char[0] は halfwidthkatakana でなければならない # 「゙」や「゚」は is_halfwidthkatakana チェックで # 通るので別でチェックしている if (not self.is_halfwidthkatakana(char[0])) or \ (w0_name in [ 'HALFWIDTH KATAKANA VOICED SOUND MARK', 'HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK']): raise CharTypeException(char) if len(char) == 1: name = re.sub(r"^HALFWIDTH\s", "", unicodedata.name(char)) return unicodedata.lookup(name) elif len(char) >= 2: w1_name = unicodedata.name(char[1]) if w1_name == \ 'HALFWIDTH KATAKANA VOICED SOUND MARK': try: return voiced[char[0]] except KeyError: raise VoicedTypeException(char[0]) elif w1_name == \ 'HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK': try: return semivoiced[char[0]] except KeyError: raise VoicedTypeException(char[0]) else: return self.half2full(char[0]) def full2half(self, char): u"""全角カタカナ char を半角カタカナに変換する""" if not self.is_katakana(char): raise CharTypeException(char) # voiced and semi-voiced sound mark vm_dic = { "ガ": "カ", "ギ": "キ", "グ": "ク", "ゲ": "ケ", "ゴ": "コ", "ザ": "サ", "ジ": "シ", "ズ": "ス", "ゼ": "セ", "ゾ": "ソ", "ダ": "タ", "ヂ": "チ", "ヅ": "ツ", "デ": "テ", "ド": "ト", "バ": "ハ", "ビ": "ヒ", "ブ": "フ", "ベ": "ヘ", "ボ": "ホ", "パ": "ハ", "ピ": "ヒ", "プ": "フ", "ペ": "ヘ", "ポ": "ホ", } if char in vm_dic: return "{}゙".format(vm_dic[char]) else: return unicodedata.lookup( "HALFWIDTH {}".format(unicodedata.name(char))) if __name__ == '__main__': import doctest doctest.testmod()
mit
benz2012/derby-dashboard
server/routes/data/alumni.js
5904
const express = require('express') const { get, update } = require('../../database') const params = require('../../database/params') const { errorEnd, applyKeyMapToObj, markdownToHTML } = require('./utility') const router = express.Router() // Shared Functions const keyMap = { name: 'Name', email: 'Email', pledges: 'Pledges', description: 'Description', endDate: 'EndDate', countData: 'CountData', countName: 'CountName', } const nextId = data => ( Object.keys(data) .filter(k => k !== 'DataName') .map(k => parseInt(k, 10)) .sort((a, b) => (b - a))[0] + 1 ) // // Alumni Routes router.get('/', (req, res) => { get({ TableName: 'Derby_App', Key: { DataName: 'AlumniPledges' }, }).then((data) => { const alumniKeys = Object.keys(data).filter(k => k !== 'DataName') const alumniData = alumniKeys.map((k) => { const a = data[k] return ({ id: k, name: a.Name, email: a.Email, pledges: a.Pledges, }) }) res.json(alumniData) }).catch(err => errorEnd(err, res)) }) router.put('/', (req, res) => { if (req.body) { const item = applyKeyMapToObj(req.body, keyMap) return get({ TableName: 'Derby_App', Key: { DataName: 'AlumniPledges' }, }).then((data) => { const newId = nextId(data) return update(params.attrUpdate( 'Derby_App', { DataName: 'AlumniPledges' }, newId, item )) }).then(data => res.json(data)) .catch(err => errorEnd(err, res)) } return errorEnd('Missing a request body', res) }) router.post('/:id', (req, res) => { const alumniId = req.params.id if (req.body) { const item = applyKeyMapToObj(req.body, keyMap) return update(params.attrUpdate( 'Derby_App', { DataName: 'AlumniPledges' }, alumniId, item )).then(data => res.json(data)) .catch(err => errorEnd(err, res)) } return errorEnd('Missing a request body', res) }) router.delete('/:id', (req, res) => { const alumniId = req.params.id return update(params.attrRemove( 'Derby_App', { DataName: 'AlumniPledges' }, alumniId )).then(data => res.json(data)) .catch(err => errorEnd(err, res)) }) // // Pledges Route router.get('/pledges', (req, res) => { get({ TableName: 'Derby_App', Key: { DataName: 'AlumniPledges' }, }).then((data) => { const alumniKeys = Object.keys(data).filter(k => k !== 'DataName') const pledgeData = alumniKeys.map(k => (data[k].Pledges)) res.json(pledgeData) }).catch(err => errorEnd(err, res)) }) // // Challenges Routes router.get('/challenges', (req, res) => { get({ TableName: 'Derby_App', Key: { DataName: 'AlumniChallenges' }, }).then((data) => { const challengeKeys = Object.keys(data).filter(k => k !== 'DataName') const challengeData = challengeKeys.map((k) => { const c = data[k] return ({ id: k, name: c.Name, description: c.Description, endDate: c.EndDate, countData: c.CountData, countName: c.CountName, }) }) res.json(challengeData) }).catch(err => errorEnd(err, res)) }) router.get('/challenges/:id', (req, res) => { const challengeId = parseInt(req.params.id) get({ TableName: 'Derby_App', Key: { DataName: 'AlumniChallenges' }, }).then((data) => { const challengeKey = Object.keys(data) .filter(k => parseInt(k) === challengeId)[0] if (challengeKey === undefined) { throw new Error('Alumni Challenge does not exist for this id') } const c = data[challengeKey] const challengeData = ({ id: challengeKey, name: c.Name, description: c.Description, endDate: c.EndDate, countData: c.CountData.map(markdownToHTML), countName: c.CountName, }) res.json(challengeData) }).catch(err => errorEnd(err, res)) }) router.put('/challenges', (req, res) => { if (req.body) { const item = applyKeyMapToObj(req.body, keyMap) return get({ TableName: 'Derby_App', Key: { DataName: 'AlumniChallenges' }, }).then((data) => { const newId = nextId(data) return update(params.attrUpdate( 'Derby_App', { DataName: 'AlumniChallenges' }, newId, item )) }).then(data => res.json(data)) .catch(err => errorEnd(err, res)) } return errorEnd('Missing a request body', res) }) router.post('/challenges/:id', (req, res) => { const challengeId = req.params.id if (req.body) { const item = applyKeyMapToObj(req.body, keyMap) return update(params.attrUpdate( 'Derby_App', { DataName: 'AlumniChallenges' }, challengeId, item )).then(data => res.json(data)) .catch(err => errorEnd(err, res)) } return errorEnd('Missing a request body', res) }) router.delete('/challenges/:id', (req, res) => { const challengeId = req.params.id return update(params.attrRemove( 'Derby_App', { DataName: 'AlumniChallenges' }, challengeId )).then(() => ( get({ TableName: 'Derby_App', Key: { DataName: 'AlumniPledges' }, }) )).then((data) => { const alumniKeys = Object.keys(data).filter(k => k !== 'DataName') return Promise.all( alumniKeys.map((key) => { const alum = data[key] const updatedPledges = Object.keys(alum.Pledges) .filter(pKey => pKey !== challengeId) .reduce((acc, pKey) => { acc[pKey] = alum.Pledges[pKey] return acc }, {}) const updatedAlum = { ...alum, Pledges: updatedPledges, } return update(params.attrUpdate( 'Derby_App', { DataName: 'AlumniPledges' }, key, updatedAlum )) }) ) }).then(data => res.json(data)) .catch(err => errorEnd(err, res)) }) module.exports = router
mit
Hawatel/hawatel_search_jobs
spec/reed_spec.rb
3162
require 'spec_helper' require 'ostruct' xdescribe HawatelSearchJobs::Api::Reed do before(:each) do HawatelSearchJobs.configure do |config| config.reed[:api] = "reed.co.uk/api" config.reed[:clientid] = '' config.reed[:page_size] = 100 end end context 'APIs returned jobs' do before(:each) do @query_api = { :keywords => 'ruby', :location => 'London' } @result = HawatelSearchJobs::Api::Reed.search( :settings => HawatelSearchJobs.reed, :query => { :keywords => @query_api[:keywords], :location => @query_api[:location] }) end it '#search' do validate_result(@result, @query_api) expect(@result.page).to be >= 0 expect(@result.last).to be >= 0 end it '#page' do validate_result(@result, @query_api) page_result = HawatelSearchJobs::Api::Reed.page({:settings => HawatelSearchJobs.reed, :query_key => @result.key, :page => 1}) expect(page_result.key).to match(/&resultsToSkip=#{HawatelSearchJobs.reed[:page_size]}/) expect(page_result.page).to eq(1) expect(page_result.last).to be >= 0 end it '#next page does not contain last page' do validate_result(@result, @query_api) page_first = HawatelSearchJobs::Api::Reed.page({:settings => HawatelSearchJobs.reed, :query_key => @result.key, :page => 1}) page_second = HawatelSearchJobs::Api::Reed.page({:settings => HawatelSearchJobs.reed, :query_key => @result.key, :page => 2}) page_first.jobs.each do |first_job| page_second.jobs.each do |second_job| expect(first_job.url).not_to eq(second_job.url) end end end it '#count of jobs is the same like page_size' do expect(@result.jobs.count).to eq(HawatelSearchJobs.reed[:page_size]) end end context 'APIs returned empty table' do before(:each) do @query_api = { :keywords => 'job-not-found-zero-records', :location => 'London' } @result = HawatelSearchJobs::Api::Reed.search( :settings => HawatelSearchJobs.reed, :query => { :keywords => @query_api[:keywords], :location => @query_api[:location] }) end it '#search' do validate_result(@result, @query_api) expect(@result.totalResults).to eq(0) expect(@result.page).to be_nil expect(@result.last).to be_nil end it '#page' do validate_result(@result, @query_api) page_result = HawatelSearchJobs::Api::Reed.page({:settings => HawatelSearchJobs.reed, :query_key => @result.key, :page => 1}) expect(@result.totalResults).to eq(0) expect(@result.page).to be_nil expect(@result.last).to be_nil end end private def validate_result(result, query_api) expect(result.code).to eq(200) expect(result.msg).to eq('OK') expect(result.totalResults).to be >= 0 expect(result.key).to match("locationName=#{query_api[:location]}") expect(result.key).to match("keywords=#{query_api[:keywords]}") end end
mit
nellypeneva/SoftUniProjects
01_ProgrFundamentalsMay/11_Data-Types-Exercises/07_ExchangeVariableValues/Properties/AssemblyInfo.cs
1426
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("07_ExchangeVariableValues")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07_ExchangeVariableValues")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b003640e-95e2-458d-bf60-94e4420eef79")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
jszoo/cat-mvc
mvc/httpHelper.js
3986
/* * httpHelper * author: ruleechen * contact: rulee@live.cn * create date: 2014.7.25 * description: migrate from expressjs [https://github.com/strongloop/express/blob/master/lib/utils.js] */ 'use strict'; var mime = require('send').mime, crc32 = require('buffer-crc32'), crypto = require('crypto'), basename = require('path').basename, proxyaddr = require('proxy-addr'), typer = require('media-typer'), utils = require('zoo-utils'); module.exports = { escapeHtml: function(html) { return String(html) .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); }, compileETag: function(val) { var t = utils.type(val); if (t === 'function') { return val; } if (val === true) { return this.wetag; } if (val === false) { return null; } if (val === 'strong') { return this.etag; } if (val === 'weak') { return this.wetag; } throw new TypeError('unknown value for etag function: ' + val); }, etag: function(body, encoding) { if (body.length === 0) { // fast-path empty body return '"1B2M2Y8AsgTpgAmY7PhCfg=="'; } else { var hash = crypto.createHash('md5').update(body, encoding).digest('base64'); return '"' + hash + '"'; } }, wetag: function(body, encoding) { if (body.length === 0) { // fast-path empty body return 'W/"0-0"'; } else { var buf = Buffer.isBuffer(body) ? body : new Buffer(body, encoding); return 'W/"' + buf.length.toString(16) + '-' + crc32.unsigned(buf) + '"'; } }, compileTrust: function(val) { var t = utils.type(val); if (t === 'function') { return val; } if (t === 'number') { return function(a, i) { return i < val; }; // Support trusting hop count } if (val === true) { return function() { return true; }; // Support plain true/false } if (t === 'string') { val = val.split(/ *, */); // Support comma-separated values } return proxyaddr.compile(val || []); }, acceptParams: function(str, index) { var parts = str.split(/ *; */); var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; for (var i = 1; i < parts.length; ++i) { var pms = parts[i].split(/ *= */); if ('q' == pms[0]) { ret.quality = parseFloat(pms[1]); } else { ret.params[pms[0]] = pms[1]; } } return ret; }, normalizeType: function(type) { return ~type.indexOf('/') ? this.acceptParams(type) : { value: mime.lookup(type), params: {} }; }, normalizeTypes: function(types) { var ret = []; for (var i = 0; i < types.length; ++i) { ret.push(this.normalizeType(types[i])); } return ret; }, contentDisposition: function(filename) { var ret = 'attachment'; if (filename) { filename = basename(filename); // if filename contains non-ascii characters, add a utf-8 version ala RFC 5987 ret = /[^\040-\176]/.test(filename) ? 'attachment; filename="' + encodeURI(filename) + '"; filename*=UTF-8\'\'' + encodeURI(filename) : 'attachment; filename="' + filename + '"'; } return ret; }, setCharset: function(type, charset) { if (!type || !charset) { return type; } // parse type var parsed = typer.parse(type); // set charset parsed.parameters.charset = charset; // format type return typer.format(parsed); } };
mit
PlayArShop/mobile-application
Assets/Games/StMichel/Scripts/TriggerBasketGoal.cs
328
using UnityEngine; using UnityEngine.UI; using System.Collections; public class TriggerBasketGoal : MonoBehaviour { void OnCollisionEnter (Collision col) { if(col.gameObject.name == "Cracker" || col.gameObject.name == "nextCracker") { //Destroy(col.gameObject); GameOver.score++; } } void Update () { } }
mit
AVSystem/scex
scex-core/src/test/scala/com/avsystem/scex/compiler/ScexCompilerTest.scala
14233
package com.avsystem.scex package compiler import com.avsystem.scex.compiler.ParameterizedClass.StaticInnerGeneric import com.avsystem.scex.compiler.ScexCompiler.CompilationFailedException import com.avsystem.scex.compiler.overriding.{Base, Klass, Specialized} import com.avsystem.scex.util.{PredefinedAccessSpecs, SimpleContext} import com.google.common.reflect.TypeToken import org.scalatest.FunSuite import java.{util => ju} import scala.annotation.nowarn import scala.collection.immutable.StringOps object ScexCompilerTest { implicit class JListExt[T](jlist: ju.List[T]) { def apply(i: Int): T = jlist.get(i) } } @nowarn("msg=a pure expression does nothing in statement position") class ScexCompilerTest extends FunSuite with CompilationTest { import com.avsystem.scex.validation.SymbolValidator._ override def defaultAcl = Nil test("trivial compilation test") { evaluate[Unit]("()") } test("simple arithmetic expression") { assert(298 == evaluate[Int]("1+5+250+42")) } test("simple syntax validation test") { intercept[CompilationFailedException] { evaluate[Unit]("while(true) {}") } } test("simple member validation test") { assertMemberAccessForbidden { evaluate[Unit]("System.exit(0)") } } test("syntax error test") { intercept[CompilationFailedException] { evaluate[Unit]("this doesn't make sense") } } test("root access test with java getter adapters") { val acl = PredefinedAccessSpecs.basicOperations ++ allow { on { jc: JavaRoot => jc.all.members } } val expr = "property + extraordinary + extraordinarilyBoxed + field + twice(42)" val cexpr = compiler.getCompiledExpression[SimpleContext[JavaRoot], String](createProfile(acl), expr, template = false) assert("propertytruefalse42.4284" == cexpr(SimpleContext(new JavaRoot))) } test("complicated root type test with java getter adapters") { val acl = PredefinedAccessSpecs.basicOperations ++ allow { on { m: ju.Map[_, _] => m.toString } on { ct: (ParameterizedClass.StaticInnerGeneric[A]#DeeplyInnerGeneric[B] forSome {type A; type B}) => ct.all.members } } type RootType = ParameterizedClass.StaticInnerGeneric[Cloneable]#DeeplyInnerGeneric[_] val expr = """ "EXPR:" + awesomeness + sampleMap + handleStuff("interesting stuff") + awesome + fjeld """ val cexpr = compiler.buildExpression.contextType(new TypeToken[SimpleContext[RootType]] {}).template(false) .resultType(classOf[String]).profile(createProfile(acl)).expression(expr).get val sig = new StaticInnerGeneric[Cloneable] assert("EXPR:true{}[interesting stuff handled]true[fjeld]" == cexpr(SimpleContext(new sig.DeeplyInnerGeneric[String]))) } test("non-root java getter adapters test") { val acl = PredefinedAccessSpecs.basicOperations ++ allow { on { jc: JavaRoot => new JavaRoot jc.all.members } } val expr = "new JavaRoot().property + new JavaRoot().extraordinary + new JavaRoot().extraordinarilyBoxed" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], String](createProfile(acl), expr, template = false) assert("propertytruefalse" == cexpr(SimpleContext(()))) } test("String.empty") { val acl = PredefinedAccessSpecs.basicOperations assert(!evaluate[Boolean]("\"str\".empty", acl)) } test("constructor allow test") { val acl = allow { new JavaRoot } val expr = "new JavaRoot" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], Unit](createProfile(acl), expr, template = false) cexpr(SimpleContext(())) } test("constructor deny test") { val acl = deny { new JavaRoot } val expr = "new JavaRoot" assertMemberAccessForbidden { compiler.getCompiledExpression[SimpleContext[Unit], Unit](createProfile(acl), expr, template = false) } } test("constructor not allow test") { val expr = "new JavaRoot" assertMemberAccessForbidden { compiler.getCompiledExpression[SimpleContext[Unit], Unit](createProfile(Nil), expr, template = false) } } test("java getter validation test") { val acl = allow { on { jc: JavaRoot => jc.getProperty } } val expr = "property" val cexpr = compiler.getCompiledExpression[SimpleContext[JavaRoot], String](createProfile(acl), expr, template = false) assert("property" == cexpr(SimpleContext(new JavaRoot))) } test("validation test with subtyping") { val acl = deny { on { jc: JavaRoot => jc.getProperty } } ++ allow { on { djc: DerivedJavaRoot => djc.all.members } } val expr = "property" assertMemberAccessForbidden { compiler.getCompiledExpression[SimpleContext[DerivedJavaRoot], String](createProfile(acl), expr, template = false) } } test("validation test with overriding") { val acl = allow { on { jc: JavaRoot => jc.overriddenMethod() } } val expr = "overriddenMethod()" val cexpr = compiler.getCompiledExpression[SimpleContext[DerivedJavaRoot], Unit](createProfile(acl), expr, template = false) cexpr(SimpleContext(new DerivedJavaRoot)) } test("header test") { val acl = allow { new ju.ArrayList[String] } val expr = "new ArrayList[String]" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], ju.List[_]]( createProfile(acl, header = "import java.util.ArrayList"), expr, template = false) assert(new ju.ArrayList[String] == cexpr(SimpleContext(()))) } test("utils test") { val expr = "utilValue" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], Int]( createProfile(Nil, header = "", utils = "val utilValue = 42"), expr, template = false) assert(42 == cexpr(SimpleContext(()))) } test("implicit context test") { val expr = "gimmeVar(\"tehname\")" val acl = allow { on { car: ContextAccessingRoot => car.gimmeVar(_: String)(_: ExpressionContext[ContextAccessingRoot, String]) } } val cexpr = compiler.getCompiledExpression[SimpleContext[ContextAccessingRoot], String](createProfile(acl), expr, template = false) val ctx = SimpleContext(new ContextAccessingRoot) ctx.setVariable("tehname", "tehvalue") assert("tehvalue" == cexpr(ctx)) } test("ACL allow entry precedence test") { val acl = allow { on { i: Int => i.toString } } ++ deny { on { i: Int => i.toString } } val expr = "42.toString" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], String](createProfile(acl), expr, template = false) assert("42" == cexpr(SimpleContext(()))) } test("ACL deny entry precedence test") { val acl = deny { on { i: Int => i.toString } } ++ allow { on { i: Int => i.toString } } val expr = "42.toString" assertMemberAccessForbidden { compiler.getCompiledExpression[SimpleContext[Unit], String](createProfile(acl), expr, template = false) } } test("static module access validation test") { val acl = allow { Some.apply(_: Any) } val expr = "Some" assertMemberAccessForbidden { compiler.getCompiledExpression[SimpleContext[Unit], Unit](createProfile(acl), expr, template = false) } } test("static module member validation test 1") { val acl = allow { Some.apply(_: Any) } val expr = "Some(42)" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], Option[Int]](createProfile(acl), expr, template = false) assert(Some(42) == cexpr(SimpleContext(()))) } test("static module member validation test 2") { val acl = allow { Some.all.members } val expr = "Some.hashCode" assertMemberAccessForbidden { compiler.getCompiledExpression[SimpleContext[Unit], Unit](createProfile(acl), expr, template = false) } } test("explicit member-by-implicit validation test 1") { val acl = allow { on { s: String => s.reverse } } val expr = "\"bippy\".reverse" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], String](createProfile(acl), expr, template = false) assert("yppib" == cexpr(SimpleContext(()))) } test("explicit member-by-implicit validation test 2") { import TestExtensions._ val acl = allow { on { any: Any => any ? (_: Any) } } val expr = "\"bippy\" ? \"fuu\"" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], String]( createProfile(acl, header = "import com.avsystem.scex.compiler.TestExtensions._"), expr, template = false) assert("bippy" == cexpr(SimpleContext(()))) } test("plain implicit conversion validation test") { val acl = allow { Predef.augmentString _ on { s: StringOps => s.reverse } } val expr = "\"bippy\".reverse" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], String](createProfile(acl), expr, template = false) assert("yppib" == cexpr(SimpleContext(()))) } test("mixed access implicit conversion validation test 1") { val acl = deny { Predef.augmentString _ } ++ allow { on { s: String => s.reverse } } val expr = "\"bippy\".reverse" assertMemberAccessForbidden { compiler.getCompiledExpression[SimpleContext[Unit], String](createProfile(acl), expr, template = false) } } test("mixed access implicit conversion validation test 2") { val acl = deny { on { s: StringOps => s.reverse } } ++ allow { on { s: String => s.reverse } } val expr = "\"bippy\".reverse" assertMemberAccessForbidden { compiler.getCompiledExpression[SimpleContext[Unit], String](createProfile(acl), expr, template = false) } } test("member by generic implicit conversion on existential type test") { import ScexCompilerTest._ val acl = allow { on { l: ju.List[_] => l.apply(_: Int) } } val header = "import com.avsystem.scex.compiler.ScexCompilerTest._" val expr = "_root(0)" val cexpr = compiler.getCompiledExpression[SimpleContext[ju.List[String]], Any](createProfile(acl, header = header), expr, template = false) val list = ju.Arrays.asList("0", "1", "2") assert("0" == cexpr(SimpleContext(list))) } test("covariance by @plus annotation test") { val acl = allow { on { l: ju.List[Any@plus] => l.add(_: Any) } } val expr = "_root.add(\"string\")" val cexpr = compiler.getCompiledExpression[SimpleContext[ju.List[String]], Unit](createProfile(acl), expr, template = false) val list = new ju.ArrayList[String] cexpr(SimpleContext(list)) assert("string" == list.get(0)) } test("contravariance by @minus annotation test") { val acl = allow { on { l: ju.List[String@minus] => l.get _ } } val expr = "_root.get(0)" val cexpr = compiler.getCompiledExpression[SimpleContext[ju.List[Any]], Any](createProfile(acl), expr, template = false) val list = ju.Arrays.asList[Any]("cos") cexpr(SimpleContext(list)) assert("cos" == list.get(0)) } test("dynamic test") { val acl = allow { SomeDynamic.selectDynamic _ } val expr = "com.avsystem.scex.compiler.SomeDynamic.dynamicProperty" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], String](createProfile(acl), expr, template = false) assert("dynamicProperty" == cexpr(SimpleContext(()))) } test("java getter inherited from multiple bases test") { val acl = allow { on { sjr: SubRoot => sjr.all.members } } val expr = "self.id" val cexpr = compiler.getCompiledExpression[SimpleContext[SubRoot], String](createProfile(acl), expr, template = false) assert("tehId" == cexpr(SimpleContext(new SubRoot))) } // https://groups.google.com/forum/#!topic/scala-user/IeD2siVXyss test("overriding problem test") { val acl = allow { on { base: Base => base.get _ } } val expr = "_root.get(\"lol\")" val cexpr = compiler.getCompiledExpression[SimpleContext[Klass], AnyRef](createProfile(acl), expr, template = false) val root = new Klass assert(root eq cexpr(SimpleContext(root))) } test("overridden java getter with bridge method test") { val acl = allow { on { s: Specialized => s.all.members } on { s: String => s + _ s.toString } } val expr = "that + _root.that" val cexpr = compiler.getCompiledExpression[SimpleContext[Specialized], String](createProfile(acl), expr, template = false) assert("thatthat" == cexpr(SimpleContext(new Specialized))) } test("toString on any2stringadd validation test") { val acl = allow { on { any: Any => any + (_: String) } on { s: String => s + _ s.toString } } val expr = "_root + \"\"" assertMemberAccessForbidden { compiler.getCompiledExpression[SimpleContext[JavaRoot], String](createProfile(acl), expr, template = false) } } def lambdaTest(name: String, expr: String) = test(name) { val acl = allow { List.apply _ on { l: List[Any] => l.forall _ } on { i: Int => i > (_: Int) } } val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], Boolean](createProfile(acl), expr, template = false) assert(cexpr(SimpleContext(()))) } lambdaTest("regular lambda test", "List(1,2,3).forall(x => 5 > x)") lambdaTest("short lambda test", "List(1,2,3).forall(5 > _)") lambdaTest("eta-expanded lambda test", "List(1,2,3).forall(5.>)") test("default arguments") { val profile = createProfile(Nil, utils = "def hasDefs(int: Int = 42, str: String = \"fuu\") = s\"$int:$str\"") val expr = "hasDefs(str = \"omglol\")" val cexpr = compiler.getCompiledExpression[SimpleContext[Unit], String](profile, expr, template = false) assert(cexpr(SimpleContext(())) == "42:omglol") } }
mit
rtnews/rtsfnt
node_modules/@nebular/theme/components/helpers.js
542
/** * @license * Copyright Akveo. All Rights Reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ /** * @license * Copyright Akveo. All Rights Reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ export function convertToBoolProperty(val) { if (typeof val === 'string') { val = val.toLowerCase().trim(); return (val === 'true' || val === ''); } return !!val; } //# sourceMappingURL=helpers.js.map
mit
matheus23/RuinsOfRevenge
src/org/matheusdev/util/MissingJSONContentException.java
1386
/* * Copyright (c) 2013 matheusdev * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.matheusdev.util; /** * @author matheusdev * */ public class MissingJSONContentException extends RuntimeException { private static final long serialVersionUID = -1414199426276129481L; public MissingJSONContentException(String msg) { super(msg); } }
mit
jeremysklarsky/movie-demo
db/migrate/20150408014912_create_critic_reviews.rb
278
class CreateCriticReviews < ActiveRecord::Migration def change create_table :critic_reviews do |t| t.integer :critic_id t.integer :movie_id t.integer :score t.string :excerpt t.string :link t.timestamps null: false end end end
mit
ebnibrahem/m5
app/_c/admin/setting.php
1227
<?php namespace M5\Controllers\Admin; use M5\MVC\App; use M5\MVC\Controller as BaseController; use M5\Library\Bread; use M5\Library\Page; use M5\Library\Session; use M5\Library\Clean; use M5\Library\Auth; use M5\MVC\Model; class Setting extends BaseController { private $tbl = "preferences"; private $class_label = "setting"; function __construct() { parent::__construct(); $this->request->formAction = "admin/setting/"; /*instant model : Singleton Style*/ $this->model = Model::getInst($this->tbl); /*breadcrumb*/ $this->data["title"] = str($this->class_label); $this->data["bread"] = Bread::create( [$this->data["title"]=>"#"], null ); } /** * Main Function */ public function index($params = []) { $this->customize(); /*view*/ $this->getView()->template("admin/setting_cp_view",$this->data,$templafolder="admin/"); } /* Set cusomize values*/ private function customize() { /*forget_aproach*/ $this->data['forget_aproach'] = $this->model->getPref("forget_aproach"); if($_POST['forget_aproachBtnAdd']){ extract($_POST); // pa(0,1); $forget_aproach = $forget_aproach; $this->model->setPref("forget_aproach",$forget_aproach); page::location($page); } } }
mit
tarnfeld/snowey
example/example.rb
315
#!/usr/bin/env ruby require 'socket' opts = { :address => "0.0.0.0", :port => 2478 } connection = TCPSocket.open opts[:address], opts[:port] # Get ID connection.print "ID twtmore" puts connection.gets # Get INFO connection.print "INFO twtmore" puts connection.gets # Close the connection connection.close
mit
conveyal/analysis-ui
pages/regions/[regionId]/projects/[projectId]/modifications/[modificationId].js
2145
import dynamic from 'next/dynamic' import {useCallback} from 'react' import {useDispatch, useSelector} from 'react-redux' import {loadBundle} from 'lib/actions' import getFeedsRoutesAndStops from 'lib/actions/get-feeds-routes-and-stops' import { saveToServer, setLocally, loadModification } from 'lib/actions/modifications' import {loadProject} from 'lib/actions/project' import MapLayout from 'lib/layouts/map' import selectModification from 'lib/selectors/active-modification' import withInitialFetch from 'lib/with-initial-fetch' // Lots of the ModificationEditor code depends on Leaflet. Load it all client side const ModificationEditor = dynamic( () => import('lib/components/modification/editor'), {ssr: false} ) const EditorPage = withInitialFetch( function Editor({query}) { const dispatch = useDispatch() const modification = useSelector(selectModification) const update = useCallback( (m) => { dispatch(saveToServer(m)) }, [dispatch] ) const updateLocally = useCallback( (m) => { dispatch(setLocally(m)) }, [dispatch] ) return ( <ModificationEditor modification={modification} query={query} update={update} updateLocally={updateLocally} /> ) }, async (dispatch, query) => { const {modificationId, projectId} = query // TODO check if project and feed are already loaded const r1 = await Promise.all([ // Always reload the modification to get recent changes dispatch(loadModification(modificationId)), dispatch(loadProject(projectId)) ]) const modification = r1[0] const project = r1[1] // Only gets unloaded feeds for modifications that have them const r2 = await Promise.all([ dispatch(loadBundle(project.bundleId)), dispatch( getFeedsRoutesAndStops({ bundleId: project.bundleId, modifications: [modification] }) ) ]) return { bundle: r2[0], feeds: r2[1], modification, project } } ) EditorPage.Layout = MapLayout export default EditorPage
mit
gerich-home/ROI-Web-School
CRM/Web/Global.asax.cs
501
namespace Crm { using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; using Web; public class MvcApplication : HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
mit
LiveSplit/LiveSplit
LiveSplit/LiveSplit.Core/Model/TimeStamp.cs
4246
using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace LiveSplit.Model { public sealed class TimeStamp { public static double PersistentDrift { get; set; } public static double NewDrift { get; set; } private static Stopwatch qpc; private static TimeSpan firstQPCTime; private static DateTime firstNTPTime; private static TimeSpan lastQPCTime; private static DateTime lastNTPTime; private readonly TimeSpan value; private TimeStamp(TimeSpan value) { this.value = value; } static TimeStamp() { PersistentDrift = 1.0; NewDrift = 1.0; firstQPCTime = lastQPCTime = TimeSpan.Zero; firstNTPTime = lastNTPTime = DateTime.MinValue; qpc = new Stopwatch(); qpc.Start(); Task.Factory.StartNew(() => RefreshDrift()); } public static TimeStamp Now => new TimeStamp(TimeSpan.FromMilliseconds(qpc.Elapsed.TotalMilliseconds / PersistentDrift)); public static bool IsSyncedWithAtomicClock => lastQPCTime != TimeSpan.Zero; public static AtomicDateTime CurrentDateTime { get { if (IsSyncedWithAtomicClock) { return new AtomicDateTime(lastNTPTime.Add(Now - new TimeStamp(lastQPCTime)), true); } return new AtomicDateTime(DateTime.UtcNow, false); } } private static void RefreshDrift() { while (true) { var times = new List<long>(); DateTime ntpTime; TimeSpan qpcTime = TimeSpan.Zero; for (var count = 1; count <= 10; count++) { try { ntpTime = NTP.Now; qpcTime = qpc.Elapsed; times.Add(ntpTime.Ticks - qpcTime.Ticks); } catch { } if (count < 10) Wait(TimeSpan.FromSeconds(5)); } if (times.Count >= 5) { var averageDifference = times.Average(); lastQPCTime = qpcTime; lastNTPTime = new DateTime(qpcTime.Ticks + (long)averageDifference, DateTimeKind.Utc); if (firstQPCTime != TimeSpan.Zero) { var qpcDelta = lastQPCTime - firstQPCTime; var ntpDelta = lastNTPTime - firstNTPTime; var newDrift = qpcDelta.TotalMilliseconds / ntpDelta.TotalMilliseconds; // Ignore any drift that is too far from 1 if (Math.Abs(newDrift - 1) < 0.01) { var weight = Math.Pow(0.95, ntpDelta.TotalHours); NewDrift = Math.Pow(newDrift, 1 - weight) * Math.Pow(PersistentDrift, weight); } Wait(TimeSpan.FromHours(0.5)); } else { firstQPCTime = lastQPCTime; firstNTPTime = lastNTPTime; Wait(TimeSpan.FromHours(1)); } } else Wait(TimeSpan.FromHours(0.5)); } } private static void Wait(TimeSpan waitTime) { var before = Now; Thread.Sleep(waitTime); var elapsed = Now - before; if (elapsed.TotalMinutes > waitTime.TotalMinutes + 2) { firstQPCTime = TimeSpan.Zero; firstNTPTime = DateTime.MinValue; } } public static TimeSpan operator -(TimeStamp a, TimeStamp b) => a.value - b.value; public static TimeStamp operator -(TimeStamp a, TimeSpan b) => new TimeStamp(a.value - b); } }
mit
agrc/deq-spills
scripts/deq_spills_pallet.py
1435
#!/usr/bin/env python # * coding: utf8 * ''' deq_spills_pallet.py A module containing the pallet plugin for the deq-spills project. ''' from os.path import join from forklift.models import Pallet class DEQSpillsPallet(Pallet): def build(self, configuration): self.arcgis_services = [('DEQSpills/MapService', 'MapServer'), ('DEQSpills/ReferenceLayers', 'MapServer')] self.sgid = join(self.garage, 'SGID.sde') self.environment = join(self.staging_rack, 'environment.gdb') self.boundaries = join(self.staging_rack, 'boundaries.gdb') self.health = join(self.staging_rack, 'health.gdb') self.copy_data = [self.environment, self.boundaries, self.health] self.add_crates(['BFNONTARGETED', 'BFTARGETED', 'SITEREM', 'NPL', 'EWA', 'FUD', 'MMRP', 'TIER2', 'TRI', 'FACILITYUST', 'VCP', 'EnvironmentalIncidents'], {'source_workspace': self.sgid, 'destination_workspace': self.environment}) self.add_crate(('Counties', self.sgid, self.boundaries)) self.add_crate(('HealthDistricts', self.sgid, self.health))
mit
from-nibly/wyre
test/server/listen.js
1553
/*! * wyre: the new way to do websockets * Copyright(c) 2015 Jordan S Davidson <thatoneemail@gmail.com> * MIT Licensed */ var assert = require('assert'), Client = require('../../lib/index.js').Client, Server = require('../../lib/index.js').Server, MultiDone = require('../multiDone.js'), ClosingDone = require('../closingDone.js'), getPort = require('../portGetter.js'); describe('listen()', function() { it('should throw an error if there is no options object provided', function(done) { var server = new Server({ logLevel : 0 }); try { server.listen(); done('should have thrown an error'); } catch (err) { done(); } }); it('should throw an error if options is not an object', function(done) { var server = new Server({ logLevel : 0 }); try { server.listen('testing'); done('should have thrown an error'); } catch (err) { done(); } }); it('should throw an error if options does not have a port', function(done) { var server = new Server({ logLevel : 0 }); try { server.listen({}); done('should have thrown an error'); } catch (err) { done(); } }); it('should not throw an error if options does have a port', function(done) { var server = new Server({ logLevel : 0 }); done = new ClosingDone(done, [server]); var port = getPort(); try { server.listen({ port: port }, function(err) { done(err); }); } catch (err) { done(err); } }); }); // end listen()
mit
GTMAP-OS/helium
client/src/main/java/cn/gtmap/helium/client/converter/ValueConverter.java
842
package cn.gtmap.helium.client.converter; import cn.gtmap.helium.client.exception.WrongAppConfigException; /** * Author: <a href="mailto:yingxiufeng@gtmap.cn">yingxiufeng</a> * Date: 2016/6/18 9:42 */ public interface ValueConverter<T> { /** * 将属性值转换为目标数据类型. * * @param key 键 * @param value 值 * @return 值 * @throws WrongAppConfigException 如果值类型与目标类型不匹配 */ T convert(String key, String value) throws WrongAppConfigException; /** * 将属性值转换为目标数据类型. 如果值类型不匹配或者未设置则返回默认值. * * @param key 键 * @param value 值 * @param defaultValue 默认值 * @return 值 */ T convert(String key, String value, T defaultValue); }
mit
zigiphp/zigiphp-2
App/serviceProviders/validatorServiceProvider.php
93
<?php /** * @return \App\Validator */ return function () { return new \App\Validator(); };
mit
grecosoft/NetFusion
netfusion/src/Common/NetFusion.Common/Extensions/Reflection/CreationExtensions.cs
3451
using System; using System.Collections.Generic; using System.Linq; namespace NetFusion.Common.Extensions.Reflection { /// <summary> /// Extension methods for creating object instances and for checking /// related type properties. /// </summary> public static class CreationExtensions { /// <summary> /// Determines if the type is a class that can be instantiated with a default constructor. /// </summary> /// <param name="type">Class type to be checked for default constructor instantiation.</param> /// <returns>True if the type is a class with a default constructor. Otherwise False.</returns> public static bool IsCreatableClassType(this Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); return type.IsClass && !type.IsGenericType && !type.IsAbstract && type.HasDefaultConstructor(); } /// <summary> /// Creates an instance of a type using the constructor with matching parameter types. /// </summary> /// <param name="type">The type of the object to be created.</param> /// <param name="args">The arguments to pass to a matching constructor.</param> /// <returns>The created instance.</returns> public static object CreateInstance(this Type type, params object[] args) { if (type == null) throw new ArgumentNullException(nameof(type)); return Activator.CreateInstance(type, args); } /// <summary> /// Filters the source list of types to those deriving from a specified base type /// and creates an instance of each type. /// </summary> /// <typeparam name="T">The base type to filter the list of potential derived types.</typeparam> /// <param name="types">The list of potential derived types to filter.</param> /// <returns>Distinct list of object instances of all types deriving from the specified base type.</returns> public static IEnumerable<T> CreateInstancesDerivingFrom<T>(this IEnumerable<Type> types) { if (types == null) throw new ArgumentNullException(nameof(types)); foreach (Type type in types.Where(t => t.IsCreatableClassType() && t.IsDerivedFrom<T>()).Distinct()) { yield return (T)type.CreateInstance(); } } /// <summary> /// Filters the source list of types to those deriving from a specified base type /// and creates an instance of each type. /// </summary> /// <param name="types">The list of potential derived types to filter.</param> /// <param name="baseType">The base type to filter the list of potential derived types.</param> /// <returns>Distinct list of object instances of all types deriving from the specified base type.</returns> public static IEnumerable<object> CreateInstancesDerivingFrom(this IEnumerable<Type> types, Type baseType) { if (types == null) throw new ArgumentNullException(nameof(types)); if (baseType == null) throw new ArgumentNullException(nameof(baseType)); foreach (Type type in types.Where(t => t.IsCreatableClassType() && t.IsDerivedFrom(baseType)).Distinct()) { yield return type.CreateInstance(); } } } }
mit
TooTallNate/NodObjC
examples/nsapplescript.js
781
var $ = require('../'); // import the "Foundation" framework and its dependencies $.import('Foundation'); // create the mandatory NSAutoreleasePool instance var pool = $.NSAutoreleasePool('alloc')('init'); // create an NSString of the applescript command that will be run var command = $('tell (system info) to return system version'); // create an NSAppleScript instance with the `command` NSString var appleScript = $.NSAppleScript('alloc')('initWithSource', command); // finally execute the NSAppleScript instance synchronously var resultObj = appleScript('executeAndReturnError', null); // resultObj may be `null` or an NSAppleEventDescriptor instance, so check first if (resultObj) { // print out the value console.log(resultObj('stringValue')); } pool('release');
mit
coe/WinkModule
winkfragment/src/main/java/jp/coe/winkfragment/camera/GraphicOverlay.java
6373
/* * Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.coe.winkfragment.camera; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import com.google.android.gms.vision.CameraSource; import java.util.HashSet; import java.util.Set; /** * A view which renders a series of custom graphics to be overlayed on top of an associated preview * (i.e., the camera preview). The creator can add graphics objects, update the objects, and remove * them, triggering the appropriate drawing and invalidation within the view.<p> * * Supports scaling and mirroring of the graphics relative the camera's preview properties. The * idea is that detection items are expressed in terms of a preview size, but need to be scaled up * to the full view size, and also mirrored in the case of the front-facing camera.<p> * * Associated {@link Graphic} items should use the following methods to convert to view coordinates * for the graphics that are drawn: * <ol> * <li>{@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of the * supplied value from the preview scale to the view scale.</li> * <li>{@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the coordinate * from the preview's coordinate system to the view coordinate system.</li> * </ol> */ public class GraphicOverlay extends View { private final Object mLock = new Object(); private int mPreviewWidth; private float mWidthScaleFactor = 1.0f; private int mPreviewHeight; private float mHeightScaleFactor = 1.0f; private int mFacing = CameraSource.CAMERA_FACING_BACK; private Set<Graphic> mGraphics = new HashSet<>(); /** * Base class for a custom graphics object to be rendered within the graphic overlay. Subclass * this and implement the {@link Graphic#draw(Canvas)} method to define the * graphics element. Add instances to the overlay using {@link GraphicOverlay#add(Graphic)}. */ public static abstract class Graphic { private GraphicOverlay mOverlay; public Graphic(GraphicOverlay overlay) { mOverlay = overlay; } /** * Draw the graphic on the supplied canvas. Drawing should use the following methods to * convert to view coordinates for the graphics that are drawn: * <ol> * <li>{@link Graphic#scaleX(float)} and {@link Graphic#scaleY(float)} adjust the size of * the supplied value from the preview scale to the view scale.</li> * <li>{@link Graphic#translateX(float)} and {@link Graphic#translateY(float)} adjust the * coordinate from the preview's coordinate system to the view coordinate system.</li> * </ol> * * @param canvas drawing canvas */ public abstract void draw(Canvas canvas); /** * Adjusts a horizontal value of the supplied value from the preview scale to the view * scale. */ public float scaleX(float horizontal) { return horizontal * mOverlay.mWidthScaleFactor; } /** * Adjusts a vertical value of the supplied value from the preview scale to the view scale. */ public float scaleY(float vertical) { return vertical * mOverlay.mHeightScaleFactor; } /** * Adjusts the x coordinate from the preview's coordinate system to the view coordinate * system. */ public float translateX(float x) { if (mOverlay.mFacing == CameraSource.CAMERA_FACING_FRONT) { return mOverlay.getWidth() - scaleX(x); } else { return scaleX(x); } } /** * Adjusts the y coordinate from the preview's coordinate system to the view coordinate * system. */ public float translateY(float y) { return scaleY(y); } public void postInvalidate() { mOverlay.postInvalidate(); } } public GraphicOverlay(Context context, AttributeSet attrs) { super(context, attrs); } /** * Removes all graphics from the overlay. */ public void clear() { synchronized (mLock) { mGraphics.clear(); } postInvalidate(); } /** * Adds a graphic to the overlay. */ public void add(Graphic graphic) { synchronized (mLock) { mGraphics.add(graphic); } postInvalidate(); } /** * Removes a graphic from the overlay. */ public void remove(Graphic graphic) { synchronized (mLock) { mGraphics.remove(graphic); } postInvalidate(); } /** * Sets the camera attributes for size and facing direction, which informs how to transform * image coordinates later. */ public void setCameraInfo(int previewWidth, int previewHeight, int facing) { synchronized (mLock) { mPreviewWidth = previewWidth; mPreviewHeight = previewHeight; mFacing = facing; } postInvalidate(); } /** * Draws the overlay with its associated graphic objects. */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); synchronized (mLock) { if ((mPreviewWidth != 0) && (mPreviewHeight != 0)) { mWidthScaleFactor = (float) canvas.getWidth() / (float) mPreviewWidth; mHeightScaleFactor = (float) canvas.getHeight() / (float) mPreviewHeight; } for (Graphic graphic : mGraphics) { graphic.draw(canvas); } } } }
mit
dwickstrom/Manager
src/MageTest/Manager/FixtureFallback.php
1904
<?php namespace MageTest\Manager; /** * Class FixtureFallback * * @package MageTest\Manager */ final class FixtureFallback { /** * Where project specific fixtures should be stored */ const CUSTOM_DIRECTORY_LOCATION = 'tests/fixtures'; /** * Where default fixtures are stored */ const DEFAULT_DIRECTORY_LOCATION = '/Fixtures'; /** * Fixture formats fallback order * * @var array */ public static $sequence = [ '.php', '.yml', '.json', '.xml' ]; /** * Registry that matches resource names to fixture file names * * @var array */ public static $fixtureTypes = [ 'admin/user' => 'admin' ]; /** * Fixture location fallback order * * @return array */ public static function locationSequence() { return [ static::getCustomLocation(), static::getDefaultLocation() ]; } /** * @return string */ private static function getCustomLocation() { return getcwd() . DIRECTORY_SEPARATOR . static::CUSTOM_DIRECTORY_LOCATION; } /** * @return string */ private static function getDefaultLocation() { return __DIR__ . static::DEFAULT_DIRECTORY_LOCATION; } /** * @param $fixtureType * @param $fileType * @return string */ public static function getFileName($fixtureType, $fileType) { if (isset(static::$fixtureTypes[$fixtureType])) { return static::$fixtureTypes[$fixtureType] . $fileType; } return static::parseFileName($fixtureType) . $fileType; } /** * @param $fixtureType * @return mixed */ private static function parseFileName($fixtureType) { $bits = explode('/', $fixtureType); return end($bits); } }
mit
michel98/RA1
RA-KimberlyMichelEstradaBlanco/WebApplication1/Properties/AssemblyInfo.cs
1475
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie los valores de estos atributos para modificar la información // asociada a un ensamblado. [assembly: AssemblyTitle("WebApplication1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebApplication1")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si ComVisible se establece en false, los componentes COM no verán los // tipos de este ensamblado. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible en true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID es para el Id. typelib cuando este proyecto esté expuesto a COM [assembly: Guid("72a70167-563e-448e-857b-ce92abd66bff")] // La información de versión de un ensamblado consta de los siguientes cuatro valores: // // Major Version // Minor Version // Build Number // Revision // // Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión // mediante el carácter '*', como se muestra a continuación: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
liangzhifeng/yo
lib/proxyRoute.js
2376
/*! * yo * Copyright(c) 2015 Hbomb * MIT Licensed */ 'use strict'; /** * 模块依赖 * @private */ var _ = require('lodash'); var fs = require('fs'); var md5 = require('./util').md5; //接口配置字典 exports.interfacesConfig = {}; /** * 解析接口信息,配置初始化接口路由 * @param {[type]} app web APP * @param {Array} interfaces 接口信息 * @return {void} */ var parseConfig = function(app) { _.forEach(exports.interfacesConfig, function(val) { var domain = val.domain; val.route = val.route || val.url; //如果route没有配置则读取url作为路由 console.log('[' + val.method + ']' + domain + val.route); app[val.method.toLowerCase()](val.route, function(req, res, next) { req.proxyParams = { params: _.merge(req.params, req.query), body: req.body }; next(); }); }); }; /** * 加载配置的接口路径 * @param {String} path 接口路径 * @param {Function} callback 完成回调 */ var loadConfig = function(path, callback) { fs.readdir(path, function(err, files) { if (err) { callback(err); return; } _.forEach(files, function(val) { var m = require((path + '/' + val).replace('.js', '')); if (m.domain && m.res && _.isArray(m.res) && m.res.length > 0) { _.forEach(m.res, function(v) { v.domain = m.domain; var key = exports.genKey(v.method, v.route); exports.interfacesConfig[key] = v; }); } else { callback(new Error('空的接口依赖')); } }); callback(); }); }; /** * 生成key * @param {string} method 方法 * @param {string} route 路由 * @return {string} 返回MD5的key */ exports.genKey = function(method, route) { return md5(method + route); }; /** * 初始化 * @param {Express} app web app * @param {String} path 接口路径 * @param {Function} callback 初始化完成事件触发 */ exports.init = function(app, path, callback) { loadConfig(path, function(err) { if (err) { callback(err); return; } parseConfig(app); callback(); }); };
mit
xuan6/admin_dashboard_local_dev
node_modules/react-icons-kit/entypo/fastForward.js
558
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var fastForward = exports.fastForward = { "viewBox": "0 0 20 20", "children": [{ "name": "path", "attribs": { "d": "M9.244,9.52L2.041,4.571C1.469,4.188,1,4.469,1,5.196v9.609c0,0.725,0.469,1.006,1.041,0.625l7.203-4.951\r\n\tc0,0,0.279-0.199,0.279-0.478C9.523,9.721,9.244,9.52,9.244,9.52z M18.6,10.001c0,0.279-0.279,0.478-0.279,0.478l-7.203,4.951\r\n\tc-0.572,0.381-1.041,0.1-1.041-0.625V5.196c0-0.727,0.469-1.008,1.041-0.625L18.32,9.52C18.32,9.52,18.6,9.721,18.6,10.001z" } }] };
mit
angular/angular-cli-stress-test
src/app/components/comp-2863/comp-2863.component.spec.ts
847
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Comp2863Component } from './comp-2863.component'; describe('Comp2863Component', () => { let component: Comp2863Component; let fixture: ComponentFixture<Comp2863Component>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ Comp2863Component ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(Comp2863Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
mit
N00bface/Real-Dolmen-Stage-Opdrachten
stageopdracht/src/main/resources/static/vendors/gentelella/vendors/echarts/test/ut/core/utHelper.js
4361
/* * Copyright (c) 2017. MIT-license for Jari Van Melckebeke * Note that there was a lot of educational work in this project, * this project was (or is) used for an assignment from Realdolmen in Belgium. * Please just don't abuse my work */ (function (context) { /** * @public * @type {Object} */ var helper = context.utHelper = {}; var nativeSlice = Array.prototype.slice; /** * @param {*} target * @param {*} source */ helper.extend = function (target, source) { for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } return target; } /** * @public */ helper.g = function (id) { return document.getElementById(id); }; /** * @public */ helper.removeEl = function (el) { var parent = helper.parentEl(el); parent && parent.removeChild(el); }; /** * @public */ helper.parentEl = function (el) { //parentElement for ie. return el.parentElement || el.parentNode; }; /** * 得到head * * @public */ helper.getHeadEl = function (s) { return document.head || document.getElementsByTagName('head')[0] || document.documentElement; }; /** * @public */ helper.curry = function (func) { var args = nativeSlice.call(arguments, 1); return function () { return func.apply(this, args.concat(nativeSlice.call(arguments))); }; }; /** * @public */ helper.bind = function (func, context) { var args = nativeSlice.call(arguments, 2); return function () { return func.apply(context, args.concat(nativeSlice.call(arguments))); }; }; /** * Load javascript script * * @param {string} resource Like 'xx/xx/xx.js'; */ helper.loadScript = function (url, id, callback) { var head = helper.getHeadEl(); var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.setAttribute('charset', 'utf-8'); if (id) { script.setAttribute('id', id); } script.setAttribute('src', url); // @see jquery // Attach handlers for all browsers script.onload = script.onreadystatechange = function () { if (!script.readyState || /loaded|complete/.test(script.readyState)) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Dereference the script script = undefined; callback && callback(); } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (jquery #2709 and #4378). head.insertBefore(script, head.firstChild); }; /** * Reset package loader, where esl is cleaned and reloaded. * * @public */ helper.resetPackageLoader = function (then) { // Clean esl var eslEl = helper.g('esl'); if (eslEl) { helper.removeEl(eslEl); } var eslConfig = helper.g('esl'); if (eslConfig) { helper.removeEl(eslConfig); } context.define = null; context.require = null; // Import esl. helper.loadScript('esl.js', 'esl', function () { helper.loadScript('config.js', 'config', function () { then(); }); }); }; /** * @public * @param {Array.<string>} deps * @param {Array.<Function>} testFnList * @param {Function} done All done callback. */ helper.resetPackageLoaderEachTest = function (deps, testFnList, done) { var i = -1; next(); function next() { i++; if (testFnList.length <= i) { done(); return; } helper.resetPackageLoader(function () { window.require(deps, function () { testFnList[i].apply(null, arguments); next(); }); }); } }; })(window);
mit
MisterToolbox/bittrex-api
lib/bittrex/summary.rb
914
require 'time' module Bittrex class Summary attr_reader :market, :name, :high, :low, :volume, :last, :base_volume, :raw, :created_at alias_method :vol, :volume alias_method :base_vol, :base_volume def initialize(attrs = {}, market = nil) @market = market @name = attrs['MarketName'] @high = attrs['High'] @low = attrs['Low'] @volume = attrs['Volume'] @last = attrs['Last'] @base_volume = attrs['BaseVolume'] @raw = attrs @created_at = Time.parse(attrs['TimeStamp']) end def self.all client.get('public/getmarketsummaries').map{|data| new(data) } end def self.one(market) new(client.get('public/getmarketsummary', market: market)[0], market) end private def self.client @client ||= Bittrex.client end end end
mit
nikolai-b/rocket_pants
lib/rocket_pants/rspec_matchers.rb
4065
module RocketPants module RSpecMatchers extend RSpec::Matchers::DSL def self.normalised_error(e) if e.is_a?(String) || e.is_a?(Symbol) Errors[e] else e end end KEYS_TO_DELETE = %w(url root instance_options).freeze def self.normalise_urls(object) if object.is_a?(Array) object.each do |o| KEYS_TO_DELETE.each { |key| o[key] = nil } end elsif object.is_a?(Hash) || (defined?(APISmith::Smash) && object.is_a?(APISmith::Smash)) KEYS_TO_DELETE.each { |key| object[key] = nil } end object end # Converts it to JSON and back again. def self.normalise_as_json(object, options = {}) options = RocketPants.default_serializer_options.reverse_merge(options) options = options.reverse_merge(:compact => true) if object.is_a?(Array) object = RocketPants::Respondable.normalise_object(object, options) j = ActiveSupport::JSON j.decode(j.encode({'response' => object}))['response'] end def self.normalise_response(response, options = {}) normalise_urls normalise_as_json response, options end def self.valid_for?(response, allowed, disallowed) body = response.decoded_body return false if body.blank? body = body.to_hash return false if body.has_key?("error") allowed.all? { |f| body.has_key?(f) } && !disallowed.any? { |f| body.has_key?(f) } end def self.differ return @_differ if instance_variable_defined?(:@_differ) if defined?(RSpec::Support::Differ) @_differ = RSpec::Support::Differ.new elsif defined?(RSpec::Expectations::Differ) @_differ = RSpec::Expectations::Differ.new else @_differ = nil end end matcher :_be_api_error do |error_type| match do |response| @error = response.decoded_body.error @error.present? && (error_type.blank? || RSpecMatchers.normalised_error(@error) == error_type) end failure_message_for_should do |response| if @error.blank? "expected #{error_type || "any error"} on response, got no error" else error_type.present? && (normalised = RSpecMatchers.normalised_error(@error)) != error_type "expected #{error_type || "any error"} but got #{normalised} instead" end end failure_message_for_should_not do |response| "expected response to not have an #{error_type || "error"}, but it did (#{@error})" end end matcher :be_singular_resource do match do |response| RSpecMatchers.valid_for? response, %w(), %w(count pagination) end end matcher :be_collection_resource do match do |response| RSpecMatchers.valid_for? response, %w(count), %w(pagination) end end matcher :be_paginated_resource do match do |response| RSpecMatchers.valid_for? response, %w(count pagination), %w() end end matcher :have_exposed do |*args| normalised_response = RSpecMatchers.normalise_response(*args) match do |response| @decoded = RSpecMatchers.normalise_urls(response.parsed_body["response"]) normalised_response == @decoded end should_failure_method = respond_to?(:failure_message) ? :failure_message : :failure_message_for_should should_not_failure_method = respond_to?(:failure_message_when_negated) ? :failure_message_when_negated : :failure_message_for_should_not send(should_failure_method) do |response| message = "expected api to have exposed #{normalised_response.inspect}, got #{@decoded.inspect} instead." if differ = RSpecMatchers.differ message << "\n\nDiff: #{differ.diff_as_object(@decoded, normalised_response)}" end message end send(should_not_failure_method) do |response| "expected api to not have exposed #{normalised_response.inspect}" end end def be_api_error(error = nil) _be_api_error error end end end
mit
ev34j/ev34j
ev34j-core/src/main/java/com/ev34j/core/buttons/ev3/ButtonType.java
604
package com.ev34j.core.buttons.ev3; import static java.lang.String.format; public enum ButtonType { UP(103), DOWN(108), LEFT(105), RIGHT(106), ENTER(28), BACKSPACE(14); private final int value; ButtonType(final int value) { this.value = value; } public int getValue() { return this.value; } public static ButtonType findByValue(final int value) { for (ButtonType type : ButtonType.values()) if (type.getValue() == value) return type; throw new IllegalArgumentException(format("Invalid %s value: %d", ButtonType.class.getSimpleName(), value)); } }
mit
Vibek/Human_intention
feature_extraction_package/src/Dead_ball.cpp
5535
#include <ros/ros.h> #include <tf/transform_listener.h> #include <stdio.h> #include <fstream> using namespace std; #define PI 3.14159265 int main(int argc, char** argv){ ros::init(argc, argv, "my_tf_listener"); ros::NodeHandle node; tf::TransformListener listener; ros::Rate rate(10.0); vector<double> right_hand_x; vector<double> right_hand_y; vector<double> right_hand_z; vector<double> left_hand_x; vector<double> left_hand_y; vector<double> left_hand_z; vector<double> head_x; vector<double> head_y; vector<double> head_z; double right_x = 0; double right_y = 0; double right_z = 0; double left_x = 0; double left_y = 0; double left_z = 0; double head1_x = 0; double head1_y = 0; double head1_z = 0; while (node.ok()){ tf::StampedTransform transform1; tf::StampedTransform transform2; try{ // ---------- FOR THE RIGHT HAND --------------------------------------------------------------- listener.lookupTransform("/head_1", "/right_hand_1", ros::Time(0), transform1); double right_x_tmp = transform1.getOrigin().x(); // returns a position of the joint with respect to fixed frame double right_y_tmp = transform1.getOrigin().y(); // individual elements of position can be accessed by x,y,z double right_z_tmp = transform1.getOrigin().z(); // the difference between current and previous position double right_x_diff = right_x_tmp - right_x; double right_y_diff = right_y_tmp - right_y; double right_z_diff = right_z_tmp - right_z; right_x = right_x_tmp; right_y = right_y_tmp; right_z = right_z_tmp; //putting the values in vector to save right_hand_x.push_back(right_x_diff); right_hand_y.push_back(right_y_diff); right_hand_z.push_back(right_z_diff); cout <<"RIGHT HAND VALUE PUSHED INTO VECTOR" <<endl; // --------------------- FOR THE LEFT HAND ------------------------------------------------------ listener.lookupTransform("/head_1", "/left_hand_1", ros::Time(0), transform2); double left_x_tmp = transform2.getOrigin().x(); // returns a position of the joint with respect to fixed frame double left_y_tmp = transform2.getOrigin().y(); // individual elements of position can be accessed by x,y,z double left_z_tmp = transform2.getOrigin().z(); // the difference between current and previous position double left_x_diff = left_x_tmp - left_x; double left_y_diff = left_y_tmp - left_y; double left_z_diff = left_z_tmp - left_z; left_x = left_x_tmp; left_y = left_y_tmp; left_z = left_z_tmp; //putting the values in vector to save left_hand_x.push_back(left_x_diff); left_hand_y.push_back(left_y_diff); left_hand_z.push_back(left_z_diff); // --------------------- FOR THE HEAD ------------------------------------------------------ listener.lookupTransform("/neck_1", "/right_foot_1", ros::Time(0), transform2); double head_x_tmp = transform2.getOrigin().x(); // returns a position of the joint with respect to fixed frame double head_y_tmp = transform2.getOrigin().y(); // individual elements of position can be accessed by x,y,z double head_z_tmp = transform2.getOrigin().z(); // the difference between current and previous position double head_x_diff = head_x_tmp - head1_x; double head_y_diff = head_y_tmp - head1_y; double head_z_diff = head_z_tmp - head1_z; head1_x = head_x_tmp; head1_y = head_y_tmp; head1_z = head_z_tmp; //putting the values in vector to save head_x.push_back(head_x_diff); head_y.push_back(head_y_diff); head_z.push_back(head_z_diff); cout <<"LEFT HAND VALUE PUSHED INTO VECTOR" <<endl; } catch (tf::TransformException ex){ ROS_ERROR("%s",ex.what()); } rate.sleep(); } cout <<"ITERATOR STARS NOW, PLEASE PAY ATTENTION"<<endl; ofstream x_file; vector<double>::iterator j = right_hand_y.begin(); vector<double>::iterator k = right_hand_z.begin(); vector<double>::iterator l = left_hand_x.begin(); vector<double>::iterator m = left_hand_y.begin(); vector<double>::iterator n = left_hand_z.begin(); vector<double>::iterator o = head_x.begin(); vector<double>::iterator p = head_y.begin(); vector<double>::iterator q = head_z.begin(); x_file.open ("dead5_June16.csv", ios::app); //the flag ios::app makes sure that the control starts at the end of already existing file. x_file << 1; x_file << ","; for (vector<double>::iterator i = right_hand_x.begin(); i != right_hand_x.end();++i){ //cout << *i << endl; x_file << *i; x_file << ","; x_file << *j; x_file << ","; j++; x_file << *k; x_file << ","; k++; x_file << *l; x_file << ","; l++; x_file << *m; x_file << ","; m++; x_file << *n; x_file << ","; n++; x_file << *o; x_file << ","; o++; x_file << *p; x_file << ","; p++; x_file << *q; x_file << ","; q++; } x_file << 0; x_file << "\n"; /* cout <<"Y VALUES TARTS NOW. KEEP IN MIND"<<endl; for (vector<double>::iterator i = right_hand_y.begin(); i != right_hand_y.end();++i){ cout << *i << endl; x_file << *i; x_file << ","; } x_file << "\n"; cout <<"Z VALUES TARTS NOW. KEEP IN MIND"<<endl; for (vector<double>::iterator i = right_hand_z.begin(); i != right_hand_z.end();++i){ cout << *i << endl; x_file << *i; x_file << ","; } x_file << "\n"; */ x_file.close(); return 0; };
mit
rvalenciano/personal_page
config/session.js
1802
/** * Session * * Sails session integration leans heavily on the great work already done by Express, but also unifies * Socket.io with the Connect session store. It uses Connect's cookie parser to normalize configuration * differences between Express and Socket.io and hooks into Sails' middleware interpreter to allow you * to access and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#documentation */ module.exports.session = { // Session secret is automatically generated when your new app is created // Replace at your own risk in production-- you will invalidate the cookies of your users, // forcing them to log in again. secret: '73f88c26a17b1fd9ead58fd760e3e4e1' // In production, uncomment the following lines to set up a shared redis session store // that can be shared across multiple Sails.js servers // adapter: 'redis', // // The following values are optional, if no options are set a redis instance running // on localhost is expected. // Read more about options at: https://github.com/visionmedia/connect-redis // // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password> // prefix: 'sess:' // Uncomment the following lines to use your Mongo adapter as a session store // adapter: 'mongo', // // host: 'localhost', // port: 27017, // db: 'sails', // collection: 'sessions', // // Optional Values: // // # Note: url will override other connection settings // url: 'mongodb://user:pass@host:port/database/collection', // // username: '', // password: '', // auto_reconnect: false, // ssl: false, // stringify: true };
mit
scholster/QueskeyDev
src/Queskey/FrontEndBundle/Controller/CourseController.php
4300
<?php namespace Queskey\FrontEndBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class CourseController extends Controller { private $loggedInUser; function __construct() { $session = new \Symfony\Component\HttpFoundation\Session\Session(); $session->start(); $this->loggedInUser = $session->get("User"); } public function indexAction($id) { if($this->loggedInUser) { $em = $this->getDoctrine()->getManager(); $insId = $this->checkIfAdmin($id, $em); // if($this->loggedInUser->getAdmin() && $this->loggedInUser->getId() == $insId[0]['id']) if($this->loggedInUser->getId() == $insId[0]['id']) { return $this->redirect($this->generateUrl('courseEdit', array('id'=>$id))); } else { $array = $this->dbHandle($id, $em); return $this->render('FrontEndBundle:Course:course.html.twig',array('course'=>$array['course_info'], 'subscriptionFlag'=>$array['subscriptionFlag'])); } } else { return $this->render('FrontEndBundle:Common:pleaseLogin.html.twig'); } } public function editAction($id) { $em = $this->getDoctrine()->getManager(); $insId = $this->checkIfAdmin($id, $em); // if($this->loggedInUser->getAdmin() && $this->loggedInUser->getId() == $insId[0]['id']) if($this->loggedInUser) { if($this->loggedInUser->getId() == $insId[0]['id']) { $array = $this->dbHandle($id, $em); return $this->render('FrontEndBundle:Course:courseEdit.html.twig',array('course'=>$array['course_info'], 'subscriptionFlag'=>$array['subscriptionFlag'])); } else { return $this->render('FrontEndBundle:Default:notFound.html.twig'); } } else { return $this->render('FrontEndBundle:Common:pleaseLogin.html.twig'); } } public function dbHandle($id, $em) { $course_query = $em->createQuery('SELECT c.id, c.name, s.name as subcatname, cat.name as catname, c.description, i.name as ins_name, p.id as pid, p.price, p.expirytime, p.discountPercent, p.resubscriptionPrice, p.description FROM Queskey\FrontEndBundle\Entity\PaymentAssociation pass JOIN pass.paymentplan p JOIN pass.course c JOIN c.subcat s JOIN s.cat cat JOIN c.instructor i WHERE c.id = :id')->setParameter('id', $id); $array = array(); $array['course_info'] = $course_query->getResult(); $userId = $this->loggedInUser->getId(); // var_dump($userId); // die; $array['subscriptionFlag'] = $this->checkSubscription($userId, $id, $em); return $array; } public function checkSubscription($userid, $courseid, $em) { $course = new \Queskey\FrontEndBundle\Model\CheckSubscription(); $course_info = $course->checkIfSubscribed($userid, $courseid, $em); if($course_info) { $flag = $course->expiry($course_info); return array('expired'=>$flag, 'flag'=>1); } else { return array('expired'=>0, 'flag'=>0); } } public function checkIfAdmin($id, $em) { $insIdQuery = $em->createQuery('SELECT i.id FROM Queskey\FrontEndBundle\Entity\Course c JOIN c.instructor i WHERE c.id = :id')->setParameter('id', $id); return $insIdQuery->getResult(); } } ?>
mit
h8every1/yii2-requirejs-view
assets/JqueryAsset.php
210
<?php namespace h8every1\requirejsview\assets; class JqueryAsset extends RequireJsAssetBundle { public $sourcePath = '@bower/jquery/dist'; public $js = [ 'jquery' => ['jquery.min.js'], ]; }
mit
ascartabelli/lamb
src/__tests__/custom_matchers.js
1193
function isSparseArray (array) { return Array.isArray(array) && Object.keys(array).filter(function (v) { return String(v >>> 0) === v; }).length !== array.length; } function isSparseArrayCheckNeeded (a, b) { return isSparseArray(a) && Array.isArray(b) || isSparseArray(b) && Array.isArray(a); } expect.extend({ toStrictArrayEqual: function (a, b) { var result = { message: function () { return "Expected " + a + " to strict array equal " + b; } }; if (isSparseArrayCheckNeeded(a, b)) { var aLen = a.length; if (aLen !== b.length) { result.pass = false; return result; } for (var i = 0; i < aLen; i++) { if (i in a ^ i in b) { result.pass = false; return result; } else if (a[i] !== b[i]) { result.pass = false; return result; } } result.pass = true; return result; } result.pass = this.equals(a, b); return result; } });
mit
kevinjruffe/tick-tock
notificationSender.php
1161
<?php // Grab keys and info for database connection. require_once '/var/www/html/kevinruffe.com/keys.php'; // Create the database connection. $dsn = "mysql:host=$host;dbname=$dbname;charset=$charset"; $pdo = new PDO($dsn, $username, $password); // Find current time info. $currentHour = date('g'); $currentMinutes = intval(date('i')); // Check to see if a record for the current hour exists. $sql = 'SELECT email FROM pendingNotifications WHERE hour = ? and minutes = ?'; $dataArray = [$currentHour, $currentMinutes]; // Prepare and send the query. $query = $pdo->prepare($sql); $query->execute($dataArray); $email = $query->fetch(); // If you find a match, send an email reminder! (Then delete the record.) if ($email) { $email = $email[0]; $subject = 'Punch Reminder!'; $body = "Don't miss that punch! 👊\n- Tick-Tock"; $headers = "From: tick-tock@kevinruffe.com"; mail($email, $subject, $body, $headers); // Check to see if a record for the current hour exists. $sql = 'DELETE FROM pendingNotifications WHERE email = ?'; $dataArray = [$email]; // Prepare and send the query. $query = $pdo->prepare($sql); $query->execute($dataArray); }
mit
a11n/devfest-2016-realm
app/src/main/java/gdg/devfest/passwordmanager/framework/Injector.java
77
package gdg.devfest.passwordmanager.framework; public interface Injector {}
mit