code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* This file is part of the BlizzLikeCore Project. See CREDITS and LICENSE files * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Gehennas SD%Complete: 90 SDComment: SDCategory: Molten Core EndScriptData */ #include "precompiled.h" #include "molten_core.h" enum { SPELL_SHADOW_BOLT = 19728, // 19729 exists too, but can be reflected SPELL_RAIN_OF_FIRE = 19717, SPELL_GEHENNAS_CURSE = 19716 }; struct BLIZZLIKE_DLL_DECL boss_gehennasAI : public ScriptedAI { boss_gehennasAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); } ScriptedInstance* m_pInstance; uint32 m_uiShadowBoltTimer; uint32 m_uiRainOfFireTimer; uint32 m_uiGehennasCurseTimer; void Reset() override { m_uiShadowBoltTimer = 6000; m_uiRainOfFireTimer = 10000; m_uiGehennasCurseTimer = 12000; } void Aggro(Unit* /*pwho*/) override { if (m_pInstance) m_pInstance->SetData(TYPE_GEHENNAS, IN_PROGRESS); } void JustDied(Unit* /*pKiller*/) override { if (m_pInstance) m_pInstance->SetData(TYPE_GEHENNAS, DONE); } void JustReachedHome() override { if (m_pInstance) m_pInstance->SetData(TYPE_GEHENNAS, FAIL); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; // ShadowBolt Timer if (m_uiShadowBoltTimer < uiDiff) { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1)) { if (DoCastSpellIfCan(pTarget, SPELL_SHADOW_BOLT) == CAST_OK) m_uiShadowBoltTimer = 7000; } else // In case someone attempts soloing, we don't need to scan for targets every tick m_uiShadowBoltTimer = 7000; } else m_uiShadowBoltTimer -= uiDiff; // Rain of Fire Timer if (m_uiRainOfFireTimer < uiDiff) { if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) { if (DoCastSpellIfCan(pTarget, SPELL_RAIN_OF_FIRE) == CAST_OK) m_uiRainOfFireTimer = urand(4000, 12000); } } else m_uiRainOfFireTimer -= uiDiff; // GehennasCurse Timer if (m_uiGehennasCurseTimer < uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_GEHENNAS_CURSE) == CAST_OK) m_uiGehennasCurseTimer = 30000; } else m_uiGehennasCurseTimer -= uiDiff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_gehennas(Creature* pCreature) { return new boss_gehennasAI(pCreature); } void AddSC_boss_gehennas() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_gehennas"; pNewScript->GetAI = &GetAI_boss_gehennas; pNewScript->RegisterSelf(); }
blizzlikegroup/blizzlikecore
src/scripts/scripts/eastern_kingdoms/molten_core/boss_gehennas.cpp
C++
gpl-3.0
3,848
//---------------------------------------------------------------------------- // Copyright (C) 2004-2017 by EMGU Corporation. All rights reserved. //---------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Drawing; using System.Threading.Tasks; using Emgu.CV; using Emgu.CV.CvEnum; using Emgu.CV.Structure; using Emgu.Util; using PedestrianDetection; namespace Emgu.CV.XamarinForms { public class PedestrianDetectionPage : ButtonTextImagePage { public PedestrianDetectionPage() : base() { var button = this.GetButton(); button.Text = "Perform Pedestrian Detection"; OnImagesLoaded += async (sender, image) => { GetLabel().Text = "please wait..."; SetImage(null); Task<Tuple<Mat, long>> t = new Task<Tuple<Mat, long>>( () => { long time; if (image == null) return new Tuple<Mat, long>(null, 0); Rectangle[] pedestrians = FindPedestrian.Find(image[0], out time); foreach (Rectangle rect in pedestrians) { CvInvoke.Rectangle(image[0], rect, new MCvScalar(0, 0, 255), 2); } return new Tuple<Mat, long>(image[0], time); }); t.Start(); var result = await t; String computeDevice = CvInvoke.UseOpenCL ? "OpenCL: " + Ocl.Device.Default.Name : "CPU"; GetLabel().Text = String.Format("Detection completed with {1} in {0} milliseconds.", t.Result.Item2, computeDevice); SetImage(t.Result.Item1); }; button.Clicked += OnButtonClicked; } private void OnButtonClicked(object sender, EventArgs e) { LoadImages(new String[] { "pedestrian.png" }); } } }
neutmute/emgucv
Emgu.CV.Example/XamarinForms/Core/PedestrianDetectionPage.cs
C#
gpl-3.0
2,048
package ch.cyberduck.binding; /* * Copyright (c) 2002-2016 iterate GmbH. All rights reserved. * https://cyberduck.io/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ import ch.cyberduck.core.AbstractController; import ch.cyberduck.core.threading.MainAction; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.rococoa.ID; public class ProxyController extends AbstractController { private static final Logger log = LogManager.getLogger(ProxyController.class); private final Proxy proxy = new Proxy(this); public ID id() { return proxy.id(); } /** * Free all locked resources by this controller; also remove me from all observables; * marks this controller to be garbage collected as soon as needed */ public void invalidate() { if(log.isDebugEnabled()) { log.debug(String.format("Invalidate controller %s", this)); } proxy.invalidate(); } /** * You can use this method to deliver messages to the main thread of your application. The main thread * encompasses the application’s main run loop, and is where the NSApplication object receives * events. The message in this case is a method of the current object that you want to execute * on the thread. * <p> * Execute the passed <code>Runnable</code> on the main thread also known as NSRunLoop.DefaultRunLoopMode * * @param runnable The <code>Runnable</code> to run * @param wait Block until execution on main thread exits. A Boolean that specifies whether the current * thread blocks until after the specified selector is performed on the receiver on the main thread. * Specify YES to block this thread; otherwise, specify NO to have this method return immediately. * If the current thread is also the main thread, and you specify YES for this parameter, * the message is delivered and processed immediately. */ @Override public void invoke(final MainAction runnable, final boolean wait) { if(!runnable.isValid()) { return; } // The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle // of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated // while processing an event. If you use the Application Kit, you therefore typically don’t have to // create your own pools. proxy.invoke(runnable, runnable.lock(), wait); } }
iterate-ch/cyberduck
binding/src/main/java/ch/cyberduck/binding/ProxyController.java
Java
gpl-3.0
3,080
<?php namespace StubHubTest; use StubHub\Event; class EventTest extends \PHPUnit_Framework_TestCase { public function testEventSearch() { $response = new \stdClass(); $response->response = new \stdClass(); $client = $this->getMock('StubHub\Client'); $client->expects($this->once()) ->method('make_request') ->willReturn($response); $event = new Event($client); $searchResponse = $event->search('Cubs'); $this->assertEquals($searchResponse, $response); } }
TomSeldon/StubHub
tests/StubHub/src/StubHubTest/EventTest.php
PHP
gpl-3.0
556
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "base58.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "addressbookpage.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "dialogwindowflags.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QLocale> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent, DIALOGWINDOWHINTS), ui(new Ui::SendCoinsDialog), model(0), coinControl(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a GolfCoin address (e.g. 4Zo1ga6xuKuQ7JV7M9rGDoxdbYwV5zgQJ5)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; coinControl = new CoinControlDialog(0); connect(coinControl, SIGNAL(beforeClose()), this, SLOT(coinControlUpdateLabels())); } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getBalanceWatchOnly(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete coinControl; delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; if (ui->lineEditCoinControlChange->isEnabled()) { if(!ui->lineEditCoinControlChange->hasAcceptableInput() || (model && !model->validateAddress(ui->lineEditCoinControlChange->text()))) { CoinControlDialog::coinControl->destChange = CNoDestination(); ui->lineEditCoinControlChange->setValid(false); valid = false; } else CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); } for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { #if QT_VERSION < 0x050000 formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); #else formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address)); #endif } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 total, qint64 watchOnly, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, total - watchOnly)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance() - model->getBalanceWatchOnly())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { QApplication::clipboard()->setText(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { QApplication::clipboard()->setText(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { coinControl->setModel(model); coinControl->setWindowModality(Qt::ApplicationModal); coinControl->show(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); // ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked)); ui->addressBookButton->setEnabled((state == Qt::Checked)); ui->pasteButton->setEnabled((state == Qt::Checked)); } void SendCoinsDialog::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->lineEditCoinControlChange->setText(QApplication::clipboard()->text()); } void SendCoinsDialog::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->lineEditCoinControlChange->setText(dlg.getReturnValue()); } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
Golfcoin/2.0
src/qt/sendcoinsdialog.cpp
C++
gpl-3.0
17,996
# coding: utf-8 __author__ = 'Math' import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import random from scipy.interpolate import interp1d, PchipInterpolator, splrep, splev import matplotlib.patches as patches import matplotlib.path as path import matplotlib as mpl from mpltools import style from scipy.stats import gaussian_kde mpl.rc("figure", facecolor="white") class kernelhandler(object): def __init__(self, points, bandwidth): self.bandwidth = bandwidth self.points = points def kernel(self): def f(x): return 1.0/np.sqrt(2*np.pi)*np.exp(-1.0/2*x**2) return f def __call__(self, *args, **kwargs): x = kwargs['x'] f = self.kernel() inter = [f((x - x_i)*1.0/self.bandwidth)*y_i for x_i, y_i in self.points] weigth = [f((x - x_i)*1.0/self.bandwidth) for x_i, y_i in self.points] return ((1.0/sum(weigth))*sum(inter)) class Shape(object): def __init__(self, data, size_k): """ :param data: :param size_k: :return: """ self.data = data self.size_k = size_k self.nodes_ask = None self.nondes_bid = None self.__fig = None self.__ax = None self.__line_bid = None self.__line_ask = None self.__scat = None self.__patch_ask = None self.__patch_bid = None self.anot = None self.ticks = 500 self.__vert_ask = None self.__codes = None self.__vert_bid = None def cargando_figuras(self): """ :return: """ self.__fig, self.__ax = plt.subplots() self.__line_bid, = self.__ax.plot([], [], lw=2, c='#286090') self.__line_ask, = self.__ax.plot([], [], lw=2, c='#286090') self.__scat = self.__ax.scatter([], [], c='black', s=2) self.__ax.set_ylim(-1, 30) self.__ax.set_xlim(-6, 6) self.__ax.grid(linestyle='-', color='#808080', alpha=0.2) f = lambda x: [(float(x) + 0.5, 0.), (float(x) + 0.5, 0.)] self.__vert_ask = [f(x) for x in self.nodes_ask] self.__vert_ask = np.array(sum(self.__vert_ask, [])) f = lambda x: [(float(x) - 0.5, 0.), (float(x) - 0.5, 0.)] self.__vert_bid = [f(x) for x in self.nondes_bid] self.__vert_bid = np.array(sum(self.__vert_bid, [])) self.__codes = [path.Path.LINETO for _ in xrange(len(self.__vert_ask))] self.__codes[0] = path.Path.MOVETO self.__codes = np.array(self.__codes) barpath_ask = path.Path(self.__vert_ask, self.__codes) self.__patch_ask = patches.PathPatch(barpath_ask, facecolor='#5cb85c', edgecolor='#4cae4c', alpha=0.5) self.__ax.add_patch(self.__patch_ask) barpath_bid = path.Path(self.__vert_bid, self.__codes) self.__patch_bid = patches.PathPatch(barpath_bid, facecolor='#c9302c', edgecolor='#ac2925', alpha=0.5) self.__ax.add_patch(self.__patch_bid) # Se eliminan los ticks self.__ax.tick_params(width=0) # Se eliminan ejes self.__ax.spines["top"].set_visible(False) self.__ax.spines["right"].set_visible(False) self.__ax.spines["bottom"].set_visible(False) self.__ax.spines["left"].set_visible(False) self.__ax.tick_params(axis='x', colors='#404040') self.__ax.tick_params(axis='y', colors='#404040') self.anot = self.__ax.text(0.02, 0.95, '', transform=self.__ax.transAxes) def __update_limits_x(self, domain): """ :param domain: :return: """ xmin, xmax = self.__ax.get_xlim() min_domain = min(domain) max_domain = max(domain) any_change = False if xmax - 2 < max_domain: xmax = max_domain + 4 any_change = True elif abs(xmax - max_domain) > 10: xmax = max_domain + 3 any_change = True if xmin + 2 > min_domain : xmin = min_domain - 2 any_change = True elif abs(xmin - min_domain) > 10: xmin = min_domain - 4 any_change = True if any_change: self.__ax.set_xlim(xmin , xmax) self.__ax.figure.canvas.draw() def __update_limits_y(self, rango): """ :param rango: :return: """ ymin, ymax = self.__ax.get_ylim() min_rango = min(rango) max_rango = max(rango) any_change = False if ymax < max_rango: ymax = max_rango + 2 any_change = True elif abs(ymax - max_rango) > 10: ymax = max_rango + 3 any_change = True if ymin > min_rango : ymin = min_rango - 2 any_change = True elif abs(ymin - min_rango) > 10: ymin = min_rango - 3 any_change = True if any_change: self.__ax.set_ylim(ymin, ymax) self.__ax.figure.canvas.draw() def __interpolate_data(self, x, y): """ :param x: :param y: :return: """ x1 = x[:] y1 = y[:] if sorted(x1) != x1: x1.reverse() y1.reverse() f = PchipInterpolator(x1 , y1 , extrapolate=True) domain = np.linspace(x[0], x[-1], num=self.ticks, endpoint=True) return [f(a) for a in domain] def filter_data(self, x , y): index = -1 for i, data in enumerate(y): if data != 0 : index = i break if index == -1: return x , y for i in xrange(index): x.pop(0) y.pop(0) return x, y def __generator_data(self): """ :return: """ for orderbook in self.data: y_ask = [data[1] for data in orderbook[-1]] y_bid = [data[1] for data in orderbook[1]] x_ask = [data[0] for data in orderbook[-1]] x_bid = [data[0] for data in orderbook[1]] x_ask_fill, y_ask_fill= self.filter_data(x_ask[:] , y_ask[:]) x_bid_fill, y_bid_fill= self.filter_data(x_bid[:] , y_bid[:]) yield self.__interpolate_data(x_ask_fill, y_ask_fill), \ self.__interpolate_data(x_bid_fill, y_bid_fill), \ x_ask, x_bid, y_ask, y_bid, \ x_ask_fill, x_bid_fill, y_ask_fill, y_bid_fill def __run_data(self, data): """ :param data: :return: """ ask_inter_points, bid_inter_points, x_ask, x_bid, y_ask, y_bid, x_ask_fill, x_bid_fill, y_ask_fill, y_bid_fill = data mid_price = (y_ask_fill[0] + y_bid_fill[0])*1.0 / 2 # print mid_price self.anot.set_text('Mid Price = %.1f' % mid_price) # bid_inter_points.reverse() x_bid.reverse() y_bid.reverse() self.__update_limits_x(x_ask + x_bid) self.__update_limits_y(ask_inter_points + bid_inter_points) self.__line_bid.set_data(np.linspace(x_bid_fill[0], x_bid_fill[-1], num=self.ticks, endpoint=True), bid_inter_points,) self.__line_ask.set_data(np.linspace(x_ask_fill[0], x_ask_fill[-1], num=self.ticks, endpoint=True), ask_inter_points) self.__scat.set_offsets(np.array(zip(x_bid_fill + x_ask_fill, y_bid_fill + y_ask_fill))) for x, point in enumerate(y_ask): self.__vert_ask[x*2+1][1] = point self.__vert_ask[x*2+2][1] = point for x in xrange(len(y_ask), self.size_k): self.__vert_ask[x*2+1][1] = 0 self.__vert_ask[x*2+2][1] = 0 y_bid.reverse() a = len(self.__vert_bid) - 1 for x, point in enumerate(y_bid): self.__vert_bid[a-(x*2+1)][1] = point self.__vert_bid[a-(x*2+2)][1] = point for x in xrange(len(y_bid), self.size_k): self.__vert_bid[a-(x*2+1)][1] = 0 self.__vert_bid[a-(x*2+2)][1] = 0 return [self.__patch_ask, self.__patch_bid,self.__line_bid, self.__line_ask, self.__scat, self.anot] def __call__(self, *args, **kwargs): ani = animation.FuncAnimation(self.__fig, self.__run_data, self.__generator_data, blit=True, interval=100, repeat=False) plt.show() class levels_to_shape(object): def __init__(self, data, k): self.data = data self.size_k = k self.aux_data = [] self.shape = Shape(None, None) self.type_levels = None @property def data(self): return self.__data @data.setter def data(self, data): for orderbook in data: # print orderbook domain_ask = [x[0] for x in orderbook[-1]] assert all(domain_ask[i] < domain_ask[i + 1] for i in xrange(len(domain_ask) - 1)) domain_bid = [x[0] for x in orderbook[1]] # print domain_bid assert all(domain_bid[i] > domain_bid[i + 1] for i in xrange(len(domain_bid) - 1)) self.__data = data def distance_to_midprice(self): for orderbook in self.data: new_orderbook = {-1: [], 1: []} y_ask = [data[1] for data in orderbook[-1]] y_bid = [data[1] for data in orderbook[1]] x_ask = self.__ask_normalizade(y_ask) x_bid = self.__bid_normalizade(y_bid) new_orderbook[-1] = zip(x_ask, y_ask) new_orderbook[1] = zip(x_bid, y_bid) self.aux_data.append(new_orderbook) # print new_orderbook[-1] # print new_orderbook[1] # exit() self.type_levels = 'mid_price' self.set_nodes_barr() def distance_to_extreme(self): for orderbook in self.data: new_orderbook = {-1: [], 1: []} y_ask = [data[1] for data in orderbook[-1]] y_bid = [data[1] for data in orderbook[1]] len_ask = len(y_ask) len_bid = len(y_bid) x_ask = [len_bid + i for i in xrange(len_ask)] x_bid = [-(len_ask+i) for i in xrange(len_bid)] new_orderbook[-1] = zip(x_ask, y_ask) new_orderbook[1] = zip(x_bid, y_bid) # # print len_bid # print len_ask # print new_orderbook[-1] # print new_orderbook[1] # exit() for i in xrange(0, abs(x_bid[0]) - 1): new_orderbook[1].insert(i, (-(i+1), 0)) for i in xrange(1, x_ask[0]): new_orderbook[-1].insert(i - 1, (i, 0)) # print new_orderbook[-1] # print new_orderbook[1] # exit() self.aux_data.append(new_orderbook) self.type_levels = 'extreme' self.set_nodes_barr() def set_nodes_barr(self): if self.type_levels == 'mid_price': nodes_ask = xrange(self.size_k + 1) nodes_bid = xrange(-(self.size_k), 1) self.shape.nondes_bid = nodes_bid self.shape.nodes_ask = nodes_ask self.shape.size_k = self.size_k elif self.type_levels == 'extreme': nodes_ask = xrange(self.size_k*2 + 1) nodes_bid = xrange(-(self.size_k*2), 1) self.shape.nondes_bid = nodes_bid self.shape.nodes_ask = nodes_ask self.shape.size_k = self.size_k*2 def draw_shape(self): self.shape.data = self.aux_data self.shape.cargando_figuras() self.shape() def __bid_normalizade(self, p_bid): l = range(-len(p_bid), 0) l.reverse() return l def __ask_normalizade(self, p_ask): return range(1, len(p_ask) + 1) def generar_orderbook_lines(n_lines): lines = [] for i in xrange(n_lines): n_ask = random.randint(1, 4) ask = [(i, random.random() * 5 + 1) for i in xrange(0, 10, n_ask)] ask.sort(key = lambda x: x[0]) n_bid = random.randint(1, 4) bid = [(-(i+1), random.random() * 5 + 1) for i in xrange(0, 10, n_bid)] lines.append({-1: ask, 1: bid}) print lines return lines if __name__ == '__main__': lines = generar_orderbook_lines(500) shape_orderbook = levels_to_shape(lines, 10) # levels.distance_to_midprice() shape_orderbook.distance_to_extreme() shape_orderbook.draw_shape() # l = [(i, random.random()) for i in xrange(10)] # k = kernelhandler(l, 0.5) # s = [k(**{'x': x}) for x, y in l] # # print [p[1] for p in l] # print s # # plt.plot([p[0] for p in l], [p[1] for p in l] ) # # domain = np.linspace(0, 10, 100) # # plt.plot(domain, [k(**{'x': x}) for x in domain]) # # plt.show()
grupoanfi/orderbook-data-analysis
ODA/shape.py
Python
gpl-3.0
12,925
package com.amazonaws.ec2.doc._2008_12_01; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DescribeRegionsType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DescribeRegionsType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="regionSet" type="{http://ec2.amazonaws.com/doc/2008-12-01/}DescribeRegionsSetType"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DescribeRegionsType", propOrder = { "regionSet" }) public class DescribeRegionsType { @XmlElement(required = true) protected DescribeRegionsSetType regionSet; /** * Gets the value of the regionSet property. * * @return * possible object is * {@link DescribeRegionsSetType } * */ public DescribeRegionsSetType getRegionSet() { return regionSet; } /** * Sets the value of the regionSet property. * * @param value * allowed object is * {@link DescribeRegionsSetType } * */ public void setRegionSet(DescribeRegionsSetType value) { this.regionSet = value; } }
rforge/biocep
src_aws_client/com/amazonaws/ec2/doc/_2008_12_01/DescribeRegionsType.java
Java
gpl-3.0
1,630
#include <iostream> #include <tuple> /** 3 Simple C++17 Features That Will Make Your Code Simpler https://www.fluentcpp.com/2018/06/19/3-simple-c17-features-that-will-make-your-code-simpler/ */ using namespace std; int main() { { auto ch = '#'; auto i = 0; auto b = true; } { auto [ch,i,b] = tuple{'#',0,true}; } { // for(char ch = '#', int i = 0, bool b = true; i < 10; ++i) {} won't compile for (auto[ch,i,b] = tuple{'#',0,true } ; i < 10; ++i) {} } }
nikolaAV/Modern-Cpp
structured-bindings/direct_initialization/main.cpp
C++
gpl-3.0
522
package com.andy.design_patterns.combining.observer; public interface QuackObservable { public void registerObserver(Observer observer); public void notifyObservers(); }
Archerpe/aries
src/main/java/com/andy/design_patterns/combining/observer/QuackObservable.java
Java
gpl-3.0
180
package eu.f1io.io.baito.socketcon.filters; import eu.f1io.io.baito.socketcon.SocketConnectionContext; import eu.f1io.io.baito.socketcon.SocketConnectionFilter; import eu.f1io.io.baito.socketcon.SocketConnectionHandler; import eu.f1io.thread.ThreadProvider; public class ThreadedHandler extends SocketConnectionFilter { protected final ThreadProvider threadProvider; public ThreadedHandler(ThreadProvider threadProvider2, SocketConnectionHandler nextHandler) { super(nextHandler); this.threadProvider = threadProvider2; } @Override public void handle(final SocketConnectionContext cntx) { final Runnable r = new Runnable() { @Override public void run() { getNext().handle(cntx); } }; threadProvider.startInOwnThread(r); } }
fikin/f1io
baito/src/main/java/eu/f1io/io/baito/socketcon/filters/ThreadedHandler.java
Java
gpl-3.0
763
#include <cstdio> #include <cmath> #include <vector> #include <algorithm> #include <string> #include <time.h> #include "markov_chain.h" #include "peel_sequence_generator.h" #include "peeler.h" #include "locus_sampler2.h" #include "meiosis_sampler.h" #include "pedigree.h" #include "genetic_map.h" #include "descent_graph.h" #include "linkage_writer.h" #include "progress.h" #include "types.h" #include "random.h" #include "lod_score.h" #include "omp_facade.h" #ifdef USE_CUDA #include "gpu_lodscores.h" #endif using namespace std; //#define CODA_OUTPUT 1 void MarkovChain::_init() { // heat up the map map.set_temperature(temperature); // create samplers for(int i = 0; i < min(get_max_threads(), int(map.num_markers())); ++i) { LocusSampler* tmp = new LocusSampler(ped, &map, psg, i, options.sex_linked); lsamplers.push_back(tmp); } lod = new LODscores(&map); // lod scorers for(int i = 0; i < min(get_max_threads(), int((map.num_markers() - 1) * map.get_lodscore_count())); ++i) { Peeler* tmp = new Peeler(ped, &map, psg, lod, options.sex_linked); peelers.push_back(tmp); } double trait_prob = peelers[0]->calc_trait_prob(); printf("P(T) = %.5f\n", trait_prob / log(10)); // lod score result objects #ifdef USE_CUDA if(options.use_gpu) { gpulod = new GPULodscores(ped, &map, psg, options, trait_prob); } #endif //lod = new LODscores(&map); lod->set_trait_prob(trait_prob); // ordering for locus samplers for(int i = 0; i < int(map.num_markers()); ++i) { l_ordering.push_back(i); } // ordering for meiosis samplers unsigned num_meioses = 2 * (ped->num_members() - ped->num_founders()); for(unsigned int i = 0; i < num_meioses; ++i) { unsigned person_id = ped->num_founders() + (i / 2); enum parentage p = static_cast<enum parentage>(i % 2); Person* tmp = ped->get_by_index(person_id); if(not tmp->safe_to_ignore_meiosis(p)) { m_ordering.push_back(i); } } // create coda file if necessary if(options.coda_logging) { //string fname = options.coda_prefix + ".ped" + ped->get_id() + ".run" + to_string(seq_num); // does not work on gcc 4.8.X char buf[4]; sprintf(buf, "%d", seq_num); string fname = options.coda_prefix + ".ped" + ped->get_id() + ".run" + string(buf); coda_filehandle = fopen(fname.c_str(), "w"); fprintf(coda_filehandle, "iteration likelihood\n"); printf("opened trace file (%s)\n", fname.c_str()); } } void MarkovChain::_kill() { for(int i = 0; i < int(lsamplers.size()); ++i) { delete lsamplers[i]; } for(int i = 0; i < int(peelers.size()); ++i) { delete peelers[i]; } if(options.coda_logging) { fclose(coda_filehandle); } } void MarkovChain::step(DescentGraph& dg, int start_iteration, int step_size) { int thread_num = 0; for(int i = start_iteration; i < start_iteration + step_size; ++i) { if(get_random() < options.lsampler_prob) { random_shuffle(l_ordering.begin(), l_ordering.end()); vector<int> thread_assignments(get_max_threads(), -1); vector<int> tmp(l_ordering); #pragma omp parallel { thread_num = get_thread_num(); while(1) { #pragma omp critical { int locus = -1; if(not tmp.empty()) { for(int j = int(tmp.size()-1); j >= 0; --j) { if(noninterferring(thread_assignments, tmp[j], thread_num)) { locus = tmp[j]; tmp.erase(tmp.begin() + j); break; } } } thread_assignments[thread_num] = locus; } if(thread_assignments[thread_num] == -1) break; lsamplers[thread_num]->set_locus_minimal(thread_assignments[thread_num]); lsamplers[thread_num]->step(dg, thread_assignments[thread_num]); } } } else { random_shuffle(m_ordering.begin(), m_ordering.end()); msampler.reset(dg, m_ordering[0]); for(unsigned int j = 0; j < m_ordering.size(); ++j) { msampler.step(dg, m_ordering[j]); } } /* #ifdef CODA_OUTPUT if((i % options.scoring_period) == 0) { double current_likelihood = dg.get_likelihood(); if(current_likelihood == LOG_ILLEGAL) { fprintf(stderr, "error: descent graph illegal...\n"); abort(); } fprintf(stderr, "%d\t%f\n", i+1, current_likelihood); } continue; #endif */ if(i < options.burnin) continue; if(temperature != 1.0) continue; // only score the coldest chain if((i % options.scoring_period) == 0) { #ifdef USE_CUDA if(not options.use_gpu) { #endif #pragma omp parallel { thread_num = get_thread_num(); #pragma omp for for(int j = 0; j < int(map.num_markers() - 1); ++j) { peelers[thread_num]->set_locus(j); peelers[thread_num]->process(&dg); } } #ifdef USE_CUDA } else { gpulod->calculate(dg); } #endif } } #ifdef USE_CUDA if(options.use_gpu) { gpulod->get_results(lod); } #endif } void MarkovChain::run_scalable_lsampler(DescentGraph& dg, vector<int>& lgroups, int num_lgroups) { int thread_num = 0; random_shuffle(lgroups.begin(), lgroups.end()); for(int j = 0; j < num_lgroups; ++j) { #pragma omp parallel num_threads(lsamplers.size()) private(thread_num) { thread_num = get_thread_num(); #pragma omp for for(int k = lgroups[j]; k < int(map.num_markers()); k += num_lgroups) { lsamplers[thread_num]->set_locus_minimal(l_ordering[k]); lsamplers[thread_num]->step(dg, l_ordering[k]); } } } } void MarkovChain::run_old_lsampler(DescentGraph& dg) { int thread_num = 0; random_shuffle(l_ordering.begin(), l_ordering.end()); vector<int> thread_assignments(lsamplers.size(), -1); vector<int> tmp(l_ordering); #pragma omp parallel num_threads(lsamplers.size()) private(thread_num) { thread_num = get_thread_num(); while(1) { #pragma omp critical { int locus = -1; if(not tmp.empty()) { for(int j = int(tmp.size()-1); j >= 0; --j) { if(noninterferring(thread_assignments, tmp[j], thread_num)) { locus = tmp[j]; tmp.erase(tmp.begin() + j); break; } } } thread_assignments[thread_num] = locus; } if(thread_assignments[thread_num] == -1) break; lsamplers[thread_num]->set_locus_minimal(thread_assignments[thread_num]); lsamplers[thread_num]->step(dg, thread_assignments[thread_num]); #pragma omp critical { thread_assignments[thread_num] = -1; } } } } int MarkovChain::optimal_num_lgroups(DescentGraph& dg) { int best_num_lgroups = -1; double best_time, start_time, run_time; int repetitions = 100; if(get_max_threads() == 1) { return -1; } //best_time = numeric_limits<double>::infinity(); // test the old version first start_time = get_wtime(); for(int k = 0; k < repetitions; ++k) { run_old_lsampler(dg); } best_time = (get_wtime() - start_time) / repetitions; // fprintf(stderr, "%d lgroups, %f seconds\n", -1, best_time); // test scalable version with different step sizes for(int i = 3; i < 11; ++i) { vector<int> tmp(i); for(int j = 0; j < i; ++j) { tmp[j] = j; } start_time = get_wtime(); for(int k = 0; k < repetitions; ++k) { run_scalable_lsampler(dg, tmp, i); } run_time = (get_wtime() - start_time) / repetitions; if(run_time < best_time) { best_num_lgroups = i; best_time = run_time; } // fprintf(stderr, "%d lgroups, %f seconds\n", i, run_time); } return best_num_lgroups; } // old version LODscores* MarkovChain::run(DescentGraph& dg) { int thread_num = 0; int num_lgroups = -1; Progress p("MCMC: ", options.iterations + options.burnin); if(dg.get_likelihood() == LOG_ILLEGAL) { fprintf(stderr, "error: descent graph illegal pre-markov chain...\n"); abort(); } // fprintf(stderr, "\n"); num_lgroups = optimal_num_lgroups(dg); // fprintf(stderr, "\noptimal number of lgroups = %d\n", num_lgroups); // exit(1); vector<int> lgroups; //(num_lgroups, 0); for(int i = 0; i < num_lgroups; ++i) { lgroups.push_back(i); } for(int i = 0; i < (options.iterations + options.burnin); ++i) { if(get_random() < options.lsampler_prob) { if(num_lgroups == -1) { run_old_lsampler(dg); } else { run_scalable_lsampler(dg, lgroups, num_lgroups); } } else { random_shuffle(m_ordering.begin(), m_ordering.end()); msampler.reset(dg, m_ordering[0]); for(unsigned int j = 0; j < m_ordering.size(); ++j) { msampler.step(dg, m_ordering[j]); } } p.increment(); if(i < options.burnin) { continue; } if((i % options.scoring_period) == 0) { if(options.coda_logging) { double current_likelihood = dg.get_likelihood(); if(current_likelihood == LOG_ILLEGAL) { fprintf(stderr, "error: descent graph illegal...\n"); abort(); } fprintf(coda_filehandle, "%d\t%f\n", i+1, current_likelihood); } #ifdef USE_CUDA if(not options.use_gpu) { #endif #pragma omp parallel private(thread_num) { thread_num = get_thread_num(); #pragma omp for for(int j = 0; j < int(map.num_markers() - 1); ++j) { peelers[thread_num]->set_locus(j); peelers[thread_num]->process(&dg); } } #ifdef USE_CUDA } else { gpulod->calculate(dg); } #endif } } p.finish(); #ifdef USE_CUDA if(options.use_gpu) { gpulod->get_results(lod); } #endif return lod; } bool MarkovChain::noninterferring(vector<int>& x, int val, int thread_num) { for(int i = 0; i < int(x.size()); ++i) { if((i != thread_num) and (x[i] != -1)) { int diff = val - x[i]; if((diff == 1) or (diff == -1)) { return false; } } } return true; }
ajm/swiftlink
src/markov_chain.cc
C++
gpl-3.0
12,000
var searchData= [ ['end_5ftest',['END_TEST',['../group___calls_malloc.html#gaefcd1ca1799d2395f7bbe3c50bcc8ff8',1,'unit_test.h']]], ['endgame',['endGame',['../game__state_8h.html#aeda119595fcc834db9cfec532a90cf79',1,'game_state.c']]], ['endtrial',['endTrial',['../profile_8h.html#a8aae37a7e7fa5f85958ca30807cae136',1,'profile.c']]], ['err_5f1',['ERR_1',['../error_8h.html#abe0e0e5d41bcdf7365b58faf284d55b1',1,'error.h']]], ['err_5f10',['ERR_10',['../error_8h.html#a805aa89fa27b9a21ddafc999bba0bb68',1,'error.h']]], ['err_5f11',['ERR_11',['../error_8h.html#a7b8665db5362fa1e49816b7e5a839863',1,'error.h']]], ['err_5f12',['ERR_12',['../error_8h.html#ab6d13d5316dd231c323cf18998c7195e',1,'error.h']]], ['err_5f13',['ERR_13',['../error_8h.html#a57027f9c748ff6708774addce1746539',1,'error.h']]], ['err_5f14',['ERR_14',['../error_8h.html#a80b4f190b67f53f3c2dea7b01d966b6f',1,'error.h']]], ['err_5f15',['ERR_15',['../error_8h.html#aae5dc676babeb0e2b4702f59835382f4',1,'error.h']]], ['err_5f16',['ERR_16',['../error_8h.html#a1842caea0771e65e3219bb0278a181a4',1,'error.h']]], ['err_5f17',['ERR_17',['../error_8h.html#a28dcf048ee64c2f1a38f80f71d28fc2a',1,'error.h']]], ['err_5f18',['ERR_18',['../error_8h.html#ac9d7613d1c0680c3a6aa46c219fcb283',1,'error.h']]], ['err_5f19',['ERR_19',['../error_8h.html#acc63f7ea363c63c45e8efa026c6024b9',1,'error.h']]], ['err_5f2',['ERR_2',['../error_8h.html#a012097e952ead190cc831d35441d1828',1,'error.h']]], ['err_5f20',['ERR_20',['../error_8h.html#a62c46bd16d82b73650b04cf33d88b85e',1,'error.h']]], ['err_5f21',['ERR_21',['../error_8h.html#a7f36ca4ee7ec8e6b036463cdfb4f8e37',1,'error.h']]], ['err_5f22',['ERR_22',['../error_8h.html#a765e766c66b052360a0f0ef2b108d418',1,'error.h']]], ['err_5f23',['ERR_23',['../error_8h.html#afe7dc0131b0e477c85ce6f1ae81e583e',1,'error.h']]], ['err_5f24',['ERR_24',['../error_8h.html#a89111005bd52f88a676e395c2dc5b595',1,'error.h']]], ['err_5f25',['ERR_25',['../error_8h.html#acb0053735b7712b0f7fe1b568879826e',1,'error.h']]], ['err_5f26',['ERR_26',['../error_8h.html#a402e8f8ce9e0d5f50415d6e7f9234f89',1,'error.h']]], ['err_5f27',['ERR_27',['../error_8h.html#a779a2cfcbc19b315d894998e3806f38a',1,'error.h']]], ['err_5f28',['ERR_28',['../error_8h.html#aa4698896e1be73384ab032d4f6e5dd56',1,'error.h']]], ['err_5f29',['ERR_29',['../error_8h.html#a0ae86bfa2a5b1023325ab803195e26f1',1,'error.h']]], ['err_5f3',['ERR_3',['../error_8h.html#ab90bfbd2a8eb7519c0d0dc5098b9a281',1,'error.h']]], ['err_5f30',['ERR_30',['../error_8h.html#a9ad2467e024cf16be24d8571cea85092',1,'error.h']]], ['err_5f31',['ERR_31',['../error_8h.html#aee8ef3aac4cae8198c2a81433b536966',1,'error.h']]], ['err_5f32',['ERR_32',['../error_8h.html#aad40aa9441ad40db7654ad648667113b',1,'error.h']]], ['err_5f4',['ERR_4',['../error_8h.html#a76e4c62cff81f41c203a1055c05f224d',1,'error.h']]], ['err_5f5',['ERR_5',['../error_8h.html#a8d7a9415f9f39dcab0fd998d1b6abd32',1,'error.h']]], ['err_5f6',['ERR_6',['../error_8h.html#a787a962fcf3e7d2fe874c605cf0b97d7',1,'error.h']]], ['err_5f7',['ERR_7',['../error_8h.html#a8bba8a97454ca8c09e04e8a9c88ba6e6',1,'error.h']]], ['err_5f8',['ERR_8',['../error_8h.html#a45f5fb50712d5336e0b90ecb11b51383',1,'error.h']]], ['err_5f9',['ERR_9',['../error_8h.html#a1c2d6b2d90865a8010ddb14268662072',1,'error.h']]], ['error',['error',['../group___calls_malloc.html#ga600ac89163a3ee4d9e17288546b1ceed',1,'error(const char *errMessage):&#160;print.c'],['../group___calls_malloc.html#ga600ac89163a3ee4d9e17288546b1ceed',1,'error(const char *errMessage):&#160;print.c']]], ['error_2eh',['error.h',['../error_8h.html',1,'']]], ['error_5fmsg',['ERROR_MSG',['../group___calls_malloc.html#ga53cf0ce013d4c7336b4ff71a360cf89a',1,'error.h']]], ['error_5fstate',['ERROR_STATE',['../error_8h.html#a60db3d3e5c5fb314c0d698922d0b7124',1,'error.h']]], ['error_5fthrown',['ERROR_THROWN',['../error_8h.html#a0099faec25b2b4649490d7f562ade34e',1,'error.h']]], ['exp',['exp',['../math_8h.html#a9b5b75b78eff58c7f376e3ce51e9fdfd',1,'math.h']]], ['exp_5ffptr',['EXP_FPTR',['../native__functions__102_8h.html#aee9ec78d07d65bcaddf62698b64ea774',1,'native_functions_102.h']]] ];
sherman5/MeleeModdingLibrary
docs/search/all_5.js
JavaScript
gpl-3.0
4,177
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general de un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos valores de atributo para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("ConsoleExample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleExample")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde // COM, establezca el atributo ComVisible en true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. [assembly: Guid("7250d53b-80c3-406c-ae2d-edd214b8e0db")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o utilizar los números de compilación y de revisión predeterminados // mediante el carácter '*', como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Adversities/Nutdeep
ConsoleExample/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,535
#include <Interface/Colors.hpp> #include <cstdlib> // strtol() bool Colors::hasColors = false; bool Colors::init() { if (has_colors() != TRUE) /* ncurses BOOL */ { Colors::hasColors = false; return false; } Colors::hasColors = true; start_color(); // This is a big hack to initialize all 64 // possible color pairs in ncurses. // // The thing is, all colors are between // COLOR_BLACK and COLOR_WHITE. // Since I've set a large number of enums covering // all possibilities, I can do it all in a for loop. // Check 'man init_pair' for more details. // // Here's the internal value of colors, // taken straight from <curses.h>: // // #define COLOR_BLACK 0 // #define COLOR_RED 1 // #define COLOR_GREEN 2 // #define COLOR_YELLOW 3 // #define COLOR_BLUE 4 // #define COLOR_MAGENTA 5 // #define COLOR_CYAN 6 // #define COLOR_WHITE 7 // int i, j, k = 1; for (i = COLOR_BLACK; i <= COLOR_WHITE; i++) { for (j = COLOR_BLACK; j <= COLOR_WHITE; j++) { init_pair(k, i, j); k++; } } // Besides the normal color pairs, we can use // whatever colors the user has currently set to // their terminal. // It looks more "natural". // // So COLOR_PAIR(-1, -1) is the default foreground // and background. // // Let's do it if the current terminal supports it. if (use_default_colors() != ERR) { // default background init_pair(64, COLOR_BLACK, COLOR_DEFAULT); init_pair(65, COLOR_RED, COLOR_DEFAULT); init_pair(66, COLOR_GREEN, COLOR_DEFAULT); init_pair(67, COLOR_YELLOW, COLOR_DEFAULT); init_pair(68, COLOR_BLUE, COLOR_DEFAULT); init_pair(69, COLOR_MAGENTA, COLOR_DEFAULT); init_pair(70, COLOR_CYAN, COLOR_DEFAULT); init_pair(71, COLOR_WHITE, COLOR_DEFAULT); } return true; } Color Colors::rgb(short r, short g, short b) { if (can_change_color() == FALSE) return 0; if (COLORS < 256) return 0; static int color_no = 8; color_no++; if (color_no >= COLORS) color_no = 8; // init_color receives values from 0 to 1000 int expand = 1000/255; init_color((color_no - 1), r*expand, g*expand, b*expand); return (color_no - 1); } Color Colors::hex(std::string hex) { if (hex[0] != '#') return 0; // sorry if (hex.size() != 7) return 0; // #RRGGBB format char col[3]; col[2] = '\0'; col[0] = hex[1]; col[1] = hex[2]; long r = strtol(col, NULL, 16); col[0] = hex[3]; col[1] = hex[4]; long g = strtol(col, NULL, 16); col[0] = hex[5]; col[1] = hex[6]; long b = strtol(col, NULL, 16); return Colors::rgb(r, g, b); } ColorPair Colors::pair(Color foreground, Color background, bool is_bold) { // Basic nCurses colors if ((foreground < 8) && (background < 8)) { if (background == COLOR_DEFAULT) { if (is_bold) return COLOR_PAIR(64 + foreground) | A_BOLD; else return COLOR_PAIR(64 + foreground); } if (is_bold) return COLOR_PAIR(foreground*8 + background + 1) | A_BOLD; else return COLOR_PAIR(foreground*8 + background + 1); } if (COLORS < 256) { if (is_bold) return COLOR_PAIR(0) | A_BOLD; else return COLOR_PAIR(0); } // Will create color pair // (above the 64 regular ones plus 12 default = 72) static int color_pair_no = 72; color_pair_no++; if (color_pair_no >= COLOR_PAIRS) color_pair_no = 72; init_pair((color_pair_no - 1), foreground, background); if (is_bold) return COLOR_PAIR(color_pair_no - 1) | A_BOLD; else return COLOR_PAIR(color_pair_no - 1); } Color Colors::fromString(std::string str) { if (str.empty()) return 255; if (str == "default") return COLOR_DEFAULT; if (str == "black") return COLOR_BLACK; if (str == "red") return COLOR_RED; if (str == "green") return COLOR_GREEN; if (str == "yellow") return COLOR_YELLOW; if (str == "blue") return COLOR_BLUE; if (str == "magenta") return COLOR_MAGENTA; if (str == "cyan") return COLOR_CYAN; if (str == "white") return COLOR_WHITE; // keep in mind this error code return 255; } ColorPair Colors::pairFromString(std::string foreground, std::string background, bool is_bold) { if (foreground.empty() || background.empty()) return 255; short f = Colors::fromString(foreground); short b = Colors::fromString(background); return Colors::pair(f, b, is_bold); } void Colors::activate(WINDOW* window, Color foreground, Color background) { Colors::pairActivate(window, Colors::pair(foreground, background)); } void Colors::pairActivate(WINDOW* window, ColorPair color) { wattrset(window, color); }
DovydasA/nsnake
src/Interface/Colors.cpp
C++
gpl-3.0
4,494
#ifndef QUAN_META_NUMBITS_HPP_INCLUDED #define QUAN_META_NUMBITS_HPP_INCLUDED /* Copyright (c) 2003-2014 Andy Little. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses./ */ #ifndef __AVR__ #include <climits> #else #include <limits.h> #endif namespace quan { namespace meta{ template <typename T> struct numbits{ static const int value = sizeof(T) * CHAR_BIT; }; }} #endif // QUAN_META_NUMBITS_HPP_INCLUDED
andrewfernie/quan-trunk
quan/meta/numbits.hpp
C++
gpl-3.0
1,000
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SymbolDisplayTests : CSharpTestBase { [Fact] public void TestClassNameOnlySimple() { var text = "class A {}"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("A", 0).Single(); var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly); TestSymbolDescription( text, findSymbol, format, "A", SymbolDisplayPartKind.ClassName); } [Fact] public void TestClassNameOnlyComplex() { var text = @" namespace N1 { namespace N2.N3 { class C1 { class C2 {} } } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetNestedNamespace("N1"). GetNestedNamespace("N2"). GetNestedNamespace("N3"). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(); var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly); TestSymbolDescription( text, findSymbol, format, "C2", SymbolDisplayPartKind.ClassName); } [Fact] public void TestFullyQualifiedFormat() { var text = @" namespace N1 { namespace N2.N3 { class C1 { class C2 {} } } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetNestedNamespace("N1"). GetNestedNamespace("N2"). GetNestedNamespace("N3"). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(); TestSymbolDescription( text, findSymbol, SymbolDisplayFormat.FullyQualifiedFormat, "global::N1.N2.N3.C1.C2", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName); } [Fact] public void TestClassNameAndContainingTypesSimple() { var text = "class A {}"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("A", 0).Single(); var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes); TestSymbolDescription( text, findSymbol, format, "A", SymbolDisplayPartKind.ClassName); } [Fact] public void TestClassNameAndContainingTypesComplex() { var text = @" namespace N1 { namespace N2.N3 { class C1 { class C2 {} } } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetNestedNamespace("N1"). GetNestedNamespace("N2"). GetNestedNamespace("N3"). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(); var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes); TestSymbolDescription( text, findSymbol, format, "C1.C2", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName); } [Fact] public void TestMethodNameOnlySimple() { var text = @" class A { void M() {} } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("A", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat(); TestSymbolDescription( text, findSymbol, format, "M", SymbolDisplayPartKind.MethodName); } [Fact] public void TestMethodNameOnlyComplex() { var text = @" namespace N1 { namespace N2.N3 { class C1 { class C2 { public static int[] M(int? x, C1 c) {} } } } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetNestedNamespace("N1"). GetNestedNamespace("N2"). GetNestedNamespace("N3"). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat(); TestSymbolDescription( text, findSymbol, format, "M", SymbolDisplayPartKind.MethodName); } [Fact] public void TestMethodAndParamsSimple() { var text = @" class A { void M() {} } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("A", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "private void M()", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestMethodAndParamsComplex() { var text = @" namespace N1 { namespace N2.N3 { class C1 { class C2 { public static int[] M(int? x, C1 c) {} } } } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetNestedNamespace("N1"). GetNestedNamespace("N2"). GetNestedNamespace("N3"). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "public static int[] M(int? x, C1 c)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, //M SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //x SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, //C1 SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //c SymbolDisplayPartKind.Punctuation); } [Fact] public void TestExtensionMethodAsStatic() { var text = @" class C1<T> { } class C2 { public static TSource M<TSource>(this C1<TSource> source, int index) {} } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C2").Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "public static TSource C2.M<TSource>(this C1<TSource> source, int index)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, //TSource SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, //C2 SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.MethodName, //M SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, //TSource SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, //C1 SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, //TSource SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //source SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //index SymbolDisplayPartKind.Punctuation); } [Fact] public void TestExtensionMethodAsInstance() { var text = @" class C1<T> { } class C2 { public static TSource M<TSource>(this C1<TSource> source, int index) {} } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C2").Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( extensionMethodStyle: SymbolDisplayExtensionMethodStyle.InstanceMethod, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "public static TSource C1<TSource>.M<TSource>(int index)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, //TSource SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, //C1 SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, //TSource SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.MethodName, //M SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, //TSource SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //index SymbolDisplayPartKind.Punctuation); } [Fact] public void TestNullParameters() { var text = @" class A { int[][,][,,] f; } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("A", 0).Single(). GetMembers("f").Single(); SymbolDisplayFormat format = null; TestSymbolDescription( text, findSymbol, format, "A.f", SymbolDisplayPartKind.ClassName, //A SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName); //f } [Fact] public void TestArrayRank() { var text = @" class A { int[][,][,,] f; } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("A", 0).Single(). GetMembers("f").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "int[][,][,,] f", SymbolDisplayPartKind.Keyword, //int SymbolDisplayPartKind.Punctuation, //[ SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, //[ SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, //[ SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName); //f } [Fact] public void TestOptionalParameters_Bool() { var text = @" using System.Runtime.InteropServices; class C { void F([Optional]bool arg) { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("F").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "void F(bool arg)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, // F SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // arg SymbolDisplayPartKind.Punctuation); } [Fact] public void TestOptionalParameters_String() { var text = @" class C { void F(string s = ""f\t\r\noo"") { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("F").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, @"void F(string s = ""f\t\r\noo"")", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, // F SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // s SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, // = SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StringLiteral, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestOptionalParameters_ReferenceType() { var text = @" using System.Runtime.InteropServices; class C { void F([Optional]C arg) { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("F").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "void F(C arg)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, // F SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // arg SymbolDisplayPartKind.Punctuation); } [Fact] public void TestOptionalParameters_Constrained_Class() { var text = @" using System.Runtime.InteropServices; class C { void F<T>([Optional]T arg) where T : class { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("F").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "void F(T arg)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, // F SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // arg SymbolDisplayPartKind.Punctuation); } [Fact] public void TestOptionalParameters_Constrained_Struct() { var text = @" using System.Runtime.InteropServices; class C { void F<T>([Optional]T arg) where T : struct { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("F").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "void F(T arg)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, // F SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // arg SymbolDisplayPartKind.Punctuation); } [Fact] public void TestOptionalParameters_Unconstrained() { var text = @" using System.Runtime.InteropServices; class C { void F<T>([Optional]T arg) { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("F").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "void F(T arg)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, // F SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // arg SymbolDisplayPartKind.Punctuation); } [Fact] public void TestOptionalParameters_ArrayAndType() { var text = @" using System.Runtime.InteropServices; class C { void F<T>(int a, [Optional]double[] arg, int b, [Optional]System.Type t) { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("F").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "void F(int a, double[] arg, int b, Type t)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, // F SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, // int SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // a SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, // double SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // arg SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, // int SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // b SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, // Type SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // t SymbolDisplayPartKind.Punctuation); } [Fact] public void TestEscapeKeywordIdentifiers() { var text = @" class @true { @true @false(@true @true, bool @bool = true) { return @true; } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("true", 0).Single(). GetMembers("false").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "@true @false(@true @true, bool @bool = true)", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, //@false SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //@true SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //@bool SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestNoEscapeKeywordIdentifiers() { var text = @" class @true { @true @false(@true @true, bool @bool = true) { return @true; } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("true", 0).Single(). GetMembers("false").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "true false(true true, bool bool = true)", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, // @false SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // @true SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, // @bool SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestExplicitMethodImplNameOnly() { var text = @" interface I { void M(); } class C : I { void I.M() { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("I.M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.None); TestSymbolDescription( text, findSymbol, format, "M", SymbolDisplayPartKind.MethodName); //M } [Fact] public void TestExplicitMethodImplNameAndInterface() { var text = @" interface I { void M(); } class C : I { void I.M() { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("I.M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface); TestSymbolDescription( text, findSymbol, format, "I.M", SymbolDisplayPartKind.InterfaceName, //I SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.MethodName); //M } [Fact] public void TestExplicitMethodImplNameAndInterfaceAndType() { var text = @" interface I { void M(); } class C : I { void I.M() { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("I.M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType); TestSymbolDescription( text, findSymbol, format, "C.I.M", SymbolDisplayPartKind.ClassName, //C SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.InterfaceName, //I SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.MethodName); //M } [Fact] public void TestGlobalNamespaceCode() { var text = @" class C { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(); var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included); TestSymbolDescription( text, findSymbol, format, "global::C", SymbolDisplayPartKind.Keyword, //global SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName); //C } [Fact] public void TestGlobalNamespaceHumanReadable() { var text = @" class C { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global; var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included); TestSymbolDescription( text, findSymbol, format, "<global namespace>", SymbolDisplayPartKind.Text); } [Fact] public void TestSpecialTypes() { var text = @" class C { int f; } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("f").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "int f", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName); } [Fact] public void TestArrayAsterisks() { var text = @" class C { int[][,][,,] f; } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("f").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays); TestSymbolDescription( text, findSymbol, format, "Int32[][*,*][*,*,*] f", SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName); } [Fact] public void TestMetadataMethodNames() { var text = @" class C { C() { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers(".ctor").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames); TestSymbolDescription( text, findSymbol, format, ".ctor", SymbolDisplayPartKind.MethodName); } [Fact] public void TestArityForGenericTypes() { var text = @" class C<T, U, V> { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 3).Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes); TestSymbolDescription( text, findSymbol, format, "C`3", SymbolDisplayPartKind.ClassName, InternalSymbolDisplayPartKind.Arity); } [Fact] public void TestGenericTypeParameters() { var text = @" class C<in T, out U, V> { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 3).Single(); var format = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters); TestSymbolDescription( text, findSymbol, format, "C<T, U, V>", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestGenericTypeParametersAndVariance() { var text = @" class C<in T, out U, V> { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 3).Single(); var format = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); TestSymbolDescription( text, findSymbol, format, "C<in T, out U, V>", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestGenericTypeConstraints() { var text = @" class C<T> where T : C<T> { } "; Func<NamespaceSymbol, Symbol> findType = global => global.GetMember<NamedTypeSymbol>("C"); Func<NamespaceSymbol, Symbol> findTypeParameter = global => global.GetMember<NamedTypeSymbol>("C").TypeParameters.Single(); var format = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints); TestSymbolDescription(text, findType, format, "C<T> where T : C<T>", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation); TestSymbolDescription(text, findTypeParameter, format, "T", SymbolDisplayPartKind.TypeParameterName); } [Fact] public void TestGenericMethodParameters() { var text = @" class C { void M<in T, out U, V>() { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters); TestSymbolDescription( text, findSymbol, format, "M<T, U, V>", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestGenericMethodParametersAndVariance() { var text = @" class C { void M<in T, out U, V>() { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance); TestSymbolDescription( text, findSymbol, format, "M<T, U, V>", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestGenericMethodConstraints() { var text = @" class C<T> { void M<U, V>() where V : class, U, T {} }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M"); var format = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints); TestSymbolDescription( text, findSymbol, format, "M<U, V> where V : class, U, T", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.TypeParameterName); } [Fact] public void TestMemberMethodNone() { var text = @" class C { void M(int p) { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.None); TestSymbolDescription( text, findSymbol, format, "M", SymbolDisplayPartKind.MethodName); } [Fact] public void TestMemberMethodAll() { var text = @" class C { void M(int p) { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType); TestSymbolDescription( text, findSymbol, format, "private void C.M()", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestMemberFieldNone() { var text = @" class C { int f; } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("f").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.None); TestSymbolDescription( text, findSymbol, format, "f", SymbolDisplayPartKind.FieldName); } [Fact] public void TestMemberFieldAll() { var text = @"class C { int f; }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("f").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType); TestSymbolDescription( text, findSymbol, format, "private Int32 C.f", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName); } [Fact] public void TestMemberPropertyNone() { var text = @" class C { int P { get; } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("P").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.None); TestSymbolDescription( text, findSymbol, format, "P", SymbolDisplayPartKind.PropertyName); } [Fact] public void TestMemberPropertyAll() { var text = @" class C { int P { get; } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("P").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType); TestSymbolDescription( text, findSymbol, format, "private Int32 C.P", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.PropertyName); } [Fact] public void TestMemberPropertyGetSet() { var text = @" class C { int P { get; } object Q { set; } object R { get { return null; } set { } } } "; var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor); TestSymbolDescription( text, global => global.GetTypeMembers("C", 0).Single().GetMembers("P").Single(), format, "Int32 P { get; }", SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation); TestSymbolDescription( text, global => global.GetTypeMembers("C", 0).Single().GetMembers("Q").Single(), format, "Object Q { set; }", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation); TestSymbolDescription( text, global => global.GetTypeMembers("C", 0).Single().GetMembers("R").Single(), format, "Object R { get; set; }", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestPropertyGetAccessor() { var text = @" class C { int P { get; set; } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("get_P").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType); TestSymbolDescription( text, findSymbol, format, "private Int32 C.P.get", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword); } [Fact] public void TestPropertySetAccessor() { var text = @" class C { int P { get; set; } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("set_P").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType); TestSymbolDescription( text, findSymbol, format, "private void C.P.set", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.PropertyName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword); } [Fact] public void TestMemberEventAll() { var text = @" class C { event System.Action E; event System.Action F { add { } remove { } } } "; Func<NamespaceSymbol, Symbol> findSymbol1 = global => global.GetMember<NamedTypeSymbol>("C"). GetMembers("E").Where(m => m.Kind == SymbolKind.Event).Single(); Func<NamespaceSymbol, Symbol> findSymbol2 = global => global.GetMember<NamedTypeSymbol>("C"). GetMember<EventSymbol>("F"); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType); TestSymbolDescription( text, findSymbol1, format, "private Action C.E", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.EventName); TestSymbolDescription( text, findSymbol2, format, "private Action C.F", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.EventName); } [Fact] public void TestMemberEventAddRemove() { var text = @" class C { event System.Action E; event System.Action F { add { } remove { } } } "; Func<NamespaceSymbol, Symbol> findSymbol1 = global => global.GetMember<NamedTypeSymbol>("C"). GetMembers("E").Where(m => m.Kind == SymbolKind.Event).Single(); Func<NamespaceSymbol, Symbol> findSymbol2 = global => global.GetMember<NamedTypeSymbol>("C"). GetMember<EventSymbol>("F"); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeType, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor); // Does not affect events (did before rename). TestSymbolDescription( text, findSymbol1, format, "Action E", SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EventName); TestSymbolDescription( text, findSymbol2, format, "Action F", SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EventName); } [Fact] public void TestEventAddAccessor() { var text = @" class C { event System.Action E { add { } remove { } } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetMember<NamedTypeSymbol>("C"). GetMembers("add_E").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType); TestSymbolDescription( text, findSymbol, format, "private void C.E.add", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.EventName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword); } [Fact] public void TestEventRemoveAccessor() { var text = @" class C { event System.Action E { add { } remove { } } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetMember<NamedTypeSymbol>("C"). GetMembers("remove_E").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType); TestSymbolDescription( text, findSymbol, format, "private void C.E.remove", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.EventName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword); } [Fact] public void TestParameterMethodNone() { var text = @" static class C { static void M(this object obj, ref short s, int i = 1) { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.None); TestSymbolDescription( text, findSymbol, format, "M()", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestMethodReturnType1() { var text = @" static class C { static int M() { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType); TestSymbolDescription( text, findSymbol, format, "System.Int32 M()", SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestMethodReturnType2() { var text = @" static class C { static void M() { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType); TestSymbolDescription( text, findSymbol, format, "void M()", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestParameterMethodNameTypeModifiers() { var text = @" class C { void M(ref short s, int i, params string[] args) { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName); TestSymbolDescription( text, findSymbol, format, "M(ref Int16 s, Int32 i, params String[] args)", SymbolDisplayPartKind.MethodName, //M SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //s SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //i SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //args SymbolDisplayPartKind.Punctuation); } [Fact()] public void TestParameterMethodNameAll() { var text = @" static class C { static void M(this object self, ref short s, int i = 1, params string[] args) { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeDefaultValue); TestSymbolDescription( text, findSymbol, format, "M(this Object self, ref Int16 s, Int32 i = 1, params String[] args)", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //self SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //s SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //i SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //args SymbolDisplayPartKind.Punctuation); } [Fact] public void TestOptionalParameterBrackets() { var text = @" class C { void M(int i = 0) { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("M").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeOptionalBrackets); TestSymbolDescription( text, findSymbol, format, "M([Int32 i])", SymbolDisplayPartKind.MethodName, //M SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, //i SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation); } /// <summary> /// "public" and "abstract" should not be included for interface members. /// </summary> [Fact] public void TestInterfaceMembers() { var text = @" interface I { int P { get; } object F(); } abstract class C { public abstract object F(); interface I { void M(); } }"; var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, global => global.GetTypeMembers("I", 0).Single().GetMembers("P").Single(), format, "int P { get; }"); TestSymbolDescription( text, global => global.GetTypeMembers("I", 0).Single().GetMembers("F").Single(), format, "object F()"); TestSymbolDescription( text, global => global.GetTypeMembers("C", 0).Single().GetMembers("F").Single(), format, "public abstract object F()"); TestSymbolDescription( text, global => global.GetTypeMembers("C", 0).Single().GetTypeMembers("I", 0).Single().GetMembers("M").Single(), format, "void M()"); } [WorkItem(537447)] [Fact] public void TestBug2239() { var text = @" public class GC1<T> {} public class X : GC1<BOGUS> {} "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("X", 0).Single(). BaseType; var format = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters); TestSymbolDescription( text, findSymbol, format, "GC1<BOGUS>", SymbolDisplayPartKind.ClassName, //GC1 SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ErrorTypeName, //BOGUS SymbolDisplayPartKind.Punctuation); } [Fact] public void TestAlias1() { var text = @" using Foo = N1.N2.N3; namespace N1 { namespace N2.N3 { class C1 { class C2 {} } } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetNestedNamespace("N1"). GetNestedNamespace("N2"). GetNestedNamespace("N3"). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(); var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); TestSymbolDescription( text, findSymbol, format, "Foo.C1.C2", text.IndexOf("namespace"), true, SymbolDisplayPartKind.AliasName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName); } [Fact] public void TestAlias2() { var text = @" using Foo = N1.N2.N3.C1; namespace N1 { namespace N2.N3 { class C1 { class C2 {} } } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetNestedNamespace("N1"). GetNestedNamespace("N2"). GetNestedNamespace("N3"). GetTypeMembers("C1").Single(). GetTypeMembers("C2").Single(); var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); TestSymbolDescription( text, findSymbol, format, "Foo.C2", text.IndexOf("namespace"), true, SymbolDisplayPartKind.AliasName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName); } [Fact] public void TestAlias3() { var text = @" using Foo = N1.C1; namespace N1 { class Foo { } class C1 { } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetNestedNamespace("N1"). GetTypeMembers("C1").Single(); var format = SymbolDisplayFormat.MinimallyQualifiedFormat; TestSymbolDescription( text, findSymbol, format, "C1", text.IndexOf("class Foo"), true, SymbolDisplayPartKind.ClassName); } [Fact] public void TestMinimalNamespace1() { var text = @" namespace N1 { namespace N2 { namespace N3 { class C1 { class C2 {} } } } } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetNestedNamespace("N1"). GetNestedNamespace("N2"). GetNestedNamespace("N3"); var format = new SymbolDisplayFormat(); TestSymbolDescription(text, findSymbol, format, "N1.N2.N3", text.IndexOf("N1"), true, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NamespaceName); TestSymbolDescription(text, findSymbol, format, "N2.N3", text.IndexOf("N2"), true, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NamespaceName); TestSymbolDescription(text, findSymbol, format, "N3", text.IndexOf("N3"), true, SymbolDisplayPartKind.NamespaceName); TestSymbolDescription(text, findSymbol, format, "N3", text.IndexOf("C1"), true, SymbolDisplayPartKind.NamespaceName); TestSymbolDescription(text, findSymbol, format, "N3", text.IndexOf("C2"), true, SymbolDisplayPartKind.NamespaceName); } [Fact] public void TestRemoveAttributeSuffix1() { var text = @" class class1Attribute : System.Attribute { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("class1Attribute").Single(); TestSymbolDescription(text, findSymbol, new SymbolDisplayFormat(), "class1Attribute", SymbolDisplayPartKind.ClassName); TestSymbolDescription(text, findSymbol, new SymbolDisplayFormat(miscellaneousOptions: SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "class1", 0, true, SymbolDisplayPartKind.ClassName); } [Fact] public void TestRemoveAttributeSuffix2() { var text = @" class classAttribute : System.Attribute { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("classAttribute").Single(); TestSymbolDescription(text, findSymbol, new SymbolDisplayFormat(), "classAttribute", SymbolDisplayPartKind.ClassName); TestSymbolDescription(text, findSymbol, new SymbolDisplayFormat(miscellaneousOptions: SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "classAttribute", SymbolDisplayPartKind.ClassName); } [Fact] public void TestRemoveAttributeSuffix3() { var text = @" class class1Attribute { } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("class1Attribute").Single(); TestSymbolDescription(text, findSymbol, new SymbolDisplayFormat(), "class1Attribute", SymbolDisplayPartKind.ClassName); TestSymbolDescription(text, findSymbol, new SymbolDisplayFormat(miscellaneousOptions: SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix), "class1Attribute", SymbolDisplayPartKind.ClassName); } [Fact] public void TestMinimalClass1() { var text = @" using System.Collections.Generic; class C1 { private System.Collections.Generic.IDictionary<System.Collections.Generic.IList<System.Int32>, System.String> foo; } "; Func<NamespaceSymbol, Symbol> findSymbol = global => ((FieldSymbol)global.GetTypeMembers("C1").Single().GetMembers("foo").Single()).Type; var format = SymbolDisplayFormat.MinimallyQualifiedFormat; TestSymbolDescription(text, findSymbol, format, "IDictionary<IList<int>, string>", text.IndexOf("foo"), true, SymbolDisplayPartKind.InterfaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.InterfaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestMethodCustomModifierPositions() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[] { TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll, TestReferences.NetFx.v4_0_21006.mscorlib }); var globalNamespace = assemblies[0].GlobalNamespace; var @class = globalNamespace.GetMember<NamedTypeSymbol>("MethodCustomModifierCombinations"); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers); Verify(@class.GetMember<MethodSymbol>("Method1111").ToDisplayParts(format), "int modopt(IsConst) [] modopt(IsConst) Method1111(int modopt(IsConst) [] modopt(IsConst) a)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation); Verify(@class.GetMember<MethodSymbol>("Method1000").ToDisplayParts(format), "int modopt(IsConst) [] Method1000(int[] a)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation); Verify(@class.GetMember<MethodSymbol>("Method0100").ToDisplayParts(format), "int[] modopt(IsConst) Method0100(int[] a)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation); Verify(@class.GetMember<MethodSymbol>("Method0010").ToDisplayParts(format), "int[] Method0010(int modopt(IsConst) [] a)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation); Verify(@class.GetMember<MethodSymbol>("Method0001").ToDisplayParts(format), "int[] Method0001(int[] modopt(IsConst) a)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation); Verify(@class.GetMember<MethodSymbol>("Method0000").ToDisplayParts(format), "int[] Method0000(int[] a)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestPropertyCustomModifierPositions() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[] { TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll, TestReferences.NetFx.v4_0_21006.mscorlib }); var globalNamespace = assemblies[0].GlobalNamespace; var @class = globalNamespace.GetMember<NamedTypeSymbol>("PropertyCustomModifierCombinations"); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers); Verify(@class.GetMember<PropertySymbol>("Property11").ToDisplayParts(format), "int modopt(IsConst) [] modopt(IsConst) Property11", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName); Verify(@class.GetMember<PropertySymbol>("Property10").ToDisplayParts(format), "int modopt(IsConst) [] Property10", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName); Verify(@class.GetMember<PropertySymbol>("Property01").ToDisplayParts(format), "int[] modopt(IsConst) Property01", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName); Verify(@class.GetMember<PropertySymbol>("Property00").ToDisplayParts(format), "int[] Property00", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.PropertyName); } [Fact] public void TestFieldCustomModifierPositions() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[] { TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll, TestReferences.NetFx.v4_0_21006.mscorlib }); var globalNamespace = assemblies[0].GlobalNamespace; var @class = globalNamespace.GetMember<NamedTypeSymbol>("FieldCustomModifierCombinations"); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers); Verify(@class.GetMember<FieldSymbol>("field11").ToDisplayParts(format), "int modopt(IsConst) [] modopt(IsConst) field11", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName); Verify(@class.GetMember<FieldSymbol>("field10").ToDisplayParts(format), "int modopt(IsConst) [] field10", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName); Verify(@class.GetMember<FieldSymbol>("field01").ToDisplayParts(format), "int[] modopt(IsConst) field01", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName); Verify(@class.GetMember<FieldSymbol>("field00").ToDisplayParts(format), "int[] field00", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.FieldName); } [Fact] public void TestMultipleCustomModifier() { var assemblies = MetadataTestHelpers.GetSymbolsForReferences(new[] { TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll, TestReferences.NetFx.v4_0_21006.mscorlib }); var globalNamespace = assemblies[0].GlobalNamespace; var @class = globalNamespace.GetMember<NamedTypeSymbol>("Modifiers"); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers); Verify(@class.GetMember<MethodSymbol>("F3").ToDisplayParts(format), "void F3(int modopt(int) modopt(IsConst) modopt(IsConst) p)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, InternalSymbolDisplayPartKind.Other, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, //modopt SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation); } private static void TestSymbolDescription( string source, Func<NamespaceSymbol, Symbol> findSymbol, SymbolDisplayFormat format, string expectedText, int position, bool minimal, params SymbolDisplayPartKind[] expectedKinds) { var comp = CreateCompilationWithMscorlib(source); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var global = comp.GlobalNamespace; var symbol = findSymbol(global); var description = minimal ? symbol.ToMinimalDisplayParts(model, position, format) : symbol.ToDisplayParts(format); Verify(description, expectedText, expectedKinds); } private static void TestSymbolDescription( string source, Func<NamespaceSymbol, Symbol> findSymbol, SymbolDisplayFormat format, string expectedText, params SymbolDisplayPartKind[] expectedKinds) { var comp = CreateCompilationWithMscorlib(source); var global = comp.GlobalNamespace; var symbol = findSymbol(global); var description = symbol.ToDisplayParts(format); Verify(description, expectedText, expectedKinds); } private static void Verify(ImmutableArray<SymbolDisplayPart> actualParts, string expectedText, params SymbolDisplayPartKind[] expectedKinds) { Assert.Equal(expectedText, actualParts.ToDisplayString()); if (expectedKinds.Length > 0) { for (int i = 0; i < Math.Min(expectedKinds.Length, actualParts.Length); i++) { Assert.Equal(expectedKinds[i], actualParts[i].Kind); } Assert.Equal(expectedKinds.Length, actualParts.Length); } } [Fact] public void DelegateStyleRecursive() { var text = "public delegate void D(D param);"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("D", 0).Single(); var format = new SymbolDisplayFormat(globalNamespaceStyle: SymbolDisplayFormat.CSharpErrorMessageFormat.GlobalNamespaceStyle, typeQualificationStyle: SymbolDisplayFormat.CSharpErrorMessageFormat.TypeQualificationStyle, genericsOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.GenericsOptions, memberOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.MemberOptions, parameterOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.ParameterOptions, propertyStyle: SymbolDisplayFormat.CSharpErrorMessageFormat.PropertyStyle, localOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.LocalOptions, kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword, delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.MiscellaneousOptions); TestSymbolDescription( text, findSymbol, format, "delegate void D(D)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Punctuation); format = new SymbolDisplayFormat(parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType, delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions: SymbolDisplayFormat.CSharpErrorMessageFormat.MiscellaneousOptions); TestSymbolDescription( text, findSymbol, format, "void D(D param)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation); } [Fact] public void GlobalNamespace1() { var text = @"public class Test { public class System { public class Action { } } public global::System.Action field; public System.Action field2; }"; Func<NamespaceSymbol, Symbol> findSymbol = global => { var field = global.GetTypeMembers("Test", 0).Single().GetMembers("field").Single() as FieldSymbol; return field.Type; }; var format = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "global::System.Action", text.IndexOf("global::System.Action"), true /* minimal */, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.DelegateName); } [Fact] public void GlobalNamespace2() { var text = @"public class Test { public class System { public class Action { } } public global::System.Action field; public System.Action field2; }"; Func<NamespaceSymbol, Symbol> findSymbol = global => { var field = global.GetTypeMembers("Test", 0).Single().GetMembers("field").Single() as FieldSymbol; return field.Type; }; var format = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "System.Action", text.IndexOf("global::System.Action"), true /* minimal */, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.DelegateName); } [Fact] public void GlobalNamespace3() { var text = @"public class Test { public class System { public class Action { } } public System.Action field2; public global::System.Action field; }"; Func<NamespaceSymbol, Symbol> findSymbol = global => { var field = global.GetTypeMembers("Test", 0).Single().GetMembers("field2").Single() as FieldSymbol; return field.Type; }; var format = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription( text, findSymbol, format, "System.Action", text.IndexOf("System.Action"), true /* minimal */, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName); } [Fact] public void DefaultParameterValues() { var text = @" struct S { void M( int i = 1, string str = ""hello"", object o = null S s = default(S)) { } }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("M"); var format = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription(text, findSymbol, format, @"void S.M(int i = 1, string str = ""hello"", object o = null, S s = default(S))", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral, SymbolDisplayPartKind.Punctuation, //, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StringLiteral, SymbolDisplayPartKind.Punctuation, //, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, //, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, //) SymbolDisplayPartKind.Punctuation); //) } [Fact] public void DefaultParameterValues_TypeParameter() { var text = @" struct S { void M<T>(T t = default(T)) { } }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("M"); var format = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription(text, findSymbol, format, @"void S.M<T>(T t = default(T))", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, //< SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, //> SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.TypeParameterName, SymbolDisplayPartKind.Punctuation, //) SymbolDisplayPartKind.Punctuation); //) } [Fact] public void DefaultParameterValues_Enum() { var text = @" enum E { A = 1, B = 2, C = 5, } struct S { void P(E e = (E)1) { } void Q(E e = (E)3) { } void R(E e = (E)5) { } }"; Func<NamespaceSymbol, Symbol> findSymbol1 = global => global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("P"); Func<NamespaceSymbol, Symbol> findSymbol2 = global => global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("Q"); Func<NamespaceSymbol, Symbol> findSymbol3 = global => global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("R"); var format = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription(text, findSymbol1, format, @"void S.P(E e = E.A)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Punctuation); //) TestSymbolDescription(text, findSymbol2, format, @"void S.Q(E e = (E)3)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, //) SymbolDisplayPartKind.NumericLiteral, SymbolDisplayPartKind.Punctuation); //) TestSymbolDescription(text, findSymbol3, format, @"void S.R(E e = E.C)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Punctuation); //) } [Fact] public void DefaultParameterValues_FlagsEnum() { var text = @" [System.FlagsAttribute] enum E { A = 1, B = 2, C = 5, } struct S { void P(E e = (E)1) { } void Q(E e = (E)3) { } void R(E e = (E)5) { } }"; Func<NamespaceSymbol, Symbol> findSymbol1 = global => global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("P"); Func<NamespaceSymbol, Symbol> findSymbol2 = global => global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("Q"); Func<NamespaceSymbol, Symbol> findSymbol3 = global => global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("R"); var format = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription(text, findSymbol1, format, @"void S.P(E e = E.A)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Punctuation); //) TestSymbolDescription(text, findSymbol2, format, @"void S.Q(E e = E.A | E.B)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //| SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Punctuation); //) TestSymbolDescription(text, findSymbol3, format, @"void S.R(E e = E.C)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Punctuation); } [Fact] public void DefaultParameterValues_NegativeEnum() { var text = @" [System.FlagsAttribute] enum E : sbyte { A = -2, A1 = -2, B = 1, B1 = 1, C = 0, C1 = 0, } struct S { void P(E e = (E)(-2), E f = (E)(-1), E g = (E)0, E h = (E)(-3)) { } }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetMember<NamedTypeSymbol>("S").GetMember<MethodSymbol>("P"); var format = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); TestSymbolDescription(text, findSymbol, format, @"void S.P(E e = E.A, E f = E.A | E.B, E g = E.C, E h = (E)-3)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, //( SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Punctuation, //, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //| SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Punctuation, //, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, //= SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, //. SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Punctuation, //, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, // = SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, // ( SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, // ) SymbolDisplayPartKind.NumericLiteral, SymbolDisplayPartKind.Punctuation); //) } [Fact] public void TestConstantFieldValue() { var text = @"class C { const int f = 1; }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("f").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeConstantValue); TestSymbolDescription( text, findSymbol, format, "private const Int32 C.f = 1", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral); } [Fact] public void TestConstantFieldValue_EnumMember() { var text = @" enum E { A, B, C } class C { const E f = E.B; }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("f").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeConstantValue); TestSymbolDescription( text, findSymbol, format, "private const E C.f = E.B", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName); } [Fact] public void TestConstantFieldValue_EnumMember_Flags() { var text = @" [System.FlagsAttribute] enum E { A = 1, B = 2, C = 4, D = A | B | C } class C { const E f = E.D; }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("C", 0).Single(). GetMembers("f").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeConstantValue); TestSymbolDescription( text, findSymbol, format, "private const E C.f = E.D", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName); } [Fact] public void TestEnumMember() { var text = @"enum E { A, B, C }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("E", 0).Single(). GetMembers("B").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeConstantValue); TestSymbolDescription( text, findSymbol, format, "E.B = 1", SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral); } [Fact] public void TestEnumMember_Flags() { var text = @"[System.FlagsAttribute] enum E { A = 1, B = 2, C = 4, D = A | B | C }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("E", 0).Single(). GetMembers("D").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeConstantValue); TestSymbolDescription( text, findSymbol, format, "E.D = E.A | E.B | E.C", SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName); } [Fact] public void TestEnumMember_FlagsWithoutAttribute() { var text = @"enum E { A = 1, B = 2, C = 4, D = A | B | C }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetTypeMembers("E", 0).Single(). GetMembers("D").Single(); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeConstantValue); TestSymbolDescription( text, findSymbol, format, "E.D = 7", SymbolDisplayPartKind.EnumName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.FieldName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NumericLiteral); } [Fact, WorkItem(545462)] public void DateTimeDefaultParameterValue() { var text = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; class C { static void Foo([Optional][DateTimeConstant(100)] DateTime d) { } }"; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetMember<NamedTypeSymbol>("C"). GetMember<MethodSymbol>("Foo"); var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue); TestSymbolDescription( text, findSymbol, format, "Foo(DateTime d)", SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation); } [Fact, WorkItem(545681)] public void TypeParameterFromMetadata() { var src1 = @" public class LibG<T> { } "; var src2 = @" public class Gen<V> { public void M(LibG<V> p) { } } "; var complib = CreateCompilationWithMscorlib(src1, assemblyName: "Lib"); var compref = new CSharpCompilationReference(complib); var comp1 = CreateCompilationWithMscorlib(src2, references: new MetadataReference[] { compref }, assemblyName: "Comp1"); var mtdata = comp1.EmitToArray(); var mtref = new MetadataImageReference(mtdata); var comp2 = CreateCompilationWithMscorlib("", references: new MetadataReference[] { mtref }, assemblyName: "Comp2"); var tsym1 = comp1.SourceModule.GlobalNamespace.GetMember<NamedTypeSymbol>("Gen"); Assert.NotNull(tsym1); var msym1 = tsym1.GetMember<MethodSymbol>("M"); Assert.NotNull(msym1); Assert.Equal("Gen<V>.M(LibG<V>)", msym1.ToDisplayString()); var tsym2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("Gen"); Assert.NotNull(tsym2); var msym2 = tsym2.GetMember<MethodSymbol>("M"); Assert.NotNull(msym2); Assert.Equal(msym1.ToDisplayString(), msym2.ToDisplayString()); } [Fact, WorkItem(545625)] public void ReverseArrayRankSpecifiers() { var text = @" public class C { C[][,] F; } "; Func<NamespaceSymbol, Symbol> findSymbol = global => global.GetMember<NamedTypeSymbol>("C").GetMember<FieldSymbol>("F").Type; var normalFormat = new SymbolDisplayFormat(); var reverseFormat = new SymbolDisplayFormat( compilerInternalOptions: SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers); TestSymbolDescription( text, findSymbol, normalFormat, "C[][,]", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation); TestSymbolDescription( text, findSymbol, reverseFormat, "C[,][]", SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Punctuation); } [Fact, WorkItem(546638)] public void InvariantCultureNegatives() { var text = @" public class C { void M( sbyte p1 = (sbyte)-1, short p2 = (short)-1, int p3 = (int)-1, long p4 = (long)-1, float p5 = (float)-0.5, double p6 = (double)-0.5, decimal p7 = (decimal)-0.5) { } } "; var oldCulture = Thread.CurrentThread.CurrentCulture; try { Thread.CurrentThread.CurrentCulture = (CultureInfo)oldCulture.Clone(); Thread.CurrentThread.CurrentCulture.NumberFormat.NegativeSign = "~"; Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ","; var compilation = CreateCompilationWithMscorlib(text); compilation.VerifyDiagnostics(); var symbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M"); Assert.Equal("void C.M(" + "[System.SByte p1 = -1], " + "[System.Int16 p2 = -1], " + "[System.Int32 p3 = -1], " + "[System.Int64 p4 = -1], " + "[System.Single p5 = -0.5], " + "[System.Double p6 = -0.5], " + "[System.Decimal p7 = -0.5])", symbol.ToTestDisplayString()); } finally { Thread.CurrentThread.CurrentCulture = oldCulture; } } [Fact] public void TestMethodVB() { var text = @" Class A Public Sub Foo(a As Integer) End Sub End Class"; var format = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); var comp = CreateVisualBasicCompilation("c", text); var a = (ITypeSymbol)comp.GlobalNamespace.GetMembers("A").Single(); var foo = a.GetMembers("Foo").Single(); var parts = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.ToDisplayParts(foo, format); Verify( parts, "public void Foo(int a)", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.MethodName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ParameterName, SymbolDisplayPartKind.Punctuation); } [Fact] public void TestWindowsRuntimeEvent() { var source = @" class C { event System.Action E; } "; var format = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface); var comp = CreateCompilation(source, WinRtRefs, TestOptions.WinMDObj); var eventSymbol = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<EventSymbol>("E"); Assert.True(eventSymbol.IsWindowsRuntimeEvent); Verify( eventSymbol.ToDisplayParts(format), "Action C.E", SymbolDisplayPartKind.DelegateName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.EventName); Verify( eventSymbol.AddMethod.ToDisplayParts(format), "EventRegistrationToken C.E.add", SymbolDisplayPartKind.StructName, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.EventName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword); Verify( eventSymbol.RemoveMethod.ToDisplayParts(format), "void C.E.remove", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.EventName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.Keyword); } [WorkItem(791756)] [Fact] public void KindOptions() { var source = @" namespace N { class C { event System.Action E; } } "; var memberFormat = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword); var typeFormat = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, kindOptions: SymbolDisplayKindOptions.IncludeTypeKeyword); var namespaceFormat = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword); var comp = CreateCompilationWithMscorlib(source); var namespaceSymbol = comp.GlobalNamespace.GetMember<NamespaceSymbol>("N"); var typeSymbol = namespaceSymbol.GetMember<NamedTypeSymbol>("C"); var eventSymbol = typeSymbol.GetMember<EventSymbol>("E"); Verify( namespaceSymbol.ToDisplayParts(memberFormat), "N", SymbolDisplayPartKind.NamespaceName); Verify( namespaceSymbol.ToDisplayParts(typeFormat), "N", SymbolDisplayPartKind.NamespaceName); Verify( namespaceSymbol.ToDisplayParts(namespaceFormat), "namespace N", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName); Verify( typeSymbol.ToDisplayParts(memberFormat), "N.C", SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName); Verify( typeSymbol.ToDisplayParts(typeFormat), "class N.C", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName); Verify( typeSymbol.ToDisplayParts(namespaceFormat), "N.C", SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName); Verify( eventSymbol.ToDisplayParts(memberFormat), "event N.C.E", SymbolDisplayPartKind.Keyword, SymbolDisplayPartKind.Space, SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.EventName); Verify( eventSymbol.ToDisplayParts(typeFormat), "N.C.E", SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.EventName); Verify( eventSymbol.ToDisplayParts(namespaceFormat), "N.C.E", SymbolDisplayPartKind.NamespaceName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.ClassName, SymbolDisplayPartKind.Punctuation, SymbolDisplayPartKind.EventName); } [WorkItem(765287)] [Fact] public void TestVbSymbols() { var vbComp = CreateVisualBasicCompilation(@" Class Outer Class Inner(Of T) End Class Sub M(Of U)() End Sub WriteOnly Property P() As String Set(value) End Set End Property Private F As Integer Event E() Delegate Sub D() Function [Error]() As Missing End Function End Class ", assemblyName: "VB"); var outer = (INamedTypeSymbol)vbComp.GlobalNamespace.GetMembers("Outer").Single(); var type = outer.GetMembers("Inner").Single(); var method = outer.GetMembers("M").Single(); var property = outer.GetMembers("P").Single(); var field = outer.GetMembers("F").Single(); var @event = outer.GetMembers("E").Single(); var @delegate = outer.GetMembers("D").Single(); var error = outer.GetMembers("Error").Single(); Assert.IsNotType<Symbol>(type); Assert.IsNotType<Symbol>(method); Assert.IsNotType<Symbol>(property); Assert.IsNotType<Symbol>(field); Assert.IsNotType<Symbol>(@event); Assert.IsNotType<Symbol>(@delegate); Assert.IsNotType<Symbol>(error); // 1) Looks like C#. // 2) Doesn't blow up. Assert.Equal("Outer.Inner<T>", CSharp.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)); Assert.Equal("void Outer.M<U>()", CSharp.SymbolDisplay.ToDisplayString(method, SymbolDisplayFormat.TestFormat)); Assert.Equal("System.String Outer.P { set; }", CSharp.SymbolDisplay.ToDisplayString(property, SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Int32 Outer.F", CSharp.SymbolDisplay.ToDisplayString(field, SymbolDisplayFormat.TestFormat)); Assert.Equal("event Outer.EEventHandler Outer.E", CSharp.SymbolDisplay.ToDisplayString(@event, SymbolDisplayFormat.TestFormat)); Assert.Equal("Outer.D", CSharp.SymbolDisplay.ToDisplayString(@delegate, SymbolDisplayFormat.TestFormat)); Assert.Equal("Missing Outer.Error()", CSharp.SymbolDisplay.ToDisplayString(error, SymbolDisplayFormat.TestFormat)); } [Fact] public void FormatPrimitive() { // basic tests, more cases are covered by ObjectFormatterTests Assert.Equal("1", SymbolDisplay.FormatPrimitive(1, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("1", SymbolDisplay.FormatPrimitive((uint)1, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("1", SymbolDisplay.FormatPrimitive((byte)1, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("1", SymbolDisplay.FormatPrimitive((sbyte)1, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("1", SymbolDisplay.FormatPrimitive((short)1, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("1", SymbolDisplay.FormatPrimitive((ushort)1, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("1", SymbolDisplay.FormatPrimitive((long)1, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("1", SymbolDisplay.FormatPrimitive((ulong)1, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("x", SymbolDisplay.FormatPrimitive('x', quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("true", SymbolDisplay.FormatPrimitive(true, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("1.5", SymbolDisplay.FormatPrimitive(1.5, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("1.5", SymbolDisplay.FormatPrimitive((float)1.5, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("1.5", SymbolDisplay.FormatPrimitive((decimal)1.5, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("null", SymbolDisplay.FormatPrimitive(null, quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal("abc", SymbolDisplay.FormatPrimitive("abc", quoteStrings: false, useHexadecimalNumbers: false)); Assert.Equal(null, SymbolDisplay.FormatPrimitive(SymbolDisplayFormat.TestFormat, quoteStrings: false, useHexadecimalNumbers: false)); } [WorkItem(879984)] [Fact] public void EnumAmbiguityResolution() { var source = @" using System; class Program { static void M(E1 e1 = (E1)1, E2 e2 = (E2)1) { } } enum E1 { B = 1, A = 1, } [Flags] enum E2 // Identical to E1, but has [Flags] { B = 1, A = 1, } "; var comp = CreateCompilationWithMscorlib(source); var method = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Program").GetMember<MethodSymbol>("M"); var memberFormat = new SymbolDisplayFormat( memberOptions: SymbolDisplayMemberOptions.IncludeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue); Assert.Equal("M(e1 = A, e2 = A)", method.ToDisplayString(memberFormat)); // Alphabetically first candidate chosen for both enums. } } }
BlastarIndia/roslyn
Src/Compilers/CSharp/Test/Symbol/SymbolDisplay/SymbolDisplayTests.cs
C#
gpl-3.0
160,822
# -*- coding: utf-8 -*- require 'helper.rb' module BibTeX class EntryTest < MiniTest::Spec describe 'a new entry' do it "won't be nil" do Entry.new.wont_be_nil end end describe '#add' do it 'preserves BibTeX::Names (and other subclasses of BibTeX::Value)' do e = Entry.new e.add(:author, Names.new(Name.new(:first => 'first_name'))) assert_equal e[:author].class, Names end end describe 'cross-references' do it 'has no cross-reference by default' do assert_equal false, Entry.new.has_cross_reference? end it 'is not cross-referenced by default' do assert_equal false, Entry.new.cross_referenced? Entry.new.cross_referenced_by.must_be_empty end describe 'given a bibliography with cross referenced entries' do before do @bib = Bibliography.parse <<-END @book{a, editor = "A", title = "A"} @incollection{a1, crossref = "a"} @incollection{b1, crossref = "b"} END end describe '#has_cross_reference?' do it 'returns true if the entry has a valid cross-reference' do assert_equal true, @bib['a1'].has_cross_reference? end it 'returns false if the entry has no valid cross-reference' do assert_equal false, @bib['a'].has_cross_reference? assert_equal false, @bib['b1'].has_cross_reference? end end describe '#cross_referenced?' do it 'returns true if the entry is cross-referenced by another entry' do assert_equal true, @bib['a'].cross_referenced? end it 'returns false if the entry is not cross-referenced' do assert_equal false, @bib['a1'].cross_referenced? end end describe '#cross_referenced_by' do it 'returns a list of all entries that cross-reference this entry' do @bib['a'].cross_referenced_by.must_include(@bib['a1']) end it 'returns an empty list if there are no cross-references to this entry' do @bib['a1'].cross_referenced_by.must_be_empty end end describe '#respond_to?' do it 'takes into account the inherited attributes' do @bib['a1'].respond_to?(:title) end end describe 'resolve field values using array accessors #[]' do describe 'when a "title" is set in the entry itself' do before { @bib['a1'].title = 'A1' } it 'returns the title' do @bib['a1'].title.must_be :==, 'A1' end end describe 'when "title" is undefined for the entry but defined in the reference' do it 'returns the referenced title' do @bib['a1'].title.must_be :==, @bib['a'].title end end describe 'when "booktitle" is undefined for the entry but defined in the reference' do before { @bib['a'].booktitle = "A Booktitle" } it 'returns the referenced booktitle' do @bib['a1'].booktitle.must_be :==, @bib['a'].booktitle end end describe 'when "booktitle" is undefined for the entry and the reference but the reference has a "title"' do it "returns the reference's title" do @bib['a1'].booktitle.must_be :==, @bib['a'].title end end it 'does not store referenced values permanently' do refute_nil @bib['a1'].booktitle assert_nil @bib['a1'].fields[:booktitle] end describe '#inherited_fields' do it 'returns an empty list by default' do Entry.new.inherited_fields.must_be_empty end it 'returns an empty list if this entry has no cross-reference' do @bib['a'].inherited_fields.must_be_empty end it 'returns an empty list if this entry has a cross-reference but the reference does not exist in the bibliography' do @bib['b1'].inherited_fields.must_be_empty end it 'returns a list of all fields not set in the field but in the reference' do @bib['a1'].inherited_fields.must_be :==, %w(booktitle editor title) end end describe '#save_inherited_fields' do it 'copies referenced values to the entry' do @bib['a1'].title = 'a1' @bib['a1'].save_inherited_fields @bib['a1'].fields['booktitle'].must_be :==, @bib['a'].title @bib['a1'].fields['title'].wont_be :==, @bib['a'].title end end end end end describe '#names' do it 'returns an empty list by default' do Entry.new.names.must_be :==, [] end it 'returns the author (if set)' do Entry.new(:author => 'A').names.must_be :==, %w{ A } end it 'returns all authors (if set)' do Entry.new(:author => 'A B and C D').parse_names.names.length.must_be :==, 2 end it 'returns the editor (if set)' do Entry.new(:editor => 'A').names.must_be :==, %w{ A } end it 'returns the translator (if set)' do Entry.new(:translator => 'A').names.must_be :==, %w{ A } end end describe 'month conversion' do before do @entry = Entry.new end [%w(jan January), %w(feb February), %w(sep September)].each do |m| it 'should convert english months' do @entry.month = m[1] assert_equal BibTeX::Symbol.new(m[0]), @entry.month.v end end [%w(jan jan), %w(feb feb), %w(sep sep)].each do |m| it 'should convert bibtex abbreviations' do @entry.month = m[1] assert_equal BibTeX::Symbol.new(m[0]), @entry.month.v end end [['jan',1], ['feb',2], ['sep',9]].each do |m| it 'should convert numbers' do @entry.month = m[1] assert_equal BibTeX::Symbol.new(m[0]), @entry.month.v end it 'should convert numbers when parsing' do @entry = Entry.parse("@misc{id, month = #{m[1]}}")[0] assert_equal BibTeX::Symbol.new(m[0]), @entry.month.v end end end describe '#values_at' do it 'returns an empty array by default' do assert_equal [], Entry.new.values_at end it 'returns an empty array when given no arguments' do assert_equal [], Entry.new(:title => 'foo').values_at end it 'returns a nil array if the passed in key is not set' do assert_equal [nil], Entry.new.values_at(:title) end it 'returns an array with the value of the passed in key' do assert_equal ['x'], Entry.new(:title => 'x').values_at(:title) assert_equal ['a', 'b'], Entry.new(:title => 'b', :year => 'a').values_at(:year, :title) end end describe '#digest' do it 'returns an empty string by default' do assert_equal '', Entry.new.digest end it 'includes type and all defined fields' do assert_equal 'book', Entry.new(:type => 'book').digest assert_equal 'book|title:foo', Entry.new(:type => 'book', :title => 'foo').digest end it 'accepts a filter' do assert_equal 'book|year:2012', Entry.new(:type => 'book', :title => 'foo', :year => 2012).digest([:year]) end end describe 'given an entry' do before do @entry = Entry.new do |e| e.type = :book e.key = :key e.title = 'Moby Dick' e.author = 'Herman Melville' e.publisher = 'Penguin' e.address = 'New York' e.month = 'Nov' e.year = 1993 e.parse_names end end it 'supports renaming! of field attributes' do @entry.rename!(:title => :foo) refute @entry.has_field?(:title) assert_equal 'Moby Dick', @entry[:foo] end it 'supports renaming of field attributes' do e = @entry.rename(:title => :foo) assert @entry.has_field?(:title) refute @entry.has_field?(:foo) assert e.has_field?(:foo) refute e.has_field?(:title) assert_equal 'Moby Dick', @entry[:title] assert_equal 'Moby Dick', e[:foo] end it 'supports citeproc export' do e = @entry.to_citeproc assert_equal 'book', e['type'] assert_equal 'New York', e['publisher-place'] assert_equal [1993,11], e['issued']['date-parts'][0] assert_equal 1, e['author'].length assert_equal 'Herman', e['author'][0]['given'] assert_equal 'Melville', e['author'][0]['family'] end describe 'given a filter object or a filter name' do before do @filter = Object.new def @filter.apply (value); value.is_a?(::String) ? value.upcase : value; end class SuffixB < BibTeX::Filter def apply(value) value.is_a?(::String) ? "#{value}b" : value end end end it 'supports arbitrary conversion' do @entry.convert(@filter).title.must_equal 'MOBY DICK' @entry.convert(:suffixb).title.must_equal 'Moby Dickb' end it 'supports multiple filters' do @entry.convert(@filter, :suffixb).title.must_equal 'MOBY DICKb' @entry.convert(:suffixb, @filter).title.must_equal 'MOBY DICKB' end it 'supports arbitrary in-place conversion' do @entry.convert!(@filter).title.must_equal 'MOBY DICK' end it 'supports conditional arbitrary in-place conversion' do @entry.convert!(@filter) { |k,v| k.to_s =~ /publisher/i } assert_equal 'Moby Dick', @entry.title assert_equal 'PENGUIN', @entry.publisher end it 'supports conditional arbitrary conversion' do e = @entry.convert(@filter) { |k,v| k.to_s =~ /publisher/i } assert_equal 'Moby Dick', e.title assert_equal 'PENGUIN', e.publisher assert_equal 'Penguin', @entry.publisher end end describe 'LaTeX filter' do before do @entry.title = 'M\\"{o}by Dick' end describe '#convert' do it 'converts LaTeX umlauts' do @entry.convert(:latex).title.must_be :==, 'Möby Dick' end it 'does not change the original entry' do e = @entry.convert(:latex) e.wont_be :==, @entry e.title.to_s.length.must_be :<, @entry.title.to_s.length end end describe '#convert!' do it 'converts LaTeX umlauts' do @entry.convert!(:latex).title.must_be :==, 'Möby Dick' end it 'changes the original entry in-place' do e = @entry.convert!(:latex) e.must_be :equal?, @entry e.title.to_s.length.must_be :==, @entry.title.to_s.length end end end end describe 'citeproc export' do before do @entry = Entry.new do |e| e.type = :book e.key = :key e.author = 'van Beethoven, Ludwig' e.parse_names end end it 'should use non-dropping-particle by default' do assert_equal 'van', @entry.to_citeproc['author'][0]['non-dropping-particle'] end it 'should accept option to use non-dropping-particle' do assert_equal 'van', @entry.to_citeproc(:particle => 'non-dropping-particle')['author'][0]['non-dropping-particle'] end end def test_simple bib = BibTeX::Bibliography.open(Test.fixtures(:entry), :debug => false) refute_nil(bib) assert_equal(BibTeX::Bibliography, bib.class) assert_equal(4, bib.data.length) assert_equal([BibTeX::Entry], bib.data.map(&:class).uniq) assert_equal('key:0', bib.data[0].key) assert_equal('key:1', bib.data[1].key) assert_equal('foo', bib.data[2].key) assert_equal('book', bib.data[0].type) assert_equal('article', bib.data[1].type) assert_equal('article', bib.data[2].type) assert_equal('Poe, Edgar A.', bib.data[0][:author].to_s) assert_equal('Hawthorne, Nathaniel', bib.data[1][:author].to_s) assert_equal('2003', bib.data[0][:year]) assert_equal('2001', bib.data[1][:year]) assert_equal('American Library', bib.data[0][:publisher]) assert_equal('American Library', bib.data[1][:publisher]) assert_equal('Selected \\emph{Poetry} and `Tales\'', bib.data[0].title) assert_equal('Tales and Sketches', bib.data[1].title) end def test_ghost_methods bib = BibTeX::Bibliography.open(Test.fixtures(:entry), :debug => false) assert_equal 'Poe, Edgar A.', bib[0].author.to_s expected = 'Poe, Edgar Allen' bib.data[0].author = expected assert_equal expected, bib[0].author.to_s end def test_creation_simple entry = BibTeX::Entry.new entry.type = :book entry.key = :raven entry.author = 'Poe, Edgar A.' entry.title = 'The Raven' assert_equal 'book', entry.type assert_equal 'raven', entry.key assert_equal 'Poe, Edgar A.', entry.author assert_equal 'The Raven', entry.title end def test_creation_from_hash entry = BibTeX::Entry.new({ :type => 'book', :key => :raven, :author => 'Poe, Edgar A.', :title => 'The Raven' }) assert_equal 'book', entry.type assert_equal 'raven', entry.key assert_equal 'Poe, Edgar A.', entry.author assert_equal 'The Raven', entry.title end def test_creation_from_block entry = BibTeX::Entry.new do |e| e.type = 'book' e.key = 'raven' e.author = 'Poe, Edgar A.' e.title = 'The Raven' end assert_equal 'book', entry.type assert_equal 'raven', entry.key assert_equal 'Poe, Edgar A.', entry.author assert_equal 'The Raven', entry.title end def test_sorting entries = [] entries << Entry.new({ :type => 'book', :key => 'raven3', :author => 'Poe, Edgar A.', :title => 'The Raven'}) entries << Entry.new({ :type => 'book', :key => 'raven2', :author => 'Poe, Edgar A.', :title => 'The Raven'}) entries << Entry.new({ :type => 'book', :key => 'raven1', :author => 'Poe, Edgar A.', :title => 'The Raven'}) entries << Entry.new({ :type => 'book', :key => 'raven1', :author => 'Poe, Edgar A.', :title => 'The Aven'}) entries.sort! assert_equal ['raven1', 'raven1', 'raven2', 'raven3'], entries.map(&:key) assert_equal ['The Aven', 'The Raven'], entries.map(&:title)[0,2] end describe 'default keys' do before { @e1 = Entry.new(:type => 'book', :author => 'Poe, Edgar A.', :title => 'The Raven', :editor => 'John Hopkins', :year => 1996) @e2 = Entry.new(:type => 'book', :title => 'The Raven', :editor => 'John Hopkins', :year => 1996) @e3 = Entry.new(:type => 'book', :author => 'Poe, Edgar A.', :title => 'The Raven', :editor => 'John Hopkins') } it 'should return "unknown-a" for an empty Entry' do Entry.new.key.must_be :==, 'unknown-a' end it 'should return a key made up of author-year-a if all fields are present' do @e1.key.must_be :==, 'poe1996a' end it 'should return a key made up of editor-year-a if there is no author' do @e2.key.must_be :==, 'john1996a' end it 'should return use the last name if the author/editor names have been parsed' do @e2.parse_names.key.must_be :==, 'hopkins1996a' end it 'skips the year if not present' do @e3.key.must_be :==, 'poe-a' end end describe 'when the entry is added to a Bibliography' do before { @e = Entry.new @bib = Bibliography.new } it 'should register itself with its key' do @bib << @e @bib.entries.keys.must_include @e.key end describe "when there is already an element registered with the entry's key" do before { @bib << Entry.new } it "should find a suitable key" do k = @e.key @bib << @e @bib.entries.keys.must_include @e.key k.wont_be :==, @e.key end end end describe '#meet?' do before { @e = Entry.new } it 'returns true for an empty condition list' do assert @e.meet? [] assert @e.meet? [''] end it 'it returns true when all conditions hold' do refute @e.meet? ['author = Edgar'] @e.author = 'Poe, Edgar A.' refute @e.meet? ['author = Edgar'] refute @e.meet? ['author = Poe, Edgar'] assert @e.meet? ['author = Poe, Edgar A.'] assert @e.meet? ['author ^= Poe'] refute @e.meet? ['author ^= Edgar'] assert @e.meet? ['author ~= Edgar'] assert @e.meet? ['author ~= .'] assert @e.meet? ['author ~= [a-z]*'] assert @e.meet? ['author ^= P\w+'] end end end end
minad/bibtex-ruby
test/bibtex/test_entry.rb
Ruby
gpl-3.0
17,321
using System; using System.ComponentModel; using System.Diagnostics; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Serialization; namespace RDI.NFe2.Business.HWS.SVCAN.Status { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name = "NfeStatusServico2Soap", Namespace = "http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2")] public partial class NfeStatusServico2 : System.Web.Services.Protocols.SoapHttpClientProtocol { private nfeCabecMsg nfeCabecMsgValueField; private System.Threading.SendOrPostCallback nfeStatusServicoNF2OperationCompleted; /// <remarks/> public NfeStatusServico2() { this.Url = "https://hom.svc.fazenda.gov.br/NfeStatusServico2/NfeStatusServico2.asmx"; } public nfeCabecMsg nfeCabecMsgValue { get { return this.nfeCabecMsgValueField; } set { this.nfeCabecMsgValueField = value; } } /// <remarks/> public event nfeStatusServicoNF2CompletedEventHandler nfeStatusServicoNF2Completed; /// <remarks/> [System.Web.Services.Protocols.SoapHeaderAttribute("nfeCabecMsgValue")] [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2/nfeStatusServicoNF2", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Bare)] [return: System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2")] public System.Xml.XmlNode nfeStatusServicoNF2([System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2")] System.Xml.XmlNode nfeDadosMsg) { object[] results = this.Invoke("nfeStatusServicoNF2", new object[] { nfeDadosMsg}); return ((System.Xml.XmlNode)(results[0])); } /// <remarks/> public System.IAsyncResult BeginnfeStatusServicoNF2(System.Xml.XmlNode nfeDadosMsg, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("nfeStatusServicoNF2", new object[] { nfeDadosMsg}, callback, asyncState); } /// <remarks/> public System.Xml.XmlNode EndnfeStatusServicoNF2(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Xml.XmlNode)(results[0])); } /// <remarks/> public void nfeStatusServicoNF2Async(System.Xml.XmlNode nfeDadosMsg) { this.nfeStatusServicoNF2Async(nfeDadosMsg, null); } /// <remarks/> public void nfeStatusServicoNF2Async(System.Xml.XmlNode nfeDadosMsg, object userState) { if ((this.nfeStatusServicoNF2OperationCompleted == null)) { this.nfeStatusServicoNF2OperationCompleted = new System.Threading.SendOrPostCallback(this.OnnfeStatusServicoNF2OperationCompleted); } this.InvokeAsync("nfeStatusServicoNF2", new object[] { nfeDadosMsg}, this.nfeStatusServicoNF2OperationCompleted, userState); } private void OnnfeStatusServicoNF2OperationCompleted(object arg) { if ((this.nfeStatusServicoNF2Completed != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.nfeStatusServicoNF2Completed(this, new nfeStatusServicoNF2CompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2", IsNullable = false)] public partial class nfeCabecMsg : System.Web.Services.Protocols.SoapHeader { private string versaoDadosField; private string cUFField; private System.Xml.XmlAttribute[] anyAttrField; /// <remarks/> public string versaoDados { get { return this.versaoDadosField; } set { this.versaoDadosField = value; } } /// <remarks/> public string cUF { get { return this.cUFField; } set { this.cUFField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAnyAttributeAttribute()] public System.Xml.XmlAttribute[] AnyAttr { get { return this.anyAttrField; } set { this.anyAttrField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] public delegate void nfeStatusServicoNF2CompletedEventHandler(object sender, nfeStatusServicoNF2CompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class nfeStatusServicoNF2CompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal nfeStatusServicoNF2CompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Xml.XmlNode Result { get { this.RaiseExceptionIfNecessary(); return ((System.Xml.XmlNode)(this.results[0])); } } } }
rodrigordi/opennfe
Open NFe 3/RDI.NFe2.Business/HWS/HWS.SVCAN.Status.NfeStatusServico2.cs
C#
gpl-3.0
6,894
#include <vector> #include <queue> #include <cstdio> #include <cstring> using namespace std; typedef vector<int> vi; #define pb push_back vector<vi> G; int dist[10010]; int parent[10010]; void bfs(int n) { queue<int> q; q.push(n); memset(dist, -1, sizeof(dist)); memset(dist, -1, sizeof(parent)); dist[n] = 0; while(!q.empty()) { int u = q.front(); q.pop(); for(int i=0; i<G[u].size(); i++) { if(dist[G[u][i]] == -1) { dist[G[u][i]] = dist[u] + 1; parent[G[u][i]] = u; q.push(G[u][i]); } } } } int main() { int v, e; scanf("%d %d", &v, &e); G.assign(v, vi()); int a, b; for(int i=0; i<e; i++) { scanf("%d %d", &a, &b); G[a].pb(b); } bfs(0); printf("Distances\n"); for(int i=0; i<v; i++) printf("%d ", dist[i]); printf("\n"); printf("Parents\n"); for(int i=0; i<v; i++) printf("%d ", parent[i]); printf("\n"); return 0; }
jhtan/cp
teambook/algorithms/graphs/bfs.cpp
C++
gpl-3.0
940
# -*- coding: utf-8 -*- #------------------------------------------------------------ # streamondemand - XBMC Plugin # Conector para tutele # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core import scrapertools from core import logger from core import config DEBUG = config.get_setting("debug") def find_url_play(data, headers): logger.info("[tutele.py] find_url_play") ''' <script type='text/javascript'> width=700, height=420, channel='footmax1', token=document.domain, e='1';</script><script type='text/javascript' src='http://tutelehd.com/embedPlayer.js'></script> ''' fid = scrapertools.find_single_match (data, "channel=['\"]([^'\"]+)[^<]+</script><script type=['\"]text/javascript['\"] src=['\"]http://tutelehd.com/embedPlayer.js['\"]") #fid = scrapertools.find_single_match (data, "channel=['\"]([^'\"]+).*?<script type=['\"]text/javascript['\"] src=['\"]http://tutelehd.com/embedPlayer.js['\"]") if fid == '': return '' pageurl = 'http://tutelehd.com/embed/embed.php?channel=%s&w=700&h=420' % fid # http://tutelehd.com/embed/embed.php?channel=footmax1&w=700&h=420 data2 = scrapertools.cachePage(pageurl, headers=headers) if (DEBUG): logger.info("data2="+data2) ''' <script type="text/javascript"> var so = new SWFObject('/player.swf', 'jwplayer1', '100%', '100%', '8'); so.addParam('allowscriptaccess', 'always'); so.addParam('allowfullscreen', 'true'); so.addParam('wmode','opaque'); so.addVariable('logo', ''); so.addVariable('dock','false') so.addVariable('autostart', 'true'); so.addVariable('token', '0fea41113b03061a'); so.addVariable('abouttext', 'Player http://tutelehd.com'); so.addVariable('aboutlink', 'http://tutelehd.com'); so.addVariable('file', 'footmax1'); so.addVariable('image', ''); so.addVariable('logo.link','http://tutelehd.com/'); so.addVariable('logo.position','top-right'); so.addVariable('stretching','exactfit'); so.addVariable('backcolor','000000'); so.addVariable('frontcolor','ffffff'); so.addVariable('screencolor','000000'); so.addVariable('streamer', 'rtmpe://live.tutelehd.com/redirect?token=lkTEmeABiFNVNxbjh9SgsAExpired=1422985939'); so.addVariable('provider', 'rtmp'); so.write('jwplayer1'); </script> ''' swfurl = 'http://tutelehd.com' + scrapertools.find_single_match (data2, 'new SWFObject\(["\']([^"\']+)') filevalue = scrapertools.find_single_match (data2, '["\']file["\'][:,]\s*["\']([^"\']+)') rtmpurl = scrapertools.find_single_match (data2, '["\']streamer["\'][:,]\s*["\']([^"\']+)') tokenvalue = scrapertools.find_single_match (data2, '["\']token["\'][:,]\s*["\']([^"\']+)') #appvalue = scrapertools.find_single_match (rtmpurl, 'rtmpe://live.tutelehd.com/([^"\']+)') #url = '%s app=%s playpath=%s swfUrl=%s swfVfy=1 live=true token=%s flashver=WIN\\202012,0,0,77 pageUrl=%s' % (rtmpurl, appvalue, filevalue, swfurl, tokenvalue, pageurl) url = '%s playpath=%s swfUrl=%s swfVfy=1 live=true token=%s pageUrl=%s' % (rtmpurl, filevalue, swfurl, tokenvalue, pageurl) return url
Zanzibar82/streamondemand.test
servers_sports/tutele.py
Python
gpl-3.0
3,586
import { registerReducer } from 'foremanReact/common/MountingService'; import { addGlobalFill } from 'foremanReact/components/common/Fill/GlobalFill'; import { registerRoutes } from 'foremanReact/routes/RoutingService'; import Routes from './src/Router/routes' import reducers from './src/reducers'; // register reducers Object.entries(reducers).forEach(([key, reducer]) => registerReducer(key, reducer) ); // register client routes registerRoutes('PluginTemplate', Routes); // register fills for extending foreman core // http://foreman.surge.sh/?path=/docs/introduction-slot-and-fill--page addGlobalFill('<slotId>', '<fillId>', <div key='plugin-template-example' />, 300);
theforeman/foreman_plugin_template
webpack/global_index.js
JavaScript
gpl-3.0
682
/* * IntelliJ IDEA plugin to support the Neos CMS. * Copyright (C) 2016 Christian Vette * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vette.idea.neos.lang.fusion.resolve.ref; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiPolyVariantReference; import de.vette.idea.neos.lang.fusion.psi.FusionElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public interface FusionReference extends PsiPolyVariantReference { @Override @NotNull FusionElement getElement(); @Nullable @Override PsiElement resolve(); }
cvette/intellij-neos
src/main/java/de/vette/idea/neos/lang/fusion/resolve/ref/FusionReference.java
Java
gpl-3.0
1,221
using System.Windows; using JetBrains.Annotations; using KMBEditor.PresentationLayer.Common.Behavior; namespace KMBEditor.PresentationLayer.Common.Property { /// <summary> /// コンテンツの遅延ロード用データ保持添付プロパティ /// <see cref="TabControlLazyLoadContentAttachedBehavior"/>と組み合わせて使用する /// </summary> public class LazyLoadContentAttachedProperty { [NotNull] public static readonly DependencyProperty ContentProperty = DependencyProperty.RegisterAttached( "Content", typeof(object), typeof(LazyLoadContentAttachedProperty), new UIPropertyMetadata()); public static object GetContent(DependencyObject obj) { return obj.GetValue(ContentProperty); } public static void SetContent(DependencyObject obj, object value) { obj.SetValue(ContentProperty, value); } } }
tar-bin/KMBEditor
KMBEditor/PresentationLayer/Common/Property/LazyLoadContentAttachedProperty.cs
C#
gpl-3.0
1,011
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("KataMinesweeper.Tests")] [assembly : AssemblyDescription("")] [assembly : AssemblyConfiguration("")] [assembly : AssemblyCompany("")] [assembly : AssemblyProduct("KataMinesweeper.Tests")] [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("f18a2a49-f3b5-4948-ab25-843d65b89c3c")] // 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")]
tschroedter/csharp_examples
Katas/Minesweeper/KataMinesweeper.Tests/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,394
using System; using OpenTK; using OpenTK.Graphics.OpenGL; using OpenTK.Audio; using OpenTK.Audio.OpenAL; using OpenTK.Input; using System.Drawing; namespace Game2DKit { class Game : GameWindow { protected ContentManager Content = new ContentManager(); /// <summary>Creates a 800x600 window with the specified title.</summary> public Game() : base((int)Globals.ScreenDimensions.X, (int)Globals.ScreenDimensions.Y, OpenTK.Graphics.GraphicsMode.Default, "Game") { VSync = VSyncMode.On; } /// <summary>Load resources here.</summary> /// <param name="e">Not used.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); GL.ClearColor(Color.CornflowerBlue); SetupViewport(); //GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); //GL.AlphaFunc(AlphaFunction.Greater, 0.5f); //GL.Enable(EnableCap.AlphaTest); GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest); Game2DKit.Input.Keyboard.GameKeyboard = this.Keyboard; } protected void SetupViewport() { GL.Viewport(new System.Drawing.Size(Width, Height)); GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); GL.Ortho(0, (int)Globals.ScreenDimensions.X, 0, (int)Globals.ScreenDimensions.Y, -1, 1); //GL.Ortho(0, Width, 0, Height, -1, 1); } /// <summary> /// Called when your window is resized. Set your viewport here. It is also /// a good place to set up your projection matrix (which probably changes /// along when the aspect ratio of your window). /// </summary> /// <param name="e">Not used.</param> protected override void OnResize(EventArgs e) { SetupViewport(); } /// <summary> /// Called when it is time to setup the next frame. Add you game logic here. /// </summary> /// <param name="e">Contains timing information for framerate independent logic.</param> protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); if (Keyboard[Key.Escape]) Exit(); } /// <summary> /// Called when it is time to render the next frame. Add your rendering code here. /// </summary> /// <param name="e">Contains timing information.</param> protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); GL.Flush(); SwapBuffers(); } } }
BriptimusPrimus/shooter
ConsoleApplication1/Game2DKit/Game.cs
C#
gpl-3.0
2,917
package gui.menus.control; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.JMenuItem; import gui.HelpText; import gui.control.HelpGUIControl; import gui.menus.HelpHelpMenu; public class HelpHelpMenuControl { private static HelpHelpMenuControl instance; public static HelpHelpMenuControl getInstance() { if (instance == null) instance = new HelpHelpMenuControl(); return instance; } private HelpHelpMenu menu = HelpHelpMenu.getInstance(); private HelpHelpMenuControl() { Vector<JMenuItem> menuList = this.menu.getMenuList(); for (JMenuItem item : menuList) { item.addActionListener(l); } } private ActionListener l = new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { menuActionPerformed(evt); } }; private void menuActionPerformed(ActionEvent evt) { JMenuItem item = (JMenuItem) evt.getSource(); if (item == menu.getAllItem()) { new HelpGUIControl(HelpText.ALLGEMEIN,"Hilfe Allgemein"); } if (item == menu.getFileItem()) { new HelpGUIControl(HelpText.DATEI,"Hilfe Datei"); } if (item == menu.getObjectItem()) { new HelpGUIControl(HelpText.OBJEKT,"Hilfe Objekt"); } if (item == menu.getWindowItem()) { new HelpGUIControl(HelpText.FENSTER,"Hilfe Fenster"); } } }
reinerho/BRLA
BRLA/src/gui/menus/control/HelpHelpMenuControl.java
Java
gpl-3.0
1,394
namespace EventsAndAttendance.Forms { partial class complaintsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(complaintsForm)); this.searchInComboBox = new System.Windows.Forms.ToolStripComboBox(); this.toolStripLabel4 = new System.Windows.Forms.ToolStripLabel(); this.searchForTextBox = new System.Windows.Forms.ToolStripTextBox(); this.totalRecsLabel = new System.Windows.Forms.ToolStripLabel(); this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel(); this.dsplySizeComboBox = new System.Windows.Forms.ToolStripComboBox(); this.panel1 = new System.Windows.Forms.Panel(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.addButton = new System.Windows.Forms.ToolStripButton(); this.editButton = new System.Windows.Forms.ToolStripButton(); this.saveButton = new System.Windows.Forms.ToolStripButton(); this.delButton = new System.Windows.Forms.ToolStripButton(); this.rcHstryButton = new System.Windows.Forms.ToolStripButton(); this.vwSQLButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.moveFirstButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.movePreviousButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.positionTextBox = new System.Windows.Forms.ToolStripTextBox(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.moveNextButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.moveLastButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.goButton = new System.Windows.Forms.ToolStripButton(); this.resetButton = new System.Windows.Forms.ToolStripButton(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.cmplntsDataGridView = new System.Windows.Forms.DataGridView(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column5 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column6 = new System.Windows.Forms.DataGridViewButtonColumn(); this.Column7 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column8 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column9 = new System.Windows.Forms.DataGridViewButtonColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column3 = new System.Windows.Forms.DataGridViewButtonColumn(); this.Column11 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column4 = new System.Windows.Forms.DataGridViewCheckBoxColumn(); this.Column10 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column12 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.panel1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.groupBox4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.cmplntsDataGridView)).BeginInit(); this.SuspendLayout(); // // searchInComboBox // this.searchInComboBox.Items.AddRange(new object[] { "Complaint/Observation Type", "Customer", "Date Created", "Description", "Person to Resolve", "Status"}); this.searchInComboBox.Name = "searchInComboBox"; this.searchInComboBox.Size = new System.Drawing.Size(121, 25); this.searchInComboBox.Sorted = true; this.searchInComboBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.searchForTextBox_KeyDown); // // toolStripLabel4 // this.toolStripLabel4.Name = "toolStripLabel4"; this.toolStripLabel4.Size = new System.Drawing.Size(58, 22); this.toolStripLabel4.Text = "Search In:"; // // searchForTextBox // this.searchForTextBox.Name = "searchForTextBox"; this.searchForTextBox.Size = new System.Drawing.Size(80, 25); this.searchForTextBox.Text = "%"; this.searchForTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.searchForTextBox_KeyDown); this.searchForTextBox.Enter += new System.EventHandler(this.searchForTextBox_Click); this.searchForTextBox.Click += new System.EventHandler(this.searchForTextBox_Click); // // totalRecsLabel // this.totalRecsLabel.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.totalRecsLabel.Name = "totalRecsLabel"; this.totalRecsLabel.Size = new System.Drawing.Size(50, 22); this.totalRecsLabel.Text = "of Total"; // // toolStripLabel3 // this.toolStripLabel3.Name = "toolStripLabel3"; this.toolStripLabel3.Size = new System.Drawing.Size(65, 22); this.toolStripLabel3.Text = "Search For:"; // // dsplySizeComboBox // this.dsplySizeComboBox.AutoSize = false; this.dsplySizeComboBox.Items.AddRange(new object[] { "1", "5", "10", "20", "30", "50", "100", "500", "1000", "5000", "10000"}); this.dsplySizeComboBox.Name = "dsplySizeComboBox"; this.dsplySizeComboBox.Size = new System.Drawing.Size(35, 23); this.dsplySizeComboBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.searchForTextBox_KeyDown); // // panel1 // this.panel1.AutoScroll = true; this.panel1.BackColor = System.Drawing.Color.Transparent; this.panel1.Controls.Add(this.toolStrip1); this.panel1.Controls.Add(this.groupBox4); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(1134, 363); this.panel1.TabIndex = 1; // // toolStrip1 // this.toolStrip1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.toolStrip1.AutoSize = false; this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.addButton, this.editButton, this.saveButton, this.delButton, this.rcHstryButton, this.vwSQLButton, this.toolStripSeparator1, this.moveFirstButton, this.toolStripSeparator3, this.movePreviousButton, this.toolStripSeparator4, this.toolStripLabel1, this.positionTextBox, this.totalRecsLabel, this.toolStripSeparator5, this.moveNextButton, this.toolStripSeparator6, this.moveLastButton, this.toolStripSeparator7, this.dsplySizeComboBox, this.toolStripSeparator8, this.toolStripLabel3, this.searchForTextBox, this.toolStripLabel4, this.searchInComboBox, this.goButton, this.resetButton}); this.toolStrip1.Location = new System.Drawing.Point(0, 3); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(1134, 25); this.toolStrip1.TabIndex = 13; this.toolStrip1.Text = "toolStrip1"; // // addButton // this.addButton.Image = global::EventsAndAttendance.Properties.Resources.plus_32; this.addButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.addButton.Name = "addButton"; this.addButton.Size = new System.Drawing.Size(51, 22); this.addButton.Text = "ADD"; this.addButton.Click += new System.EventHandler(this.addButton_Click); // // editButton // this.editButton.Image = global::EventsAndAttendance.Properties.Resources.edit32; this.editButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.editButton.Name = "editButton"; this.editButton.Size = new System.Drawing.Size(51, 22); this.editButton.Text = "EDIT"; this.editButton.Click += new System.EventHandler(this.editButton_Click); // // saveButton // this.saveButton.Image = global::EventsAndAttendance.Properties.Resources.FloppyDisk; this.saveButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.saveButton.Name = "saveButton"; this.saveButton.Size = new System.Drawing.Size(54, 22); this.saveButton.Text = "SAVE"; this.saveButton.Click += new System.EventHandler(this.saveButton_Click); // // delButton // this.delButton.Image = global::EventsAndAttendance.Properties.Resources.delete; this.delButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.delButton.Name = "delButton"; this.delButton.Size = new System.Drawing.Size(66, 22); this.delButton.Text = "DELETE"; this.delButton.Click += new System.EventHandler(this.delButton_Click); // // rcHstryButton // this.rcHstryButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.rcHstryButton.Image = global::EventsAndAttendance.Properties.Resources.statistics_32; this.rcHstryButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.rcHstryButton.Name = "rcHstryButton"; this.rcHstryButton.Size = new System.Drawing.Size(23, 22); this.rcHstryButton.Text = "Record History"; this.rcHstryButton.Click += new System.EventHandler(this.rcHstryButton_Click); // // vwSQLButton // this.vwSQLButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.vwSQLButton.Image = global::EventsAndAttendance.Properties.Resources.sql_icon; this.vwSQLButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.vwSQLButton.Name = "vwSQLButton"; this.vwSQLButton.Size = new System.Drawing.Size(23, 22); this.vwSQLButton.Text = "View SQL"; this.vwSQLButton.Click += new System.EventHandler(this.vwSQLButton_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // moveFirstButton // this.moveFirstButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.moveFirstButton.Image = global::EventsAndAttendance.Properties.Resources.DataContainer_MoveFirstHS; this.moveFirstButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.moveFirstButton.Name = "moveFirstButton"; this.moveFirstButton.Size = new System.Drawing.Size(23, 22); this.moveFirstButton.Text = "First"; this.moveFirstButton.Click += new System.EventHandler(this.PnlNavButtons); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25); // // movePreviousButton // this.movePreviousButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.movePreviousButton.Image = global::EventsAndAttendance.Properties.Resources.DataContainer_MovePreviousHS; this.movePreviousButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.movePreviousButton.Name = "movePreviousButton"; this.movePreviousButton.Size = new System.Drawing.Size(23, 22); this.movePreviousButton.Text = "tsbPrevious"; this.movePreviousButton.ToolTipText = "Previous"; this.movePreviousButton.Click += new System.EventHandler(this.PnlNavButtons); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25); // // toolStripLabel1 // this.toolStripLabel1.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(50, 22); this.toolStripLabel1.Text = "Record "; // // positionTextBox // this.positionTextBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.positionTextBox.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.positionTextBox.Name = "positionTextBox"; this.positionTextBox.Size = new System.Drawing.Size(50, 25); this.positionTextBox.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.positionTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.positionTextBox_KeyDown); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25); // // moveNextButton // this.moveNextButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.moveNextButton.Image = global::EventsAndAttendance.Properties.Resources.DataContainer_MoveNextHS; this.moveNextButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.moveNextButton.Name = "moveNextButton"; this.moveNextButton.Size = new System.Drawing.Size(23, 22); this.moveNextButton.Text = "toolStripButton3"; this.moveNextButton.ToolTipText = "Next"; this.moveNextButton.Click += new System.EventHandler(this.PnlNavButtons); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25); // // moveLastButton // this.moveLastButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.moveLastButton.Image = global::EventsAndAttendance.Properties.Resources.DataContainer_MoveLastHS; this.moveLastButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.moveLastButton.Name = "moveLastButton"; this.moveLastButton.Size = new System.Drawing.Size(23, 22); this.moveLastButton.Text = "toolStripButton4"; this.moveLastButton.ToolTipText = "Last"; this.moveLastButton.Click += new System.EventHandler(this.PnlNavButtons); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; this.toolStripSeparator7.Size = new System.Drawing.Size(6, 25); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(6, 25); // // goButton // this.goButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.goButton.Image = global::EventsAndAttendance.Properties.Resources.refresh; this.goButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.goButton.Name = "goButton"; this.goButton.Size = new System.Drawing.Size(23, 22); this.goButton.Text = "Go"; this.goButton.Click += new System.EventHandler(this.goButton_Click); // // resetButton // this.resetButton.Image = global::EventsAndAttendance.Properties.Resources.undo_256; this.resetButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.resetButton.Name = "resetButton"; this.resetButton.Size = new System.Drawing.Size(59, 22); this.resetButton.Text = "RESET"; this.resetButton.Click += new System.EventHandler(this.resetButton_Click); // // groupBox4 // this.groupBox4.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox4.Controls.Add(this.cmplntsDataGridView); this.groupBox4.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.groupBox4.ForeColor = System.Drawing.Color.White; this.groupBox4.Location = new System.Drawing.Point(3, 23); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(1128, 340); this.groupBox4.TabIndex = 23; this.groupBox4.TabStop = false; // // cmplntsDataGridView // this.cmplntsDataGridView.AllowUserToAddRows = false; this.cmplntsDataGridView.AllowUserToDeleteRows = false; this.cmplntsDataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cmplntsDataGridView.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells; this.cmplntsDataGridView.BackgroundColor = System.Drawing.Color.White; this.cmplntsDataGridView.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.cmplntsDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.cmplntsDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.dataGridViewTextBoxColumn4, this.Column5, this.Column6, this.Column7, this.Column8, this.Column9, this.dataGridViewTextBoxColumn2, this.Column2, this.Column1, this.Column3, this.Column11, this.Column4, this.Column10, this.Column12}); dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle5.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle5.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle5.ForeColor = System.Drawing.Color.White; dataGridViewCellStyle5.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle5.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.cmplntsDataGridView.DefaultCellStyle = dataGridViewCellStyle5; this.cmplntsDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter; this.cmplntsDataGridView.Location = new System.Drawing.Point(2, 10); this.cmplntsDataGridView.MinimumSize = new System.Drawing.Size(286, 96); this.cmplntsDataGridView.Name = "cmplntsDataGridView"; this.cmplntsDataGridView.ReadOnly = true; this.cmplntsDataGridView.RowHeadersWidth = 20; dataGridViewCellStyle6.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle6.ForeColor = System.Drawing.Color.Black; dataGridViewCellStyle6.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.cmplntsDataGridView.RowsDefaultCellStyle = dataGridViewCellStyle6; this.cmplntsDataGridView.Size = new System.Drawing.Size(1124, 327); this.cmplntsDataGridView.TabIndex = 16; this.cmplntsDataGridView.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.cmplntsDataGridView_CellValueChanged); this.cmplntsDataGridView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.cmplntsDataGridView_CellContentClick); // // dataGridViewTextBoxColumn4 // this.dataGridViewTextBoxColumn4.HeaderText = "Report No."; this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4"; this.dataGridViewTextBoxColumn4.ReadOnly = true; this.dataGridViewTextBoxColumn4.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // Column5 // this.Column5.HeaderText = "Customer"; this.Column5.Name = "Column5"; this.Column5.ReadOnly = true; this.Column5.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.Column5.Width = 120; // // Column6 // this.Column6.HeaderText = "..."; this.Column6.Name = "Column6"; this.Column6.ReadOnly = true; this.Column6.Width = 25; // // Column7 // this.Column7.HeaderText = "customer_id"; this.Column7.Name = "Column7"; this.Column7.ReadOnly = true; this.Column7.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.Column7.Visible = false; // // Column8 // this.Column8.HeaderText = "Complain / Observation Type"; this.Column8.Name = "Column8"; this.Column8.ReadOnly = true; this.Column8.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // Column9 // this.Column9.HeaderText = "..."; this.Column9.Name = "Column9"; this.Column9.ReadOnly = true; this.Column9.Width = 25; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.FillWeight = 122.7633F; this.dataGridViewTextBoxColumn2.HeaderText = "Complain / Observation Description"; this.dataGridViewTextBoxColumn2.MinimumWidth = 60; this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.ReadOnly = true; this.dataGridViewTextBoxColumn2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.dataGridViewTextBoxColumn2.Width = 190; // // Column2 // this.Column2.HeaderText = "Suggested Solution"; this.Column2.Name = "Column2"; this.Column2.ReadOnly = true; this.Column2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.Column2.Width = 130; // // Column1 // this.Column1.HeaderText = "Person to Resolve Issue"; this.Column1.Name = "Column1"; this.Column1.ReadOnly = true; this.Column1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.Column1.Width = 110; // // Column3 // this.Column3.HeaderText = "..."; this.Column3.Name = "Column3"; this.Column3.ReadOnly = true; this.Column3.Width = 25; // // Column11 // this.Column11.HeaderText = "person_id"; this.Column11.Name = "Column11"; this.Column11.ReadOnly = true; this.Column11.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.Column11.Visible = false; // // Column4 // this.Column4.HeaderText = "Issue Resolved?"; this.Column4.Name = "Column4"; this.Column4.ReadOnly = true; this.Column4.Width = 65; // // Column10 // this.Column10.HeaderText = "Status"; this.Column10.Name = "Column10"; this.Column10.ReadOnly = true; this.Column10.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.Column10.Width = 70; // // Column12 // dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.Column12.DefaultCellStyle = dataGridViewCellStyle4; this.Column12.HeaderText = "Date Created / Doc. Number"; this.Column12.Name = "Column12"; this.Column12.ReadOnly = true; this.Column12.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.Column12.Width = 130; // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "73.ico"); this.imageList1.Images.SetKeyName(1, "groupings.png"); this.imageList1.Images.SetKeyName(2, "LaST (Cobalt) Library Folder.png"); this.imageList1.Images.SetKeyName(3, "SecurityLock.png"); this.imageList1.Images.SetKeyName(4, "Help111.png"); this.imageList1.Images.SetKeyName(5, "logo.ico"); this.imageList1.Images.SetKeyName(6, "network_48.png"); this.imageList1.Images.SetKeyName(7, "03-books.png"); this.imageList1.Images.SetKeyName(8, "49.png"); this.imageList1.Images.SetKeyName(9, "53.png"); this.imageList1.Images.SetKeyName(10, "119.png"); this.imageList1.Images.SetKeyName(11, "lan disconnect.ico"); this.imageList1.Images.SetKeyName(12, "48.png"); this.imageList1.Images.SetKeyName(13, "mi_scare_report.png"); this.imageList1.Images.SetKeyName(14, "person.png"); this.imageList1.Images.SetKeyName(15, "user-mapping.ico"); this.imageList1.Images.SetKeyName(16, "forex_64x64x32.png"); this.imageList1.Images.SetKeyName(17, "LaSTCobaltBooks.ico"); this.imageList1.Images.SetKeyName(18, "BuildingManagement.png"); this.imageList1.Images.SetKeyName(19, "LaST (Cobalt) Control Panel.png"); this.imageList1.Images.SetKeyName(20, "Inventory.png"); this.imageList1.Images.SetKeyName(21, "Icon.ico"); this.imageList1.Images.SetKeyName(22, "reports.png"); this.imageList1.Images.SetKeyName(23, "open-safety-box-icon.png"); this.imageList1.Images.SetKeyName(24, "investor-icon.png"); this.imageList1.Images.SetKeyName(25, "Calendar-icon.png"); this.imageList1.Images.SetKeyName(26, "calendar-icon1.png"); this.imageList1.Images.SetKeyName(27, "90.png"); // // complaintsForm // this.BackColor = System.Drawing.SystemColors.ActiveCaption; this.ClientSize = new System.Drawing.Size(1134, 363); this.Controls.Add(this.panel1); this.DockAreas = WeifenLuo.WinFormsUI.Docking.DockAreas.Document; this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MinimizeBox = false; this.Name = "complaintsForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.TabText = "Complaints/Observations"; this.Text = "Complaints/Observations"; this.Load += new System.EventHandler(this.wfnPrchOrdrForm_Load); this.panel1.ResumeLayout(false); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.groupBox4.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.cmplntsDataGridView)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ToolStripComboBox searchInComboBox; private System.Windows.Forms.ToolStripLabel toolStripLabel4; private System.Windows.Forms.ToolStripButton addButton; private System.Windows.Forms.ToolStripTextBox searchForTextBox; private System.Windows.Forms.ToolStripButton editButton; private System.Windows.Forms.ToolStripLabel totalRecsLabel; private System.Windows.Forms.ToolStripLabel toolStripLabel3; private System.Windows.Forms.ToolStripButton delButton; private System.Windows.Forms.ToolStripButton saveButton; private System.Windows.Forms.ToolStripComboBox dsplySizeComboBox; private System.Windows.Forms.ToolStripButton moveLastButton; private System.Windows.Forms.ToolStripButton moveNextButton; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton moveFirstButton; private System.Windows.Forms.ToolStripButton movePreviousButton; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripTextBox positionTextBox; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.DataGridView cmplntsDataGridView; private System.Windows.Forms.ToolStripButton goButton; private System.Windows.Forms.ToolStripButton resetButton; private System.Windows.Forms.ToolStripButton rcHstryButton; private System.Windows.Forms.ToolStripButton vwSQLButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewTextBoxColumn Column5; private System.Windows.Forms.DataGridViewButtonColumn Column6; private System.Windows.Forms.DataGridViewTextBoxColumn Column7; private System.Windows.Forms.DataGridViewTextBoxColumn Column8; private System.Windows.Forms.DataGridViewButtonColumn Column9; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn Column2; private System.Windows.Forms.DataGridViewTextBoxColumn Column1; private System.Windows.Forms.DataGridViewButtonColumn Column3; private System.Windows.Forms.DataGridViewTextBoxColumn Column11; private System.Windows.Forms.DataGridViewCheckBoxColumn Column4; private System.Windows.Forms.DataGridViewTextBoxColumn Column10; private System.Windows.Forms.DataGridViewTextBoxColumn Column12; } }
rhomicom-systems-tech-gh/Rhomicom-ERP-Desktop
RhomicomERP/EventsAndAttendance/Forms/complaintsForm.designer.cs
C#
gpl-3.0
32,532
<?php /** * ProBIND v3 - Professional DNS management made easy. * * Copyright (c) 2016 by Paco Orozco <paco@pacoorozco.info> * * This file is part of some open source application. * * Licensed under GNU General Public License 3.0. * Some rights reserved. See LICENSE, AUTHORS. * * @author Paco Orozco <paco@pacoorozco.info> * @copyright 2016 Paco Orozco * @license GPL-3.0 <http://spdx.org/licenses/GPL-3.0> * * @link https://github.com/pacoorozco/probind */ namespace App\Http\Requests; use App\Enums\ServerType; use BenSampo\Enum\Rules\EnumValue; use Illuminate\Validation\Rule; class ServerCreateRequest extends Request { public function authorize(): bool { return true; } public function rules(): array { return [ 'hostname' => [ 'required', 'string', Rule::unique('servers'), ], 'ip_address' => [ 'required', 'ip', Rule::unique('servers'), ], 'type' => [ 'required', new EnumValue(ServerType::class), ], 'ns_record' => [ 'required', 'boolean', ], 'push_updates' => [ 'required', 'boolean', ], 'active' => [ 'required', 'boolean', ], ]; } public function hostname(): string { return $this->input('hostname'); } public function ipAddress(): string { return $this->input('ip_address'); } public function type(): ServerType { $serverTypeName = $this->input('type'); return ServerType::fromValue($serverTypeName); } public function requiresNSRecord(): bool { return (bool) $this->input('ns_record'); } public function requiresUpdatePushes(): bool { return (bool) $this->input('push_updates'); } public function enabled(): bool { return (bool) $this->input('active'); } }
pacoorozco/probind
app/Http/Requests/ServerCreateRequest.php
PHP
gpl-3.0
2,159
<?php /** * @package DPCalendar * @copyright Copyright (C) 2019 Digital Peak GmbH. <https://www.digital-peak.com> * @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL */ defined('_JEXEC') or die(); $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $saveOrder = $listOrder == 'a.ordering'; if ($saveOrder && \DPCalendar\Helper\DPCalendarHelper::isJoomlaVersion('4', '<')) { $saveOrderingUrl = 'index.php?option=com_dpcalendar&task=extcalendars.saveOrderAjax&tmpl=component'; JHtml::_('sortablelist.sortable', 'extcalendarsList', 'adminForm', strtolower($listDirn), $saveOrderingUrl); } ?> <div class="com-dpcalendar-extcalendars__calendars"> <table class="dp-table" id="extcalendarsList"> <thead> <tr> <th class="dp-table__col-order"> <?php echo JHtml::_( 'searchtools.sort', '', 'a.ordering', $listDirn, $listOrder, null, 'asc', 'JGRID_HEADING_ORDERING', 'icon-menu-2' ); ?> </th> <th class="dp-table__col-check"> <input type="checkbox" name="checkall-toggle" value="" title="<?php echo $this->translate('JGLOBAL_CHECK_ALL'); ?>" class="dp-input dp-input-checkbox dp-input-check-all"/> </th> <th class="dp-table__col-state"><?php echo JHtml::_('grid.sort', 'JSTATUS', 'a.state', $listDirn, $listOrder); ?></th> <th class="dp-table__col-expand"><?php echo JHtml::_('grid.sort', 'JGLOBAL_TITLE', 'a.title', $listDirn, $listOrder); ?></th> <th><?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ACCESS', 'a.access', $listDirn, $listOrder); ?></th> <th><?php echo JHtml::_('grid.sort', 'JGRID_HEADING_LANGUAGE', 'a.language', $listDirn, $listOrder); ?></th> <th><?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ID', 'a.id', $listDirn, $listOrder); ?></th> </tr> </thead> <tbody> <?php foreach ($this->items as $i => $item) { ?> <?php $ordering = $listOrder == 'a.ordering'; ?> <?php $canCreate = $this->user->authorise('core.create', 'com_dpcalendar'); ?> <?php $canEdit = $this->user->authorise('core.edit', 'com_dpcalendar'); ?> <?php $canChange = $this->user->authorise('core.edit.state', 'com_dpcalendar'); ?> <tr sortable-group-id=""> <td data-column="<?php echo $this->translate('JGRID_HEADING_ORDERING'); ?>"> <?php if ($canChange) { ?> <span class="sortable-handler <?php echo $saveOrder ? '' : 'inactive tip-top'; ?>"><i class="icon-menu"></i></span> <input type="text" style="display:none" name="order[]" size="5" value="<?php echo $item->ordering; ?>" class="width-20 text-area-order"/> <?php } else { ?> <span class="sortable-handler inactive"><i class="icon-menu"></i></span> <?php } ?> </td> <td data-column="<?php echo $this->translate('JGLOBAL_CHECK_ALL'); ?>"><?php echo JHtml::_('grid.id', $i, $item->id); ?></td> <td data-column="<?php echo $this->translate('JSTATUS'); ?>"> <?php echo JHtml::_( 'jgrid.published', $item->state, $i, 'extcalendars.', $canChange, 'cb', $item->publish_up, $item->publish_down ); ?> </td> <td data-column="<?php echo $this->translate('JGLOBAL_TITLE'); ?>"> <?php if ($canEdit) { ?> <a href="<?php echo JRoute::_('index.php?option=com_dpcalendar&task=extcalendar.edit&id=' . (int)$item->id . '&tmpl=' . $this->input->getWord('tmpl') . '&dpplugin=' . $this->input->getWord('dpplugin')); ?>"> <?php echo $this->escape($item->title); ?></a> <?php } else { ?> <?php echo $this->escape($item->title); ?> <?php } ?> </td> <td data-column="<?php echo $this->translate('JGRID_HEADING_ACCESS'); ?>"><?php echo $this->escape($item->access_level); ?></td> <td data-column="<?php echo $this->translate('JGRID_HEADING_LANGUAGE'); ?>"> <?php if ($item->language == '*') { ?> <?php echo JText::alt('JALL', 'language'); ?> <?php } else { ?> <?php echo $item->language_title ? $this->escape($item->language_title) : JText::_('JUNDEFINED'); ?> <?php } ?> </td> <td data-column="<?php echo $this->translate('JGRID_HEADING_ID'); ?>"><?php echo (int)$item->id; ?></td> </tr> <?php } ?> </table> <tfoot> <tr> <td colspan="10"> <?php echo $this->pagination->getListFooter(); ?> </td> </tr> </tfoot> </div>
Digital-Peak/DPCalendar-Free
com_dpcalendar/admin/views/extcalendars/tmpl/default_calendars.php
PHP
gpl-3.0
4,363
package pt.uminho.sysbio.biosynth.integration.model; import java.io.Serializable; import java.util.List; import java.util.Set; import org.neo4j.graphdb.DynamicLabel; import org.neo4j.graphdb.DynamicRelationshipType; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Label; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.helpers.collection.Iterators; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pt.uminho.sysbio.biosynth.integration.io.dao.AbstractNeo4jDao; import pt.uminho.sysbio.biosynth.integration.io.dao.neo4j.GlobalLabel; import pt.uminho.sysbio.biosynth.integration.io.dao.neo4j.MetabolicModelLabel; import pt.uminho.sysbio.biosynth.integration.io.dao.neo4j.Neo4jDefinitions; import pt.uminho.sysbio.biosynth.integration.io.dao.neo4j.Neo4jUtils; import pt.uminho.sysbio.biosynth.integration.io.dao.neo4j.Neo4jUtilsIntegration; public class Neo4jGraphNormalizedGPR extends AbstractNeo4jDao implements GPRDao<GraphGPREntity>{ private static final Logger LOGGER = LoggerFactory.getLogger(Neo4jGraphNormalizedGPR.class); protected static final Label GENE_LABEL = GlobalLabel.Gene; private String model; public Neo4jGraphNormalizedGPR(GraphDatabaseService graphDatabaseService, String model) { super(graphDatabaseService); this.model = model; // TODO Auto-generated constructor stub } @Override public GraphGPREntity getGPRById(String tag, Serializable id) { // TODO Auto-generated method stub return null; } @Override public GraphGPREntity getGPRByEntry(String tag, String entry) { // TODO Auto-generated method stub return null; } @Override public GraphGPREntity saveGPR(String tag, GraphGPREntity gpr) { // GPRNormalization gprNormalization = new GPRNormalization(); Node node = graphDatabaseService.createNode(); LOGGER.debug("Create " + node); node.addLabel(DynamicLabel.label(gpr.getMajorLabel())); for (String label : gpr.getLabels()){ node.addLabel(DynamicLabel.label(label)); } Neo4jUtils.applyProperties(node, gpr.getProperties()); // AbstractSyntaxTree<DataTypeEnum, IValue> gr = gpr.getGeneRule(); // Set<Set<String>> ngprs; try { // ngprs = gprNormalization.getVariablesToSenceNode(gr.getRootNode(), true); NormalizedGPRTree normalizedTree = gpr.getNormalizedTree(); createNormalizedGPR(node, normalizedTree.getTreeNode()); node.setProperty("normalized_rule", normalizedTree.toString()); node.setProperty(Neo4jDefinitions.MAJOR_LABEL_PROPERTY.toString(), gpr.getMajorLabel()); node.setProperty(Neo4jDefinitions.PROXY_PROPERTY.toString(), false); gpr.setId(node.getId()); } catch (Exception e) { e.printStackTrace(); } return gpr; } public void createNormalizedGPR(Node parent, NormalizedGPRTreeNode gpr){ if (gpr instanceof GPRLeaf){ createNodeLeaf(parent, ((GPRLeaf) gpr).getLeaf()); } else if (gpr instanceof GPRAnd){ Node node_and = createNodeAnd(parent); for (String leaf : ((GPRAnd) gpr).getElements()){ createNodeLeaf(node_and, leaf); } } else if (gpr instanceof GPROr){ Node node_or = createNodeOr(parent); for (Set<String> orElements : ((GPROr) gpr).getElements()){ if (orElements.size() == 1){ createNodeLeaf(node_or, orElements.iterator().next()); } else { Node node_and = createNodeAnd(node_or); for (String andElement : orElements){ createNodeLeaf(node_and, andElement); } } } } } public Node createNodeAnd(Node parent){ DynamicRelationshipType relationshipType = DynamicRelationshipType.withName(GPRRelationshipType.has_logical_operator.toString()); Node node_and = graphDatabaseService.createNode(); LOGGER.debug("Create " + node_and); node_and.addLabel(DynamicLabel.label(GPRMajorLabels.AND.toString())); node_and.addLabel(DynamicLabel.label(GlobalLabel.LogicalOperator.toString())); node_and.setProperty(Neo4jDefinitions.MAJOR_LABEL_PROPERTY.toString(), GPRMajorLabels.AND.toString()); node_and.setProperty(Neo4jDefinitions.PROXY_PROPERTY.toString(), false); Relationship relationship = parent.createRelationshipTo(node_and, relationshipType); return node_and; } public Node createNodeOr(Node parent){ DynamicRelationshipType relationshipType = DynamicRelationshipType.withName(GPRRelationshipType.has_logical_operator.toString()); Node node_or = graphDatabaseService.createNode(); LOGGER.debug("Create " + node_or); node_or.addLabel(DynamicLabel.label(GPRMajorLabels.OR.toString())); node_or.addLabel(DynamicLabel.label(GlobalLabel.LogicalOperator.toString())); node_or.setProperty(Neo4jDefinitions.MAJOR_LABEL_PROPERTY.toString(), GPRMajorLabels.OR.toString()); node_or.setProperty(Neo4jDefinitions.PROXY_PROPERTY.toString(), false); Relationship relationship = parent.createRelationshipTo(node_or, relationshipType); return node_or; } public void createNodeLeaf(Node parent, String gene){ GraphGPRGeneEntity gprGene = new GraphGPRGeneEntity(); gprGene.setEntry(gene + "@" + this.model); gprGene.addLabel(MetabolicModelLabel.ModelGene.toString()); gprGene.setMajorLabel(GPRMajorLabels.Leaf.toString()); gprGene.setName(gene); gprGene.setModel(this.model); createGeneGPR(parent, gprGene); } public GraphGPRGeneEntity createGeneGPR(Node parent, GraphGPRGeneEntity gene){ DynamicRelationshipType relationshipType = DynamicRelationshipType.withName(GPRRelationshipType.has_leaf.toString()); boolean create = true; for (Node node : Iterators.asIterable(graphDatabaseService.findNodes( DynamicLabel.label(gene.getMajorLabel()), "entry", gene.getEntry()))) { create = false; LOGGER.debug(String.format("Found Previous node with entry:%s", gene.getEntry())); LOGGER.debug(String.format("MODE:UPDATE %s", node)); Neo4jUtils.applyProperties(node, gene.getProperties()); node.setProperty(Neo4jDefinitions.MAJOR_LABEL_PROPERTY.toString(), gene.getMajorLabel()); node.setProperty(Neo4jDefinitions.PROXY_PROPERTY.toString(), false); Relationship relationship = parent.createRelationshipTo(node, relationshipType); gene.setId(node.getId()); } if (create){ Node node = graphDatabaseService.createNode(); LOGGER.debug("Create " + node); node.addLabel(DynamicLabel.label(gene.getMajorLabel())); for (String label : gene.getLabels()){ node.addLabel(DynamicLabel.label(label)); } Neo4jUtils.applyProperties(node, gene.getProperties()); node.setProperty(Neo4jDefinitions.MAJOR_LABEL_PROPERTY.toString(), gene.getMajorLabel()); node.setProperty(Neo4jDefinitions.PROXY_PROPERTY.toString(), false); Relationship relationship = parent.createRelationshipTo(node, relationshipType); gene.setId(node.getId()); } return gene; } @Override public List<Long> getGlobalAllGPRIds() { // TODO Auto-generated method stub return null; } @Override public List<Long> getAllGPRIds(String tag) { // TODO Auto-generated method stub return null; } @Override public List<String> getAllGPREntries(String tag) { // TODO Auto-generated method stub return null; } }
Fxe/biosynth-framework
biosynth-integration/src/main/java/pt/uminho/sysbio/biosynth/integration/model/Neo4jGraphNormalizedGPR.java
Java
gpl-3.0
7,104
import logging import ssl import sys import threading from typing import List import websocket from homematicip.base.enums import * from homematicip.base.helpers import bytes2str from homematicip.class_maps import * from homematicip.connection import Connection from homematicip.device import * from homematicip.EventHook import * from homematicip.group import * from homematicip.rule import * from homematicip.securityEvent import * LOGGER = logging.getLogger(__name__) class Weather(HomeMaticIPObject): """ this class represents the weather of the home location""" def __init__(self, connection): super().__init__(connection) #:float: the current temperature self.temperature = 0.0 #:WeatherCondition: the current weather self.weatherCondition = WeatherCondition.UNKNOWN #:datetime: the current datime self.weatherDayTime = WeatherDayTime.DAY #:float: the minimum temperature of the day self.minTemperature = 0.0 #:float: the maximum temperature of the day self.maxTemperature = 0.0 #:float: the current humidity self.humidity = 0 #:float: the current windspeed self.windSpeed = 0.0 #:int: the current wind direction in 360° where 0° is north self.windDirection = 0 #:float: the current vapor self.vaporAmount = 0.0 def from_json(self, js): super().from_json(js) self.temperature = js["temperature"] self.weatherCondition = WeatherCondition.from_str(js["weatherCondition"]) self.weatherDayTime = WeatherDayTime.from_str(js["weatherDayTime"]) self.minTemperature = js["minTemperature"] self.maxTemperature = js["maxTemperature"] self.humidity = js["humidity"] self.windSpeed = js["windSpeed"] self.windDirection = js["windDirection"] self.vaporAmount = js["vaporAmount"] def __str__(self): return "temperature({}) weatherCondition({}) weatherDayTime({}) minTemperature({}) maxTemperature({}) humidity({}) vaporAmount({}) windSpeed({}) windDirection({})".format( self.temperature, self.weatherCondition, self.weatherDayTime, self.minTemperature, self.maxTemperature, self.humidity, self.vaporAmount, self.windSpeed, self.windDirection, ) class Location(HomeMaticIPObject): """This class represents the possible location""" def __init__(self, connection): super().__init__(connection) #:str: the name of the city self.city = "London" #:float: the latitude of the location self.latitude = 51.509865 #:float: the longitue of the location self.longitude = -0.118092 def from_json(self, js): super().from_json(js) self.city = js["city"] self.latitude = js["latitude"] self.longitude = js["longitude"] def __str__(self): return "city({}) latitude({}) longitude({})".format( self.city, self.latitude, self.longitude ) class Client(HomeMaticIPObject): """A client is an app which has access to the access point. e.g. smartphone, 3th party apps, google home, conrad connect """ def __init__(self, connection): super().__init__(connection) #:str: the unique id of the client self.id = "" #:str: a human understandable name of the client self.label = "" #:str: the home where the client belongs to self.homeId = "" #:str: the c2c service name self.c2cServiceIdentifier = "" #:ClientType: the type of this client self.clientType = ClientType.APP def from_json(self, js): super().from_json(js) self.id = js["id"] self.label = js["label"] self.homeId = js["homeId"] self.clientType = ClientType.from_str(js["clientType"]) if "c2cServiceIdentifier" in js: self.c2cServiceIdentifier = js["c2cServiceIdentifier"] def __str__(self): return "label({})".format(self.label) class OAuthOTK(HomeMaticIPObject): def __init__(self, connection): super().__init__(connection) self.authToken = None self.expirationTimestamp = None def from_json(self, js): super().from_json(js) self.authToken = js["authToken"] self.expirationTimestamp = self.fromtimestamp(js["expirationTimestamp"]) class AccessPointUpdateState(HomeMaticIPObject): def __init__(self, connection): super().__init__(connection) self.accessPointUpdateState = DeviceUpdateState.UP_TO_DATE self.successfulUpdateTimestamp = None self.updateStateChangedTimestamp = None def from_json(self, js): self.accessPointUpdateState = js["accessPointUpdateState"] self.successfulUpdateTimestamp = self.fromtimestamp( js["successfulUpdateTimestamp"] ) self.updateStateChangedTimestamp = self.fromtimestamp( js["updateStateChangedTimestamp"] ) class Home(HomeMaticIPObject): """this class represents the 'Home' of the homematic ip""" _typeClassMap = TYPE_CLASS_MAP _typeGroupMap = TYPE_GROUP_MAP _typeSecurityEventMap = TYPE_SECURITY_EVENT_MAP _typeRuleMap = TYPE_RULE_MAP _typeFunctionalHomeMap = TYPE_FUNCTIONALHOME_MAP def __init__(self, connection=None): if connection is None: connection = Connection() super().__init__(connection) # List with create handlers. self._on_create = [] self.apExchangeClientId = None self.apExchangeState = ApExchangeState.NONE self.availableAPVersion = None self.carrierSense = None #:bool:displays if the access point is connected to the hmip cloud or # not self.connected = None #:str:the current version of the access point self.currentAPVersion = None self.deviceUpdateStrategy = DeviceUpdateStrategy.MANUALLY self.dutyCycle = None #:str:the SGTIN of the access point self.id = None self.lastReadyForUpdateTimestamp = None #:Location:the location of the AP self.location = None #:bool:determines if a pin is set on this access point self.pinAssigned = None self.powerMeterCurrency = None self.powerMeterUnitPrice = None self.timeZoneId = None self.updateState = HomeUpdateState.UP_TO_DATE #:Weather:the current weather self.weather = None self.__webSocket = None self.__webSocketThread = None self.onEvent = EventHook() self.onWsError = EventHook() #:bool:switch to enable/disable automatic reconnection of the websocket (default=True) self.websocket_reconnect_on_error = True #:List[Device]: a collection of all devices in home self.devices = [] #:List[Client]: a collection of all clients in home self.clients = [] #:List[Group]: a collection of all groups in the home self.groups = [] #:List[Rule]: a collection of all rules in the home self.rules = [] #: a collection of all functionalHomes in the home self.functionalHomes = [] #:Map: a map of all access points and their updateStates self.accessPointUpdateStates = {} def init(self, access_point_id, lookup=True): self._connection.init(access_point_id, lookup) def set_auth_token(self, auth_token): self._connection.set_auth_token(auth_token) def from_json(self, js_home): super().from_json(js_home) self.weather = Weather(self._connection) self.weather.from_json(js_home["weather"]) if js_home["location"] != None: self.location = Location(self._connection) self.location.from_json(js_home["location"]) self.connected = js_home["connected"] self.currentAPVersion = js_home["currentAPVersion"] self.availableAPVersion = js_home["availableAPVersion"] self.timeZoneId = js_home["timeZoneId"] self.pinAssigned = js_home["pinAssigned"] self.dutyCycle = js_home["dutyCycle"] self.updateState = HomeUpdateState.from_str(js_home["updateState"]) self.powerMeterUnitPrice = js_home["powerMeterUnitPrice"] self.powerMeterCurrency = js_home["powerMeterCurrency"] self.deviceUpdateStrategy = DeviceUpdateStrategy.from_str( js_home["deviceUpdateStrategy"] ) self.lastReadyForUpdateTimestamp = js_home["lastReadyForUpdateTimestamp"] self.apExchangeClientId = js_home["apExchangeClientId"] self.apExchangeState = ApExchangeState.from_str(js_home["apExchangeState"]) self.id = js_home["id"] self.carrierSense = js_home["carrierSense"] for ap, state in js_home["accessPointUpdateStates"].items(): ap_state = AccessPointUpdateState(self._connection) ap_state.from_json(state) self.accessPointUpdateStates[ap] = ap_state self._get_rules(js_home) def on_create(self, handler): """Adds an event handler to the create method. Fires when a device is created.""" self._on_create.append(handler) def fire_create_event(self, *args, **kwargs): """Trigger the method tied to _on_create""" for _handler in self._on_create: _handler(*args, **kwargs) def remove_callback(self, handler): """Remove event handler.""" super().remove_callback(handler) if handler in self._on_create: self._on_create.remove(handler) def download_configuration(self) -> str: """downloads the current configuration from the cloud Returns the downloaded configuration or an errorCode """ return self._restCall( "home/getCurrentState", json.dumps(self._connection.clientCharacteristics) ) def get_current_state(self, clearConfig: bool = False): """downloads the current configuration and parses it into self Args: clearConfig(bool): if set to true, this function will remove all old objects from self.devices, self.client, ... to have a fresh config instead of reparsing them """ json_state = self.download_configuration() return self.update_home(json_state, clearConfig) def update_home(self, json_state, clearConfig: bool = False): """parse a given json configuration into self. This will update the whole home including devices, clients and groups. Args: clearConfig(bool): if set to true, this function will remove all old objects from self.devices, self.client, ... to have a fresh config instead of reparsing them """ if "errorCode" in json_state: LOGGER.error( "Could not get the current configuration. Error: %s", json_state["errorCode"], ) return False if clearConfig: self.devices = [] self.clients = [] self.groups = [] self._get_devices(json_state) self._get_clients(json_state) self._get_groups(json_state) self._load_functionalChannels() js_home = json_state["home"] return self.update_home_only(js_home, clearConfig) def update_home_only(self, js_home, clearConfig: bool = False): """parse a given home json configuration into self. This will update only the home without updating devices, clients and groups. Args: clearConfig(bool): if set to true, this function will remove all old objects from self.devices, self.client, ... to have a fresh config instead of reparsing them """ if "errorCode" in js_home: LOGGER.error( "Could not get the current configuration. Error: %s", js_home["errorCode"], ) return False if clearConfig: self.rules = [] self.functionalHomes = [] self.from_json(js_home) self._get_functionalHomes(js_home) return True def _get_devices(self, json_state): self.devices = [x for x in self.devices if x.id in json_state["devices"].keys()] for id_, raw in json_state["devices"].items(): _device = self.search_device_by_id(id_) if _device: _device.from_json(raw) else: self.devices.append(self._parse_device(raw)) def _parse_device(self, json_state): try: deviceType = DeviceType.from_str(json_state["type"]) d = self._typeClassMap[deviceType](self._connection) d.from_json(json_state) return d except: d = self._typeClassMap[DeviceType.DEVICE](self._connection) d.from_json(json_state) LOGGER.warning("There is no class for device '%s' yet", json_state["type"]) return d def _get_rules(self, json_state): self.rules = [ x for x in self.rules if x.id in json_state["ruleMetaDatas"].keys() ] for id_, raw in json_state["ruleMetaDatas"].items(): _rule = self.search_rule_by_id(id_) if _rule: _rule.from_json(raw) else: self.rules.append(self._parse_rule(raw)) def _parse_rule(self, json_state): try: ruleType = AutomationRuleType.from_str(json_state["type"]) r = self._typeRuleMap[ruleType](self._connection) r.from_json(json_state) return r except: r = Rule(self._connection) r.from_json(json_state) LOGGER.warning("There is no class for rule '%s' yet", json_state["type"]) return r def _get_clients(self, json_state): self.clients = [x for x in self.clients if x.id in json_state["clients"].keys()] for id_, raw in json_state["clients"].items(): _client = self.search_client_by_id(id_) if _client: _client.from_json(raw) else: c = Client(self._connection) c.from_json(raw) self.clients.append(c) def _parse_group(self, json_state): g = None if json_state["type"] == "META": g = MetaGroup(self._connection) g.from_json(json_state, self.devices, self.groups) else: try: groupType = GroupType.from_str(json_state["type"]) g = self._typeGroupMap[groupType](self._connection) g.from_json(json_state, self.devices) except: g = self._typeGroupMap[GroupType.GROUP](self._connection) g.from_json(json_state, self.devices) LOGGER.warning( "There is no class for group '%s' yet", json_state["type"] ) return g def _get_groups(self, json_state): self.groups = [x for x in self.groups if x.id in json_state["groups"].keys()] metaGroups = [] for id_, raw in json_state["groups"].items(): _group = self.search_group_by_id(id_) if _group: if isinstance(_group, MetaGroup): _group.from_json(raw, self.devices, self.groups) else: _group.from_json(raw, self.devices) else: group_type = raw["type"] if group_type == "META": metaGroups.append(raw) else: self.groups.append(self._parse_group(raw)) for mg in metaGroups: self.groups.append(self._parse_group(mg)) def _get_functionalHomes(self, json_state): for solution, functionalHome in json_state["functionalHomes"].items(): try: solutionType = FunctionalHomeType.from_str(solution) h = None for fh in self.functionalHomes: if fh.solution == solution: h = fh break if h is None: h = self._typeFunctionalHomeMap[solutionType](self._connection) self.functionalHomes.append(h) h.from_json(functionalHome, self.groups) except: h = FunctionalHome(self._connection) h.from_json(functionalHome, self.groups) LOGGER.warning( "There is no class for functionalHome '%s' yet", solution ) self.functionalHomes.append(h) def _load_functionalChannels(self): for d in self.devices: d.load_functionalChannels(self.groups) def get_functionalHome(self, functionalHomeType: type) -> FunctionalHome: """ gets the specified functionalHome Args: functionalHome(type): the type of the functionalHome which should be returned Returns: the FunctionalHome or None if it couldn't be found """ for x in self.functionalHomes: if isinstance(x, functionalHomeType): return x return None def search_device_by_id(self, deviceID) -> Device: """ searches a device by given id Args: deviceID(str): the device to search for Returns the Device object or None if it couldn't find a device """ for d in self.devices: if d.id == deviceID: return d return None def search_group_by_id(self, groupID) -> Group: """ searches a group by given id Args: groupID(str): groupID the group to search for Returns the group object or None if it couldn't find a group """ for g in self.groups: if g.id == groupID: return g return None def search_client_by_id(self, clientID) -> Client: """ searches a client by given id Args: clientID(str): the client to search for Returns the client object or None if it couldn't find a client """ for c in self.clients: if c.id == clientID: return c return None def search_rule_by_id(self, ruleID) -> Rule: """ searches a rule by given id Args: ruleID(str): the rule to search for Returns the rule object or None if it couldn't find a rule """ for r in self.rules: if r.id == ruleID: return r return None def get_security_zones_activation(self) -> (bool, bool): """ returns the value of the security zones if they are armed or not Returns internal True if the internal zone is armed external True if the external zone is armed """ internal_active = False external_active = False for g in self.groups: if isinstance(g, SecurityZoneGroup): if g.label == "EXTERNAL": external_active = g.active elif g.label == "INTERNAL": internal_active = g.active return internal_active, external_active def set_security_zones_activation(self, internal=True, external=True): """ this function will set the alarm system to armed or disable it Args: internal(bool): activates/deactivates the internal zone external(bool): activates/deactivates the external zone Examples: arming while being at home >>> home.set_security_zones_activation(False,True) arming without being at home >>> home.set_security_zones_activation(True,True) disarming the alarm system >>> home.set_security_zones_activation(False,False) """ data = {"zonesActivation": {"EXTERNAL": external, "INTERNAL": internal}} return self._restCall("home/security/setZonesActivation", json.dumps(data)) def set_location(self, city, latitude, longitude): data = {"city": city, "latitude": latitude, "longitude": longitude} return self._restCall("home/setLocation", json.dumps(data)) def set_intrusion_alert_through_smoke_detectors(self, activate: bool = True): """ activate or deactivate if smoke detectors should "ring" during an alarm Args: activate(bool): True will let the smoke detectors "ring" during an alarm """ data = {"intrusionAlertThroughSmokeDetectors": activate} return self._restCall( "home/security/setIntrusionAlertThroughSmokeDetectors", json.dumps(data) ) def activate_absence_with_period(self, endtime: datetime): """ activates the absence mode until the given time Args: endtime(datetime): the time when the absence should automatically be disabled """ data = {"endTime": endtime.strftime("%Y_%m_%d %H:%M")} return self._restCall( "home/heating/activateAbsenceWithPeriod", json.dumps(data) ) def activate_absence_permanent(self): """ activates the absence forever """ return self._restCall("home/heating/activateAbsencePermanent") def activate_absence_with_duration(self, duration: int): """ activates the absence mode for a given time Args: duration(int): the absence duration in minutes """ data = {"duration": duration} return self._restCall( "home/heating/activateAbsenceWithDuration", json.dumps(data) ) def deactivate_absence(self): """ deactivates the absence mode immediately""" return self._restCall("home/heating/deactivateAbsence") def activate_vacation(self, endtime: datetime, temperature: float): """ activates the vatation mode until the given time Args: endtime(datetime): the time when the vatation mode should automatically be disabled temperature(float): the settemperature during the vacation mode """ data = { "endTime": endtime.strftime("%Y_%m_%d %H:%M"), "temperature": temperature, } return self._restCall("home/heating/activateVacation", json.dumps(data)) def deactivate_vacation(self): """ deactivates the vacation mode immediately""" return self._restCall("home/heating/deactivateVacation") def set_pin(self, newPin: str, oldPin: str = None) -> dict: """ sets a new pin for the home Args: newPin(str): the new pin oldPin(str): optional, if there is currently a pin active it must be given here. Otherwise it will not be possible to set the new pin Returns: the result of the call """ if newPin is None: newPin = "" data = {"pin": newPin} if oldPin: self._connection.headers["PIN"] = str(oldPin) result = self._restCall("home/setPin", body=json.dumps(data)) if oldPin: del self._connection.headers["PIN"] return result def set_zone_activation_delay(self, delay): data = {"zoneActivationDelay": delay} return self._restCall( "home/security/setZoneActivationDelay", body=json.dumps(data) ) def get_security_journal(self): journal = self._restCall("home/security/getSecurityJournal") if "errorCode" in journal: LOGGER.error( "Could not get the security journal. Error: %s", journal["errorCode"] ) return None ret = [] for entry in journal["entries"]: try: eventType = SecurityEventType(entry["eventType"]) if eventType in self._typeSecurityEventMap: j = self._typeSecurityEventMap[eventType](self._connection) except: j = SecurityEvent(self._connection) LOGGER.warning("There is no class for %s yet", entry["eventType"]) j.from_json(entry) ret.append(j) return ret def delete_group(self, group: Group): """deletes the given group from the cloud Args: group(Group):the group to delete """ return group.delete() def get_OAuth_OTK(self): token = OAuthOTK(self._connection) token.from_json(self._restCall("home/getOAuthOTK")) return token def set_timezone(self, timezone: str): """ sets the timezone for the AP. e.g. "Europe/Berlin" Args: timezone(str): the new timezone """ data = {"timezoneId": timezone} return self._restCall("home/setTimezone", body=json.dumps(data)) def set_powermeter_unit_price(self, price): data = {"powerMeterUnitPrice": price} return self._restCall("home/setPowerMeterUnitPrice", body=json.dumps(data)) def set_zones_device_assignment(self, internal_devices, external_devices) -> dict: """ sets the devices for the security zones Args: internal_devices(List[Device]): the devices which should be used for the internal zone external_devices(List[Device]): the devices which should be used for the external(hull) zone Returns: the result of _restCall """ internal = [x.id for x in internal_devices] external = [x.id for x in external_devices] data = {"zonesDeviceAssignment": {"INTERNAL": internal, "EXTERNAL": external}} return self._restCall( "home/security/setZonesDeviceAssignment", body=json.dumps(data) ) def start_inclusion(self, deviceId): """ start inclusion mode for specific device Args: deviceId: sgtin of device """ data = {"deviceId": deviceId} return self._restCall("home/startInclusionModeForDevice", body=json.dumps(data)) def enable_events(self, enable_trace=False, ping_interval=20): websocket.enableTrace(enable_trace) self.__webSocket = websocket.WebSocketApp( self._connection.urlWebSocket, header=[ "AUTHTOKEN: {}".format(self._connection.auth_token), "CLIENTAUTH: {}".format(self._connection.clientauth_token), ], on_message=self._ws_on_message, on_error=self._ws_on_error, on_close=self._ws_on_close, ) websocket_kwargs = {"ping_interval": ping_interval} if hasattr(sys, "_called_from_test"): # disable ssl during a test run sslopt = {"cert_reqs": ssl.CERT_NONE} websocket_kwargs = {"sslopt": sslopt, "ping_interval": 2, "ping_timeout": 1} self.__webSocketThread = threading.Thread( name="hmip-websocket", target=self.__webSocket.run_forever, kwargs=websocket_kwargs, ) self.__webSocketThread.daemon = True self.__webSocketThread.start() def disable_events(self): if self.__webSocket: self.__webSocket.close() self.__webSocket = None def _ws_on_close(self, *_): self.__webSocket = None def _ws_on_error(self, _, err): LOGGER.exception(err) self.onWsError.fire(err) if self.websocket_reconnect_on_error: logger.debug("Trying to reconnect websocket") self.disable_events() self.enable_events() def _ws_on_message(self, _, message): # json.loads doesn't support bytes as parameter before python 3.6 js = json.loads(bytes2str(message)) # LOGGER.debug(js) eventList = [] for event in js["events"].values(): try: pushEventType = EventType(event["pushEventType"]) LOGGER.debug(pushEventType) obj = None if pushEventType == EventType.GROUP_CHANGED: data = event["group"] obj = self.search_group_by_id(data["id"]) if obj is None: obj = self._parse_group(data) self.groups.append(obj) pushEventType = EventType.GROUP_ADDED self.fire_create_event(obj, event_type=pushEventType, obj=obj) if type(obj) is MetaGroup: obj.from_json(data, self.devices, self.groups) else: obj.from_json(data, self.devices) obj.fire_update_event(data, event_type=pushEventType, obj=obj) elif pushEventType == EventType.HOME_CHANGED: data = event["home"] obj = self obj.update_home_only(data) obj.fire_update_event(data, event_type=pushEventType, obj=obj) elif pushEventType == EventType.CLIENT_ADDED: data = event["client"] obj = Client(self._connection) obj.from_json(data) self.clients.append(obj) elif pushEventType == EventType.CLIENT_CHANGED: data = event["client"] obj = self.search_client_by_id(data["id"]) obj.from_json(data) elif pushEventType == EventType.CLIENT_REMOVED: obj = self.search_client_by_id(event["id"]) self.clients.remove(obj) elif pushEventType == EventType.DEVICE_ADDED: data = event["device"] obj = self._parse_device(data) obj.load_functionalChannels(self.groups) self.devices.append(obj) self.fire_create_event(data, event_type=pushEventType, obj=obj) elif pushEventType == EventType.DEVICE_CHANGED: data = event["device"] obj = self.search_device_by_id(data["id"]) if obj is None: # no DEVICE_ADDED Event? obj = self._parse_device(data) self.devices.append(obj) pushEventType = EventType.DEVICE_ADDED self.fire_create_event(data, event_type=pushEventType, obj=obj) else: obj.from_json(data) obj.load_functionalChannels(self.groups) obj.fire_update_event(data, event_type=pushEventType, obj=obj) elif pushEventType == EventType.DEVICE_REMOVED: obj = self.search_device_by_id(event["id"]) obj.fire_remove_event(obj, event_type=pushEventType, obj=obj) self.devices.remove(obj) elif pushEventType == EventType.GROUP_REMOVED: obj = self.search_group_by_id(event["id"]) obj.fire_remove_event(obj, event_type=pushEventType, obj=obj) self.groups.remove(obj) elif pushEventType == EventType.GROUP_ADDED: group = event["group"] obj = self._parse_group(group) self.groups.append(obj) self.fire_create_event(obj, event_type=pushEventType, obj=obj) elif pushEventType == EventType.SECURITY_JOURNAL_CHANGED: pass # data is just none so nothing to do here # TODO: implement INCLUSION_REQUESTED, NONE eventList.append({"eventType": pushEventType, "data": obj}) except ValueError as valerr: # pragma: no cover LOGGER.warning( "Uknown EventType '%s' Data: %s", event["pushEventType"], event ) except Exception as err: # pragma: no cover LOGGER.exception(err) self.onEvent.fire(eventList)
coreGreenberet/homematicip-rest-api
homematicip/home.py
Python
gpl-3.0
33,503
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using System; using org.bn.attributes; using org.bn.attributes.constraints; using org.bn.coders; using org.bn.types; using org.bn; namespace MMS_ASN1_Model { [ASN1PreparedElement] [ASN1Null ( Name = "RemoveEventConditionListReference-Response" )] public class RemoveEventConditionListReference_Response: IASN1PreparedElement { public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(RemoveEventConditionListReference_Response)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } }
rogerz/IEDExplorer
MMS_ASN1_Model/RemoveEventConditionListReference_Response.cs
C#
gpl-3.0
934
class MassExamsController < ApplicationController before_filter :require_teacher def new @mass_exam = MassExam.new end def create @mass_exam = @current_user.mass_exams.build(params[:mass_exam]) if @mass_exam.save flash[:notice] = t("controllers.notice.mass_exam_created") redirect_to new_mass_exam_path else render :new end end end
morgoth/quiz
app/controllers/mass_exams_controller.rb
Ruby
gpl-3.0
382
package org.figis.search.service.util; import org.apache.deltaspike.core.util.StringUtils; import org.fao.fi.factsheetwebservice.domain.FactsheetDomain; import org.figis.search.config.ref.FigisSearchException; public class FactsheetId { private FactsheetDomain domain; private String factsheet; private String lang; public FactsheetId domain(FactsheetDomain domain) { this.domain = domain; return this; } public FactsheetId factsheet(String factsheet) { this.factsheet = factsheet; return this; } public FactsheetId lang(String lang) { this.lang = lang; return this; } public String compose() { if (domain == null || StringUtils.isEmpty(factsheet) || StringUtils.isEmpty(lang)) { throw new FigisSearchException("All domain, factsheet and lang must be filled"); } return domain + "-" + factsheet + "-" + lang; } }
openfigis/figis-search
figis-search-service/src/main/java/org/figis/search/service/util/FactsheetId.java
Java
gpl-3.0
853
/* * Copyright (c) 2016 by VIAE (http///viae-it.com) */ package com.viae.maven.sonar.exceptions; /** * Exception to be thrown when something goes wrong when handling git processes. * * Created by Vandeperre Maarten on 05/05/2016. */ public class GitException extends Exception { private static final String GIT_ERROR_MESSAGE = "Something went wrong while executing GIT command, verify that git is installed properly on the system"; public GitException(final Exception cause){ super(GIT_ERROR_MESSAGE, cause); } }
VandeperreMaarten/sonar-maven-plugin
src/main/java/com/viae/maven/sonar/exceptions/GitException.java
Java
gpl-3.0
543
<?php // Heading $_['heading_title'] = 'Informações da conta'; // Text $_['text_account'] = 'Minha conta'; $_['text_edit'] = 'Informações da conta'; $_['text_your_details'] = 'Caso deseje, modifique as informações da sua conta'; $_['text_success'] = 'As informações da sua conta foram modificadas.'; // Entry $_['entry_firstname'] = 'Nome'; $_['entry_lastname'] = 'Sobrenome'; $_['entry_email'] = 'E-mail'; $_['entry_telephone'] = 'Telefone'; // Error $_['error_exists'] = 'Atenção: Este e-mail já está cadastrado.'; $_['error_firstname'] = 'O nome deve ter entre 1 e 32 caracteres.'; $_['error_lastname'] = 'O sobrenome deve entre 1 e 32 caracteres.'; $_['error_email'] = 'O e-mail não é válido.'; $_['error_telephone'] = 'O telefone deve ter entre 10 e 11 números.'; $_['error_custom_field'] = 'O campo %s é obrigatório.';
opencartbrasil/traducao
upload/catalog/language/pt-br/account/edit.php
PHP
gpl-3.0
912
using System; namespace Editor_Mono.Cecil.Metadata { internal struct TableInformation { public uint Offset; public uint Length; public uint RowSize; } }
lichunlincn/cshotfix
CSHotFix_SimpleFramework/Assets/CSHotFixLibaray/Editor/Injector/MonoCecil/Mono.Cecil.Metadata/TableInformation.cs
C#
gpl-3.0
172
module Kddev class Project class << self def list `ls #{ PATH }` end def find(name) project = new(name) project.exists? ? project : nil end def find!(name) project = find(name) raise "Unknown project #{ name }" if project.nil? project end end attr_reader :name def initialize(name) @name = name end def path File.join(File.expand_path(PATH), name) end def exists? File.exists?(path) end def subpath(p) File.join(path, p) end def subpath?(p) File.exists?(subpath(p)) end def subpath!(p) File.exists?(subpath(p)) ? File.join(path, p) : nil end end end
atd/kddev
kddev/project.rb
Ruby
gpl-3.0
760
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; using Questionnaires.Core.Services.Models; using System.Text; namespace Questionnaires.Web.Helpers { /// <summary> /// This class is tightly coupled to the partial views for answeroptions as it seeks the control ids /// </summary> public class QuestionReader { public const string Delimiter = ":"; public const string Prefix = "qid"; private static readonly IDictionary<AnswerOption.OptionType, IValueReader> Implementations = new Dictionary<AnswerOption.OptionType, IValueReader> { { AnswerOption.OptionType.radio, new RadioReader() }, { AnswerOption.OptionType.check, new CheckBoxReader()}, {AnswerOption.OptionType.checkunique, new CheckBoxReader()} }; public static IList<Answer> Read(IEnumerable<QuestionSetPageItem> questions, IDictionary<string, string> formCollection, string operatorID) { List<Answer> answers = new List<Answer>(); foreach (var item in questions) answers.AddRange(ReadQuestion(item, formCollection)); foreach (var answer in answers) answer.OperatorID = operatorID; return answers; } public static IEnumerable< Answer> ReadQuestion(QuestionSetPageItem question, IDictionary<string, string> formCollection) { var keys = (from k in formCollection.Keys where k.Contains(string.Format("{0}{1}{2}{3}",Prefix , Delimiter , question.QuestionID.ToString(CultureInfo.InvariantCulture) , Delimiter)) select k); if (keys.Count() == 0 && question.Question.Required) throw new KeyNotFoundException(string.Format("Missing answer to question {0}", question.QuestionID)); List<Answer> answerList = new List<Answer>(); //ToDo: validate we dont have duplicates for types other than OptionType.check foreach (var key in keys) { //get the answer type string[] vals = key.Split(new string[] { Delimiter },StringSplitOptions.None); AnswerOption.OptionType answerType; if(!Enum.TryParse(vals[2], out answerType)) throw new KeyNotFoundException(string.Format("Missing answerOptionType to question {0}", question.QuestionID)); //read the answer answerList.AddRange(GetValueReader(answerType).Read(question, key, formCollection)); } return answerList; } public static IValueReader GetValueReader(AnswerOption.OptionType type) { if(Implementations.ContainsKey(type)) { return Implementations[type]; } else { return new DefaultReader(type); } } /// <summary> /// Creates a name attribute for AnswerOption items /// </summary> /// <param name="model"></param> /// <returns></returns> public static string CreateName(AnswerOption model) { StringBuilder sb = new StringBuilder(); sb.Append(Prefix); sb.Append(Delimiter); sb.Append(model.QuestionID.ToString(CultureInfo.InvariantCulture)); sb.Append(Delimiter); sb.Append(model.Type.ToString()); return sb.ToString(); } public static string CreateName(QuestionSetPageItem model) { StringBuilder sb = new StringBuilder(); sb.Append(Prefix); sb.Append(Delimiter); sb.Append(model.QuestionID.ToString(CultureInfo.InvariantCulture)); return sb.ToString(); } } }
Healthlines/Healthlines-Applications
Source/ElephantParade.Web/Areas/Advisor/Helpers/QuestionReader.cs
C#
gpl-3.0
4,393
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using GitCommands; using GitExtUtils.GitUI; using GitExtUtils.GitUI.Theming; using GitUI.Editor.Diff; using GitUI.Theming; using ICSharpCode.TextEditor; using ICSharpCode.TextEditor.Document; using JetBrains.Annotations; namespace GitUI.Editor { public partial class FileViewerInternal : GitModuleControl, IFileViewer { /// <summary> /// Raised when the Escape key is pressed (and only when no selection exists, as the default behaviour of escape is to clear the selection). /// </summary> public event Action EscapePressed; public event EventHandler<SelectedLineEventArgs> SelectedLineChanged; public new event MouseEventHandler MouseMove; public new event EventHandler MouseEnter; public new event EventHandler MouseLeave; public new event System.Windows.Forms.KeyEventHandler KeyUp; public new event EventHandler DoubleClick; private readonly FindAndReplaceForm _findAndReplaceForm = new(); private readonly CurrentViewPositionCache _currentViewPositionCache; private DiffViewerLineNumberControl _lineNumbersControl; private DiffHighlightService _diffHighlightService = DiffHighlightService.Instance; private bool _shouldScrollToTop = false; private bool _shouldScrollToBottom = false; private readonly int _bottomBlankHeight = DpiUtil.Scale(300); private ContinuousScrollEventManager _continuousScrollEventManager; private BlameAuthorMargin _authorsAvatarMargin; private bool _showGutterAvatars; public FileViewerInternal() { InitializeComponent(); InitializeComplete(); Disposed += (sender, e) => { //// _diffHighlightService not disposable //// _lineNumbersControl not disposable //// _currentViewPositionCache not disposable _findAndReplaceForm.Dispose(); }; _currentViewPositionCache = new CurrentViewPositionCache(this); TextEditor.ActiveTextAreaControl.TextArea.SelectionManager.SelectionChanged += SelectionManagerSelectionChanged; TextEditor.ActiveTextAreaControl.TextArea.PreviewKeyDown += (s, e) => { if (e.KeyCode == Keys.Escape && !TextEditor.ActiveTextAreaControl.SelectionManager.HasSomethingSelected) { EscapePressed?.Invoke(); } }; TextEditor.TextChanged += (s, e) => TextChanged?.Invoke(s, e); TextEditor.ActiveTextAreaControl.HScrollBar.ValueChanged += (s, e) => OnHScrollPositionChanged(EventArgs.Empty); TextEditor.ActiveTextAreaControl.VScrollBar.ValueChanged += (s, e) => OnVScrollPositionChanged(EventArgs.Empty); TextEditor.ActiveTextAreaControl.TextArea.KeyUp += (s, e) => KeyUp?.Invoke(s, e); TextEditor.ActiveTextAreaControl.TextArea.DoubleClick += (s, e) => DoubleClick?.Invoke(s, e); TextEditor.ActiveTextAreaControl.TextArea.MouseMove += (s, e) => MouseMove?.Invoke(s, e); TextEditor.ActiveTextAreaControl.TextArea.MouseEnter += (s, e) => MouseEnter?.Invoke(s, e); TextEditor.ActiveTextAreaControl.TextArea.MouseLeave += (s, e) => MouseLeave?.Invoke(s, e); TextEditor.ActiveTextAreaControl.TextArea.MouseDown += (s, e) => { SelectedLineChanged?.Invoke( this, new SelectedLineEventArgs( TextEditor.ActiveTextAreaControl.TextArea.TextView.GetLogicalLine(e.Y))); }; TextEditor.ActiveTextAreaControl.TextArea.MouseWheel += TextArea_MouseWheel; HighlightingManager.Manager.DefaultHighlighting.SetColorFor("LineNumbers", new HighlightColor(SystemColors.ControlText, SystemColors.Control, false, false)); TextEditor.ActiveTextAreaControl.TextEditorProperties.EnableFolding = false; _lineNumbersControl = new DiffViewerLineNumberControl(TextEditor.ActiveTextAreaControl.TextArea); VRulerPosition = AppSettings.DiffVerticalRulerPosition; } public void SetContinuousScrollManager(ContinuousScrollEventManager continuousScrollEventManager) { _continuousScrollEventManager = continuousScrollEventManager; } private void SelectionManagerSelectionChanged(object sender, EventArgs e) { string text = TextEditor.ActiveTextAreaControl.TextArea.SelectionManager.SelectedText; TextEditor.Document.MarkerStrategy.RemoveAll(m => true); IList<TextMarker> selectionMarkers = GetTextMarkersMatchingWord(text); foreach (var selectionMarker in selectionMarkers) { TextEditor.Document.MarkerStrategy.AddMarker(selectionMarker); } _diffHighlightService.AddPatchHighlighting(TextEditor.Document); TextEditor.ActiveTextAreaControl.TextArea.Invalidate(); } /// <summary> /// Create a list of TextMarker instances in the Document that match the given text /// </summary> /// <param name="word">The text to match.</param> [NotNull] private IList<TextMarker> GetTextMarkersMatchingWord(string word) { if (string.IsNullOrWhiteSpace(word)) { return Array.Empty<TextMarker>(); } var selectionMarkers = new List<TextMarker>(); string textContent = TextEditor.Document.TextContent; int indexMatch = -1; do { indexMatch = textContent.IndexOf(word, indexMatch + 1, StringComparison.OrdinalIgnoreCase); if (indexMatch >= 0) { Color highlightColor = AppColor.HighlightAllOccurences.GetThemeColor(); var textMarker = new TextMarker(indexMatch, word.Length, TextMarkerType.SolidBlock, highlightColor, ColorHelper.GetForeColorForBackColor(highlightColor)); selectionMarkers.Add(textMarker); } } while (indexMatch >= 0 && indexMatch < textContent.Length - 1); return selectionMarkers; } public new Font Font { get => TextEditor.Font; set => TextEditor.Font = value; } public Action OpenWithDifftool { get; private set; } /// <summary> /// Move the file viewer cursor position to the next TextMarker found in the document that matches the AppColor.HighlightAllOccurences/> /// </summary> public void GoToNextOccurrence() { int offset = TextEditor.ActiveTextAreaControl.TextArea.Caret.Offset; List<TextMarker> markers = TextEditor.Document.MarkerStrategy.GetMarkers(offset, TextEditor.Document.TextLength - offset); TextMarker marker = markers.FirstOrDefault(x => x.Offset > offset && x.Color == AppColor.HighlightAllOccurences.GetThemeColor()); if (marker is not null) { TextLocation position = TextEditor.ActiveTextAreaControl.TextArea.Document.OffsetToPosition(marker.Offset); TextEditor.ActiveTextAreaControl.Caret.Position = position; } } /// <summary> /// Move the file viewer cursor position to the previous TextMarker found in the document that matches the AppColor.HighlightAllOccurences/> /// </summary> public void GoToPreviousOccurrence() { int offset = TextEditor.ActiveTextAreaControl.TextArea.Caret.Offset; List<TextMarker> markers = TextEditor.Document.MarkerStrategy.GetMarkers(0, offset); TextMarker marker = markers.LastOrDefault(x => x.Offset < offset && x.Color == AppColor.HighlightAllOccurences.GetThemeColor()); if (marker is not null) { TextLocation position = TextEditor.ActiveTextAreaControl.TextArea.Document.OffsetToPosition(marker.Offset); TextEditor.ActiveTextAreaControl.Caret.Position = position; } } public void Find() { _findAndReplaceForm.ShowFor(TextEditor, false); OnVScrollPositionChanged(EventArgs.Empty); } public async Task FindNextAsync(bool searchForwardOrOpenWithDifftool) { if (searchForwardOrOpenWithDifftool && OpenWithDifftool is not null && string.IsNullOrEmpty(_findAndReplaceForm.LookFor)) { OpenWithDifftool.Invoke(); return; } await _findAndReplaceForm.FindNextAsync(viaF3: true, !searchForwardOrOpenWithDifftool, "Text not found"); OnVScrollPositionChanged(EventArgs.Empty); } #region IFileViewer Members public event EventHandler HScrollPositionChanged; public event EventHandler VScrollPositionChanged; public new event EventHandler TextChanged; public void ScrollToTop() { _shouldScrollToTop = true; } public void ScrollToBottom() { _shouldScrollToBottom = true; } public string GetText() { return TextEditor.Text; } public bool? ShowLineNumbers { get; set; } public void SetText(string text, Action openWithDifftool, bool isDiff = false) { SetText(text, openWithDifftool, isDiff, false); } public void SetText(string text, Action openWithDifftool, bool isDiff, bool isRangeDiff) { _currentViewPositionCache.Capture(); OpenWithDifftool = openWithDifftool; _lineNumbersControl.Clear(isDiff && !isRangeDiff); _lineNumbersControl.SetVisibility(isDiff && !isRangeDiff); if (isDiff) { var index = TextEditor.ActiveTextAreaControl.TextArea.LeftMargins.IndexOf(_lineNumbersControl); if (index == -1) { TextEditor.ActiveTextAreaControl.TextArea.InsertLeftMargin(0, _lineNumbersControl); } _diffHighlightService = isRangeDiff ? RangeDiffHighlightService.Instance : DiffHighlightService.IsCombinedDiff(text) ? CombinedDiffHighlightService.Instance : DiffHighlightService.Instance; if (!isRangeDiff) { _lineNumbersControl.DisplayLineNumFor(text); } } TextEditor.Text = text; // important to set after the text was changed // otherwise the may be rendering artifacts as noted in #5568 TextEditor.ShowLineNumbers = ShowLineNumbers ?? !isDiff; if (ShowLineNumbers.HasValue && !ShowLineNumbers.Value) { Padding = new Padding(DpiUtil.Scale(5), Padding.Top, Padding.Right, Padding.Bottom); } TextEditor.Refresh(); _currentViewPositionCache.Restore(isDiff); if (_shouldScrollToBottom || _shouldScrollToTop) { var scrollBar = TextEditor.ActiveTextAreaControl.VScrollBar; if (scrollBar.Visible) { scrollBar.Value = _shouldScrollToTop ? 0 : Math.Max(0, scrollBar.Maximum - scrollBar.Height - _bottomBlankHeight); } _shouldScrollToTop = false; _shouldScrollToBottom = false; } } protected override void OnPaintBackground(PaintEventArgs e) { if (ShowLineNumbers.HasValue && !ShowLineNumbers.Value) { e.Graphics.FillRectangle(SystemBrushes.Window, e.ClipRectangle); } else { base.OnPaintBackground(e); } } public void SetHighlighting(string syntax) => SetHighlightingStrategy(HighlightingStrategyFactory.CreateHighlightingStrategy(syntax)); public void SetHighlightingForFile(string filename) { IHighlightingStrategy highlightingStrategy; if (filename.EndsWith("git-rebase-todo")) { highlightingStrategy = new RebaseTodoHighlightingStrategy(Module); } else if (filename.EndsWith("COMMIT_EDITMSG")) { highlightingStrategy = new CommitMessageHighlightingStrategy(Module); } else { highlightingStrategy = HighlightingManager.Manager.FindHighlighterForFile(filename); } SetHighlightingStrategy(highlightingStrategy); } private void SetHighlightingStrategy(IHighlightingStrategy highlightingStrategy) { TextEditor.Document.HighlightingStrategy = ThemeModule.Settings.UseSystemVisualStyle ? highlightingStrategy : new ThemeBasedHighlighting(highlightingStrategy); TextEditor.Refresh(); } public string GetSelectedText() { return TextEditor.ActiveTextAreaControl.SelectionManager.SelectedText; } public int GetSelectionPosition() { if (TextEditor.ActiveTextAreaControl.SelectionManager.SelectionCollection.Count > 0) { return TextEditor.ActiveTextAreaControl.SelectionManager.SelectionCollection[0].Offset; } return TextEditor.ActiveTextAreaControl.Caret.Offset; } public int GetSelectionLength() { if (TextEditor.ActiveTextAreaControl.SelectionManager.SelectionCollection.Count > 0) { return TextEditor.ActiveTextAreaControl.SelectionManager.SelectionCollection[0].Length; } return 0; } public void EnableScrollBars(bool enable) { TextEditor.ActiveTextAreaControl.VScrollBar.Width = 0; TextEditor.ActiveTextAreaControl.VScrollBar.Visible = enable; TextEditor.ActiveTextAreaControl.TextArea.Dock = DockStyle.Fill; } public void AddPatchHighlighting() { TextEditor.Document.MarkerStrategy.RemoveAll(m => true); _diffHighlightService.AddPatchHighlighting(TextEditor.Document); } public int HScrollPosition { get { return TextEditor.ActiveTextAreaControl.HScrollBar?.Value ?? 0; } set { var scrollBar = TextEditor.ActiveTextAreaControl.HScrollBar; if (scrollBar is null) { return; } int max = scrollBar.Maximum - scrollBar.LargeChange; max = Math.Max(max, scrollBar.Minimum); scrollBar.Value = max > value ? value : max; } } public int VScrollPosition { get { return TextEditor.ActiveTextAreaControl.VScrollBar?.Value ?? 0; } set { var scrollBar = TextEditor.ActiveTextAreaControl.VScrollBar; if (scrollBar is null) { return; } int max = scrollBar.Maximum - scrollBar.LargeChange; max = Math.Max(max, scrollBar.Minimum); scrollBar.Value = max > value ? value : max; } } public bool ShowEOLMarkers { get => TextEditor.ShowEOLMarkers; set => TextEditor.ShowEOLMarkers = value; } public bool ShowSpaces { get => TextEditor.ShowSpaces; set => TextEditor.ShowSpaces = value; } public bool ShowTabs { get => TextEditor.ShowTabs; set => TextEditor.ShowTabs = value; } public int VRulerPosition { get => TextEditor.VRulerRow; set => TextEditor.VRulerRow = value; } public int FirstVisibleLine { get => TextEditor.ActiveTextAreaControl.TextArea.TextView.FirstVisibleLine; set => TextEditor.ActiveTextAreaControl.TextArea.TextView.FirstVisibleLine = value; } public int GetLineFromVisualPosY(int visualPosY) { return TextEditor.ActiveTextAreaControl.TextArea.TextView.GetLogicalLine(visualPosY); } public string GetLineText(int line) { if (line >= TextEditor.Document.TotalNumberOfLines) { return string.Empty; } return TextEditor.Document.GetText(TextEditor.Document.GetLineSegment(line)); } public void GoToLine(int lineNumber) { TextEditor.ActiveTextAreaControl.Caret.Position = new TextLocation(0, GetCaretLine(lineNumber, rightFile: true)); } private int GetCaretLine(int lineNumber, bool rightFile) { if (TextEditor.ShowLineNumbers) { return lineNumber - 1; } else { for (int line = 0; line < TotalNumberOfLines; ++line) { DiffLineInfo diffLineNum = _lineNumbersControl.GetLineInfo(line); if (diffLineNum is not null) { int diffLine = rightFile ? diffLineNum.RightLineNumber : diffLineNum.LeftLineNumber; if (diffLine != DiffLineInfo.NotApplicableLineNum && diffLine >= lineNumber) { return line; } } } } return 0; } public int MaxLineNumber => TextEditor.ShowLineNumbers ? TotalNumberOfLines : _lineNumbersControl.MaxLineNumber; public int LineAtCaret { get => TextEditor.ActiveTextAreaControl.Caret.Position.Line; set => TextEditor.ActiveTextAreaControl.Caret.Position = new TextLocation(TextEditor.ActiveTextAreaControl.Caret.Position.Column, value); } public void HighlightLine(int line, Color color) { _diffHighlightService.HighlightLine(TextEditor.Document, line, color); } public void HighlightLines(int startLine, int endLine, Color color) { _diffHighlightService.HighlightLines(TextEditor.Document, startLine, endLine, color); } public void ClearHighlighting() { var document = TextEditor.Document; document.MarkerStrategy.RemoveAll(t => true); } public int TotalNumberOfLines => TextEditor.Document.TotalNumberOfLines; public bool IsReadOnly { get => TextEditor.IsReadOnly; set => TextEditor.IsReadOnly = value; } public void SetFileLoader(GetNextFileFnc fileLoader) { _findAndReplaceForm.SetFileLoader(fileLoader); } private void TextArea_MouseWheel(object sender, MouseEventArgs e) { var isScrollingTowardTop = e.Delta > 0; var isScrollingTowardBottom = e.Delta < 0; var scrollBar = TextEditor.ActiveTextAreaControl.VScrollBar; if (isScrollingTowardTop && (scrollBar.Value == 0)) { _continuousScrollEventManager?.RaiseTopScrollReached(sender, e); } if (isScrollingTowardBottom && (!scrollBar.Visible || scrollBar.Value + scrollBar.Height > scrollBar.Maximum)) { _continuousScrollEventManager?.RaiseBottomScrollReached(sender, e); } } private void OnHScrollPositionChanged(EventArgs e) { HScrollPositionChanged?.Invoke(this, e); } private void OnVScrollPositionChanged(EventArgs e) { VScrollPositionChanged?.Invoke(this, e); } #endregion public void SetGitBlameGutter(IEnumerable<GitBlameEntry> gitBlameEntries) { if (_showGutterAvatars) { _authorsAvatarMargin.Initialize(gitBlameEntries); } } public bool ShowGutterAvatars { get => _showGutterAvatars; set { _showGutterAvatars = value; if (!_showGutterAvatars) { _authorsAvatarMargin?.SetVisiblity(false); return; } if (_authorsAvatarMargin is null) { _authorsAvatarMargin = new BlameAuthorMargin(TextEditor.ActiveTextAreaControl.TextArea); TextEditor.ActiveTextAreaControl.TextArea.InsertLeftMargin(0, _authorsAvatarMargin); } else { _authorsAvatarMargin.SetVisiblity(true); } } } internal sealed class CurrentViewPositionCache { private readonly FileViewerInternal _viewer; private ViewPosition _currentViewPosition; internal TestAccessor GetTestAccessor() => new TestAccessor(this); public CurrentViewPositionCache(FileViewerInternal viewer) { _viewer = viewer; } public void Capture() { if (_viewer.TotalNumberOfLines <= 1) { return; } // store the previous view position var currentViewPosition = new ViewPosition { ActiveLineNum = null, FirstLine = _viewer.GetLineText(0), TotalNumberOfLines = _viewer.TotalNumberOfLines, CaretPosition = _viewer.TextEditor.ActiveTextAreaControl.Caret.Position, FirstVisibleLine = _viewer.FirstVisibleLine }; currentViewPosition.CaretVisible = currentViewPosition.CaretPosition.Line >= currentViewPosition.FirstVisibleLine && currentViewPosition.CaretPosition.Line < currentViewPosition.FirstVisibleLine + _viewer.TextEditor.ActiveTextAreaControl.TextArea.TextView.VisibleLineCount; if (_viewer.TextEditor.ShowLineNumbers) { // a diff was displayed _currentViewPosition = currentViewPosition; return; } int initialActiveLine = currentViewPosition.CaretVisible ? currentViewPosition.CaretPosition.Line : currentViewPosition.FirstVisibleLine; // search downwards for a code line, i.e. a line with line numbers int activeLine = initialActiveLine; while (activeLine < currentViewPosition.TotalNumberOfLines && currentViewPosition.ActiveLineNum is null) { SetActiveLineNum(activeLine); ++activeLine; } // if none found, search upwards activeLine = initialActiveLine - 1; while (activeLine >= 0 && currentViewPosition.ActiveLineNum is null) { SetActiveLineNum(activeLine); --activeLine; } _currentViewPosition = currentViewPosition; return; void SetActiveLineNum(int line) { currentViewPosition.ActiveLineNum = _viewer._lineNumbersControl.GetLineInfo(line); if (currentViewPosition.ActiveLineNum is null) { return; } if (currentViewPosition.ActiveLineNum.LeftLineNumber == DiffLineInfo.NotApplicableLineNum && currentViewPosition.ActiveLineNum.RightLineNumber == DiffLineInfo.NotApplicableLineNum) { currentViewPosition.ActiveLineNum = null; } } } public void Restore(bool isDiff) { if (_viewer.TotalNumberOfLines <= 1) { return; } var viewPosition = _currentViewPosition; if (_viewer.TotalNumberOfLines == viewPosition.TotalNumberOfLines) { _viewer.FirstVisibleLine = viewPosition.FirstVisibleLine; _viewer.TextEditor.ActiveTextAreaControl.Caret.Position = viewPosition.CaretPosition; if (!viewPosition.CaretVisible) { _viewer.FirstVisibleLine = viewPosition.FirstVisibleLine; } } else if (isDiff && _viewer.GetLineText(0) == viewPosition.FirstLine && viewPosition.ActiveLineNum is not null) { // prefer the LeftLineNum because the base revision will not change int line = viewPosition.ActiveLineNum.LeftLineNumber != DiffLineInfo.NotApplicableLineNum ? _viewer.GetCaretLine(viewPosition.ActiveLineNum.LeftLineNumber, rightFile: false) : _viewer.GetCaretLine(viewPosition.ActiveLineNum.RightLineNumber, rightFile: true); if (viewPosition.CaretVisible) { _viewer.TextEditor.ActiveTextAreaControl.Caret.Position = new TextLocation(viewPosition.CaretPosition.Column, line); _viewer.TextEditor.ActiveTextAreaControl.CenterViewOn(line, treshold: 5); } else { _viewer.FirstVisibleLine = line; } } } internal readonly struct TestAccessor { private readonly CurrentViewPositionCache _viewPositionCache; public TestAccessor(CurrentViewPositionCache viewPositionCache) { _viewPositionCache = viewPositionCache; } public ViewPosition ViewPosition { get => _viewPositionCache._currentViewPosition; set => _viewPositionCache._currentViewPosition = value; } public TextEditorControl TextEditor => _viewPositionCache._viewer.TextEditor; public DiffViewerLineNumberControl LineNumberControl { get => _viewPositionCache._viewer._lineNumbersControl; set => _viewPositionCache._viewer._lineNumbersControl = value; } } } internal struct ViewPosition { internal string FirstLine; // contains the file names in case of a diff internal int TotalNumberOfLines; // if changed, CaretPosition and FirstVisibleLine must be ignored and the line number must be searched internal TextLocation CaretPosition; internal int FirstVisibleLine; internal bool CaretVisible; // if not, FirstVisibleLine has priority for restoring internal DiffLineInfo ActiveLineNum; } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly FileViewerInternal _control; public TestAccessor(FileViewerInternal control) { _control = control; } public TextEditorControl TextEditor => _control.TextEditor; } } }
EbenZhang/gitextensions
GitUI/Editor/FileViewerInternal.cs
C#
gpl-3.0
28,486
#include "include/first.hpp" #include "ServerMessageCenter.hpp" #include "SocketLib/SocketServer.hpp" #include <iostream> using namespace std; using namespace SocketLib; using namespace Server; using namespace Util; int main(int argc, char *argv[]) { int exit_code = EXIT_SUCCESS; if (argc <= 1) { cout << "usage: \nsocketserver <port>" << endl; return -1; } Logger::openLog("log.photona.server"); unsigned int port = 0; istringstream iss(argv[1]); if (!(iss >> port) || port <= 1024) { logger << logger.fatal << "invalid port number " << argv[1] << endlog; } shared_ptr<ServerMessageCenter> pServerMsgCenter = ServerMessageCenter::GetSharedPtr(); MessageCenter::SetSharedPtr(pServerMsgCenter); SocketServer server; if (!server.run("*", port)) { exit_code = EXIT_FAILURE; } Logger::closeLog(); return exit_code; }
cmere/photona
src/Server/main.cpp
C++
gpl-3.0
870
import {NavElement} from 'helpers/nav-element'; export class Navigation { constructor() { this.home = new NavElement("Home"); this.about = new NavElement("About"); this.form = new NavElement("Upload"); this._active = this.home; } changeActive(navElement) { this._active.deactivate(); navElement.activate(); this._active = navElement; return true; } }
pbujok/workoutcombiner
src/FrontEnd/src/navigation.js
JavaScript
gpl-3.0
435
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * C45PruneableClassifierTree.java * Copyright (C) 1999 Eibe Frank * */ package weka.classifiers.trees.j48; import weka.core.*; /** * Class for handling a tree structure that can * be pruned using C4.5 procedures. * * @author Eibe Frank (eibe@cs.waikato.ac.nz) * @version $Revision: 1.11 $ */ public class C45PruneableClassifierTree extends ClassifierTree{ /** True if the tree is to be pruned. */ boolean m_pruneTheTree = false; /** The confidence factor for pruning. */ float m_CF = 0.25f; /** Is subtree raising to be performed? */ boolean m_subtreeRaising = true; /** Cleanup after the tree has been built. */ boolean m_cleanup = true; /** * Constructor for pruneable tree structure. Stores reference * to associated training data at each node. * * @param toSelectLocModel selection method for local splitting model * @param pruneTree true if the tree is to be pruned * @param cf the confidence factor for pruning * @exception Exception if something goes wrong */ public C45PruneableClassifierTree(ModelSelection toSelectLocModel, boolean pruneTree,float cf, boolean raiseTree, boolean cleanup) throws Exception { super(toSelectLocModel); m_pruneTheTree = pruneTree; m_CF = cf; m_subtreeRaising = raiseTree; m_cleanup = cleanup; } /** * Method for building a pruneable classifier tree. * * @exception Exception if something goes wrong */ public void buildClassifier(Instances data) throws Exception { if (data.classAttribute().isNumeric()) throw new UnsupportedClassTypeException("Class is numeric!"); if (data.checkForStringAttributes()) { throw new UnsupportedAttributeTypeException("Cannot handle string attributes!"); } data = new Instances(data); data.deleteWithMissingClass(); buildTree(data, m_subtreeRaising); collapse(); if (m_pruneTheTree) { prune(); } if (m_cleanup) { cleanup(new Instances(data, 0)); } } /** * Collapses a tree to a node if training error doesn't increase. */ public final void collapse(){ double errorsOfSubtree; double errorsOfTree; int i; if (!m_isLeaf){ errorsOfSubtree = getTrainingErrors(); errorsOfTree = localModel().distribution().numIncorrect(); if (errorsOfSubtree >= errorsOfTree-1E-3){ // Free adjacent trees m_sons = null; m_isLeaf = true; // Get NoSplit Model for tree. m_localModel = new NoSplit(localModel().distribution()); }else for (i=0;i<m_sons.length;i++) son(i).collapse(); } } /** * Prunes a tree using C4.5's pruning procedure. * * @exception Exception if something goes wrong */ public void prune() throws Exception { double errorsLargestBranch; double errorsLeaf; double errorsTree; int indexOfLargestBranch; C45PruneableClassifierTree largestBranch; int i; if (!m_isLeaf){ // Prune all subtrees. for (i=0;i<m_sons.length;i++) son(i).prune(); // Compute error for largest branch indexOfLargestBranch = localModel().distribution().maxBag(); if (m_subtreeRaising) { errorsLargestBranch = son(indexOfLargestBranch). getEstimatedErrorsForBranch((Instances)m_train); } else { errorsLargestBranch = Double.MAX_VALUE; } // Compute error if this Tree would be leaf errorsLeaf = getEstimatedErrorsForDistribution(localModel().distribution()); // Compute error for the whole subtree errorsTree = getEstimatedErrors(); // Decide if leaf is best choice. if (Utils.smOrEq(errorsLeaf,errorsTree+0.1) && Utils.smOrEq(errorsLeaf,errorsLargestBranch+0.1)){ // Free son Trees m_sons = null; m_isLeaf = true; // Get NoSplit Model for node. m_localModel = new NoSplit(localModel().distribution()); return; } // Decide if largest branch is better choice // than whole subtree. if (Utils.smOrEq(errorsLargestBranch,errorsTree+0.1)){ largestBranch = son(indexOfLargestBranch); m_sons = largestBranch.m_sons; m_localModel = largestBranch.localModel(); m_isLeaf = largestBranch.m_isLeaf; newDistribution(m_train); prune(); } } } /** * Returns a newly created tree. * * @exception Exception if something goes wrong */ protected ClassifierTree getNewTree(Instances data) throws Exception { C45PruneableClassifierTree newTree = new C45PruneableClassifierTree(m_toSelectModel, m_pruneTheTree, m_CF, m_subtreeRaising, m_cleanup); newTree.buildTree((Instances)data, m_subtreeRaising); return newTree; } /** * Computes estimated errors for tree. */ private double getEstimatedErrors(){ double errors = 0; int i; if (m_isLeaf) return getEstimatedErrorsForDistribution(localModel().distribution()); else{ for (i=0;i<m_sons.length;i++) errors = errors+son(i).getEstimatedErrors(); return errors; } } /** * Computes estimated errors for one branch. * * @exception Exception if something goes wrong */ private double getEstimatedErrorsForBranch(Instances data) throws Exception { Instances [] localInstances; double errors = 0; int i; if (m_isLeaf) return getEstimatedErrorsForDistribution(new Distribution(data)); else{ Distribution savedDist = localModel().m_distribution; localModel().resetDistribution(data); localInstances = (Instances[])localModel().split(data); localModel().m_distribution = savedDist; for (i=0;i<m_sons.length;i++) errors = errors+ son(i).getEstimatedErrorsForBranch(localInstances[i]); return errors; } } /** * Computes estimated errors for leaf. */ private double getEstimatedErrorsForDistribution(Distribution theDistribution){ if (Utils.eq(theDistribution.total(),0)) return 0; else return theDistribution.numIncorrect()+ Stats.addErrs(theDistribution.total(), theDistribution.numIncorrect(),m_CF); } /** * Computes errors of tree on training data. */ private double getTrainingErrors(){ double errors = 0; int i; if (m_isLeaf) return localModel().distribution().numIncorrect(); else{ for (i=0;i<m_sons.length;i++) errors = errors+son(i).getTrainingErrors(); return errors; } } /** * Method just exists to make program easier to read. */ private ClassifierSplitModel localModel(){ return (ClassifierSplitModel)m_localModel; } /** * Computes new distributions of instances for nodes * in tree. * * @exception Exception if something goes wrong */ private void newDistribution(Instances data) throws Exception { Instances [] localInstances; localModel().resetDistribution(data); m_train = data; if (!m_isLeaf){ localInstances = (Instances [])localModel().split(data); for (int i = 0; i < m_sons.length; i++) son(i).newDistribution(localInstances[i]); } else { // Check whether there are some instances at the leaf now! if (!Utils.eq(data.sumOfWeights(), 0)) { m_isEmpty = false; } } } /** * Method just exists to make program easier to read. */ private C45PruneableClassifierTree son(int index){ return (C45PruneableClassifierTree)m_sons[index]; } }
paolopavan/cfr
src/weka/classifiers/TREES/J48/C45PruneableClassifierTree.java
Java
gpl-3.0
8,148
<?php namespace App\Http\Controllers\Seguridad; use App\Modelos\Seguridad\Bitacora; use App\Modelos\Seguridad\AsignacionPermisos\Rol; use App\Modelos\Seguridad\Empleado; use App\Utils; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Redirect; use App\Http\Controllers\Controller; use App\User; use DB; class EmpleadoController extends Controller { public function index(Request $request) { if ($request){ $query = trim($request -> get('searchText')); $empleado=Empleado::where('nombre','LIKE','%'.$query.'%') ->where('tipo','!=','Administrador') ->where('visible','=','1') ->orderBy('id','asc') ->paginate(25); //Bitacora::registrarListar(Utils::$TABLA_EMPLEADO); return view('admin.Seguridad.empleados.index',["empleado" => $empleado, "searchText" => $query]); } } public function create() { $roles= Rol::where('id','>',1)->get(); return view("admin.Seguridad.empleados.create",compact('roles')); } public function store(Request $request) { $user2 = new User(); $user2 -> name = $request -> get('nombre'); $user2 -> email = $request -> get('email'); $user2 -> password = bcrypt($request->get('password')); $user2 -> tipo = 'Empleado'; //$empleado -> idEmpresa = Auth::user()->idEmpresa; // if($user2 -> save()) { $empleado = new Empleado(); $empleado -> ci = $request -> get('ci'); $empleado -> nombre = $request -> get('nombre'); $empleado -> direccion = $request -> get('direccion'); $empleado -> telefono = $request -> get('telefono'); $empleado -> tipo = 'Empleado'; $empleado -> rol_id =$request->rol_id ; $empleado -> idEmpresa = Auth::user()->idEmpresa; if($empleado -> save()) { Bitacora::registrarCreate( Utils::$TABLA_EMPLEADO,$empleado->id,'se creo al empleado '.$empleado -> nombre); $user2 -> idEmpleado = $empleado->id; $user2 -> idEmpresa = Auth::user()->idEmpresa; $user2->update(); } } else{ } return Redirect::to('admin/empleados'); } public function show($id) { // } public function edit($id) { $empleado=Empleado::findOrFail($id); $roles= Rol::where('id','>',1)->get(); return view("admin.Seguridad.empleados.edit",compact('empleado','roles')); } public function update(Request $request) { $id=$request->empleado_id; $ultimo2 = DB::table('users') ->where('idEmpleado', '=', $id) ->first(); $user4 = User::findOrFail($ultimo2->id); $user4->name = $request->get('nombre'); if($user4->update()) { $empleado = Empleado::findOrFail($id); $empleado -> ci = $request -> get('ci'); $empleado -> nombre = $request -> get('nombre'); $empleado -> direccion = $request -> get('direccion'); $empleado -> telefono = $request -> get('telefono'); $empleado -> tipo = 'Empleado'; $empleado -> rol_id = $request->rol_id; $empleado -> update(); Bitacora::registrarUpdate( Utils::$TABLA_EMPLEADO,$empleado->id,'se actualizo datos del empleado '.$empleado -> nombre); } return Redirect::to('admin/empleados'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $empleado = Empleado::findOrFail($id); $empleado -> visible = 0; if ($empleado -> update()){ Bitacora::registrarDelete(Utils::$TABLA_EMPLEADO,$id,'se elimino al empleado '.$empleado -> nombre); } return Redirect::to('admin/empleados'); } }
rodrigoAb21/ERP3
app/Http/Controllers/Seguridad/EmpleadoController.php
PHP
gpl-3.0
4,088
#include <opm/parser/eclipse/EclipseState/Schedule/Action/ActionValue.hpp> #include <stdexcept> namespace Opm { namespace Action { namespace { #if 0 inline std::string tokenString(TokenType op) { switch (op) { case TokenType::op_eq: return "=="; case TokenType::op_ge: return ">="; case TokenType::op_le: return "<="; case TokenType::op_ne: return "!="; case TokenType::op_gt: return ">"; case TokenType::op_lt: return "<"; case TokenType::op_or: return "OR"; case TokenType::op_and: return "AND"; case TokenType::open_paren: return "("; case TokenType::close_paren: return ")"; default: return "????"; } } #endif bool eval_cmp_scalar(double lhs, TokenType op, double rhs) { switch (op) { case TokenType::op_eq: return lhs == rhs; case TokenType::op_ge: return lhs >= rhs; case TokenType::op_le: return lhs <= rhs; case TokenType::op_ne: return lhs != rhs; case TokenType::op_gt: return lhs > rhs; case TokenType::op_lt: return lhs < rhs; default: throw std::invalid_argument("Incorrect operator type - expected comparison"); } } } Value::Value(double value) : scalar_value(value), is_scalar(true) { } Value::Value(const std::string& wname, double value) { this->add_well(wname, value); } double Value::scalar() const { if (!this->is_scalar) throw std::invalid_argument("This value node represents a well list and can not be evaluated in scalar context"); return this->scalar_value; } void Value::add_well(const std::string& well, double value) { if (this->is_scalar) throw std::invalid_argument("This value node has been created as a scalar node - can not add well variables"); this->well_values.emplace_back(well, value); } Result Value::eval_cmp_wells(TokenType op, double rhs) const { std::vector<std::string> wells; bool result = false; for (const auto& pair : this->well_values) { const std::string& well = pair.first; const double value = pair.second; if (eval_cmp_scalar(value, op, rhs)) { wells.push_back(well); result = true; } } return Result(result, wells); } Result Value::eval_cmp(TokenType op, const Value& rhs) const { if (op == TokenType::number || op == TokenType::ecl_expr || op == TokenType::open_paren || op == TokenType::close_paren || op == TokenType::op_and || op == TokenType::op_or || op == TokenType::end || op == TokenType::error) throw std::invalid_argument("Invalid operator"); if (!rhs.is_scalar) throw std::invalid_argument("The right hand side must be a scalar value"); if (this->is_scalar) return Action::Result(eval_cmp_scalar(this->scalar(), op, rhs.scalar())); return this->eval_cmp_wells(op, rhs.scalar()); } } }
dr-robertk/opm-common
src/opm/parser/eclipse/EclipseState/Schedule/Action/ActionValue.cpp
C++
gpl-3.0
3,041
package the.bytecode.club.bytecodeviewer.obfuscators; import org.objectweb.asm.tree.ClassNode; import the.bytecode.club.bytecodeviewer.BytecodeViewer; import the.bytecode.club.bytecodeviewer.api.ASMResourceUtil; /*************************************************************************** * Bytecode Viewer (BCV) - Java & Android Reverse Engineering Suite * * Copyright (C) 2014 Kalen 'Konloch' Kinloch - http://bytecodeviewer.com * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ /** * Rename classes. * * @author Konloch */ public class RenameClasses extends JavaObfuscator { @Override public void obfuscate() { int stringLength = getStringLength(); System.out.println("Obfuscating class names..."); for (ClassNode c : BytecodeViewer.getLoadedClasses()) { String newName = generateUniqueName(stringLength); ASMResourceUtil.renameClassNode(c.name, newName); c.name = newName; } System.out.println("Obfuscated class names."); } }
Konloch/bytecode-viewer
src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameClasses.java
Java
gpl-3.0
2,070
package DBConnexion; /** * connection to SQLite database * @author Adrián Castelló Martínez; Macarena Parrizas Siles; Benedikt Futterer; Fabian Finkbeiner * creation 20.10.2016 * @version 18.01.2017 * @exception database connection not successful */ import java.sql.*; import javax.swing.JOptionPane; public class DBConnexion { //Constructor public DBConnexion (String sql) { try { //Connects to the DataBase located on the project folder Connection c=DriverManager.getConnection("jdbc:sqlite:DrawingProject.sqlite"); Statement s=c.createStatement(); if(s.execute(sql)){ ResultSet rs=s.getResultSet(); int z=rs.getMetaData().getColumnCount(); while (rs.next()){ for(int i=1; i<=z; i++){ if(i!=z) System.out.print(rs.getString(i)+", "); else System.out.print(rs.getString(i)+"\n "); } } } else System.out.println(s.getUpdateCount()); } catch (Exception ex){ JOptionPane.showMessageDialog(null, ex); ex.printStackTrace(); } } }
Rinkamika/Drawing-Project
src/DBConnexion/DBConnexion.java
Java
gpl-3.0
1,330
using SmartStore.Core.Configuration; namespace SmartStore.Core.Domain.Common { public class SocialSettings : ISettings { /// <summary> /// Gets or sets the value that determines whether social links should be show in the footer /// </summary> public bool ShowSocialLinksInFooter { get; set; } = true; /// <summary> /// Gets or sets the facebook link /// </summary> public string FacebookLink { get; set; } = "#"; /// <summary> /// Gets or sets the twitter link /// </summary> public string TwitterLink { get; set; } = "#"; /// <summary> /// Gets or sets the pinterest link /// </summary> public string PinterestLink { get; set; } = "#"; /// <summary> /// Gets or sets the youtube link /// </summary> public string YoutubeLink { get; set; } = "#"; /// <summary> /// Gets or sets the instagram link /// </summary> public string InstagramLink { get; set; } = "#"; } }
smartstoreag/SmartStoreNET
src/Libraries/SmartStore.Core/Domain/Common/SocialSettings.cs
C#
gpl-3.0
1,077
package com.mylovemhz.floordoorrecords.net; import org.json.JSONException; import org.json.JSONObject; public class DownloadResponse { private boolean isSuccess = false; public DownloadResponse(String response){ try { JSONObject data = new JSONObject(response); isSuccess = data.getBoolean("execution"); } catch (JSONException e) { isSuccess = false; } } public boolean isSuccess() { return isSuccess; } }
allanpichardo/Floordoor-Records-Android
app/src/main/java/com/mylovemhz/floordoorrecords/net/DownloadResponse.java
Java
gpl-3.0
499
package validatorStrategies import ( "encoding/json" "fmt" _ "reflect" "strconv" "strings" _ "github.com/ethereum/go-ethereum/common" ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger/glog" "github.com/tendermint/abci/types" ) type TxBasedValidatorsStrategy struct { currentValidators []*types.Validator } func (strategy *TxBasedValidatorsStrategy) SetValidators(validators []*types.Validator) { strategy.currentValidators = validators } //16进制字符串转[]byte func HexToByte(hex string) []byte { length := len(hex) / 2 slice := make([]byte, length) rs := []rune(hex) for i := 0; i < length; i++ { s := string(rs[i*2 : i*2+2]) value, _ := strconv.ParseInt(s, 16, 10) slice[i] = byte(value & 0xFF) } return slice } func (strategy *TxBasedValidatorsStrategy) CollectTx(tx *ethTypes.Transaction) { //fmt.Println("enter base CollectTx" + tx.String()) //fmt.Println("enter base CollectTx" + fmt.Sprintf("%x", tx.data.Recipient[:])) glog.V(logger.Debug).Infof("Adding validator: %v", tx.Data()) //if reflect.DeepEqual(tx.To(), common.HexToAddress("0000000000000000000000000000000000000001")) { to := fmt.Sprintf("%x", tx.To()) des := "&1000000000000000000000000000000000000001" fmt.Println("enter base CollectTx to string" + to) if strings.Compare(to, des) == 0 { fmt.Println("Adding validator,data=" + string(tx.Data())) fmt.Println("tx.value=" + strconv.FormatUint(tx.Value().Uint64(), 10)) var vaPub []string err := json.Unmarshal(tx.Data(), &vaPub) if err != nil { fmt.Println("error:", err) } length := len(vaPub) for i := 0; i < length; i++ { fmt.Println("Adding validator,pub=" + vaPub[i]) strategy.currentValidators = append( strategy.currentValidators, &types.Validator{ PubKey: HexToByte(vaPub[i]), Power: tx.Value().Uint64(), }, ) } fmt.Println("got tx data") //need to remove for test //os.Exit(1) } } func (strategy *TxBasedValidatorsStrategy) GetUpdatedValidators() []*types.Validator { return strategy.currentValidators }
wangluinc/ethermint
strategies/validators/tx_based.go
GO
gpl-3.0
2,129
/* * Copyright (c) Ashar Khan 2017. <ashar786khan@gmail.com> * This file is part of Google Developer Group's Android Application. * Google Developer Group 's Android Application is free software : you can redistribute it and/or modify * it under the terms of GNU General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * This Application is distributed in the hope that it will be useful * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this Source File. * If not, see <http:www.gnu.org/licenses/>. */ package com.softminds.gdg.fragments; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.TextInputEditText; import android.support.design.widget.TextInputLayout; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Switch; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.softminds.gdg.R; import com.softminds.gdg.utils.AdminNotifyHelper; public class Notify extends Fragment { TextInputEditText title,body; Switch aSwitch; Button button; ProgressBar progress; TextInputLayout layout1 ,layout2; public Notify() { // Required empty public constructor } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_notify, container, false); button = v.findViewById(R.id.send_notification); aSwitch = v.findViewById(R.id.switch_sound); body = v.findViewById(R.id.notification_body); title = v.findViewById(R.id.notification_title); progress = v.findViewById(R.id.progress_message_send); layout1 = v.findViewById(R.id.zzs); layout2 = v.findViewById(R.id.zzsa); return v; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(validate()){ Progress(true); String Title = title.getText().toString(); String Body = body.getText().toString(); boolean silently = !aSwitch.isChecked(); //noinspection ConstantConditions long live_time = 60 * 1000 * 60; AdminNotifyHelper adminNotifyHelper = new AdminNotifyHelper( Title, Body, silently, live_time ); AdminNotifyHelper.Companion.notifyAll(adminNotifyHelper).addOnSuccessListener( new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getContext(),R.string.notified_soon,Toast.LENGTH_SHORT).show(); Progress(false); } } ) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getContext(),R.string.something_went_wrong,Toast.LENGTH_SHORT).show(); Progress(false); } }); title.setText(null); body.setText(null); } } }); } private boolean validate() { if(body.getText().toString().isEmpty()){ body.setError(getString(R.string.missing)); title.requestFocus(); return false; } if(title.getText().toString().isEmpty()){ title.setError(getString(R.string.missing)); title.requestFocus(); return false; } return true; } private void Progress(boolean yes){ progress.setVisibility(yes ? View.VISIBLE : View.GONE); layout1.setVisibility(yes? View.GONE : View.VISIBLE); layout2.setVisibility(yes ? View.GONE: View.VISIBLE); aSwitch.setVisibility(yes ? View.GONE :View.VISIBLE); button.setVisibility(yes ? View.GONE :View.VISIBLE); } }
coder3101/gdgApp
gdg/src/main/java/com/softminds/gdg/fragments/Notify.java
Java
gpl-3.0
5,130
<?php uses('de.moonbird.common.registry.Registry'); abstract class Request extends Registry { /** * Initialise request class * @return void */ public static function init() { $querystring= $_SERVER["QUERY_STRING"]; if (strpos($querystring, "&")>-1) { $querystring= substr($querystring, 0, strpos($querystring, "&")); $additionalParams= explode("&", substr($_SERVER["QUERY_STRING"], strpos($querystring, "&"))); } else { $additionalParams= array(); } $moduleArray = @explode("/", $querystring); if (is_array($moduleArray)) { $module = array_shift($moduleArray); $file = array_shift($moduleArray); Request::set('module', $module); Request::set('file', $file); Request::set('params', $moduleArray+$additionalParams); Request::set('num_params', count($moduleArray)+count($additionalParams)); } if (Request::get('file') == '') { Request::set('file', 'index', TRUE); } foreach ($_REQUEST as $key => $value) { // add additional values, allow overwriting previously added module and file params Request::set($key, $value, TRUE); } } /** * Return module name * @return string */ public static function getModule () { return Request::get('module'); } /** * Return module file * @return string */ public static function getFile () { return Request::get('file'); } /** * Get number of parameters * @return int */ public static function getParameterCount() { return Request::get('num_params'); } /** * Return one element * @param int $index * @return array */ public static function getParam($index) { return Request::$registry['params'][$index]; // return value of parameter } }
Moonbird-IT/mbframework
src/de/moonbird/web/Request.class.php
PHP
gpl-3.0
1,791
module Msf::Module::Author # # Attributes # # @!attribute author # The array of zero or more authors. attr_reader :author # # Instance Methods # # # Return a comma separated list of author for this module. # def author_to_s author.collect { |author| author.to_s }.join(", ") end # # Enumerate each author. # def each_author(&block) author.each(&block) end protected # # Attributes # # @!attribute [w] author attr_writer :author end
cSploit/android.MSF
lib/msf/core/module/author.rb
Ruby
gpl-3.0
501
/*! * \file * \brief * \author Armin Schmidt * * ---------------------------------------------------------------------------- * * PlugBoard - A versatile communication simulation framework * Copyright (C) 2007-2008 Armin Schmidt * * This file is part of PlugBoard. * * PlugBoard is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlugBoard is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PlugBoard. If not, see <http://www.gnu.org/licenses/>. * * ---------------------------------------------------------------------------- */ #ifndef VECTORS_HPP #define VECTORS_HPP #include "types/base.hpp" #include <vector> template< class T > struct TestVec : public std::vector< T > { inline operator T() const { return (*this)[0]; } }; namespace plugboard { #define BOOST_PP_DEF(z, I, _) \ typedef TestVec< CPP_TYPE(I) > \ BOOST_PP_CAT(TYPE_VALUE(I), _vec_t); BOOST_PP_REPEAT(SIGNAL_TYPE_CNT, BOOST_PP_DEF, _) #undef BOOST_PP_DEF } #endif // VECTORS_HPP
Dunkelschorsch/plugboard
types/vectors.hpp
C++
gpl-3.0
1,451
<?php /** * * This file is part of the phpBB Forum Software package. * * @copyright (c) phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */ namespace phpbb\extension; use phpbb\exception\runtime_exception; use phpbb\file_downloader; use Symfony\Component\DependencyInjection\ContainerInterface; /** * The extension manager provides means to activate/deactivate extensions. */ class manager { /** @var ContainerInterface */ protected $container; protected $db; protected $config; protected $cache; protected $php_ext; protected $extensions; protected $extension_table; protected $phpbb_root_path; protected $cache_name; /** * Creates a manager and loads information from database * * @param ContainerInterface $container A container * @param \phpbb\db\driver\driver_interface $db A database connection * @param \phpbb\config\config $config Config object * @param \phpbb\filesystem\filesystem_interface $filesystem * @param string $extension_table The name of the table holding extensions * @param string $phpbb_root_path Path to the phpbb includes directory. * @param string $php_ext php file extension, defaults to php * @param \phpbb\cache\service $cache A cache instance or null * @param string $cache_name The name of the cache variable, defaults to _ext */ public function __construct(ContainerInterface $container, \phpbb\db\driver\driver_interface $db, \phpbb\config\config $config, \phpbb\filesystem\filesystem_interface $filesystem, $extension_table, $phpbb_root_path, $php_ext = 'php', \phpbb\cache\service $cache = null, $cache_name = '_ext') { $this->cache = $cache; $this->cache_name = $cache_name; $this->config = $config; $this->container = $container; $this->db = $db; $this->extension_table = $extension_table; $this->filesystem = $filesystem; $this->phpbb_root_path = $phpbb_root_path; $this->php_ext = $php_ext; $this->extensions = ($this->cache) ? $this->cache->get($this->cache_name) : false; if ($this->extensions === false) { $this->load_extensions(); } } /** * Loads all extension information from the database * * @return null */ public function load_extensions() { $this->extensions = array(); // Do not try to load any extensions if the extension table // does not exist or when installing or updating. // Note: database updater invokes this code, and in 3.0 // there is no extension table therefore the rest of this function // fails if (defined('IN_INSTALL') || version_compare($this->config['version'], '3.1.0-dev', '<')) { return; } $sql = 'SELECT * FROM ' . $this->extension_table; $result = $this->db->sql_query($sql); $extensions = $this->db->sql_fetchrowset($result); $this->db->sql_freeresult($result); foreach ($extensions as $extension) { $extension['ext_path'] = $this->get_extension_path($extension['ext_name']); $this->extensions[$extension['ext_name']] = $extension; } ksort($this->extensions); if ($this->cache) { $this->cache->put($this->cache_name, $this->extensions); } } /** * Generates the path to an extension * * @param string $name The name of the extension * @param bool $phpbb_relative Whether the path should be relative to phpbb root * @return string Path to an extension */ public function get_extension_path($name, $phpbb_relative = false) { $name = str_replace('.', '', $name); return (($phpbb_relative) ? $this->phpbb_root_path : '') . 'ext/' . $name . '/'; } /** * Instantiates the extension meta class for the extension with the given name * * @param string $name The extension name * @return \phpbb\extension\extension_interface Instance of the extension meta class or * \phpbb\extension\base if the class does not exist */ public function get_extension($name) { $extension_class_name = str_replace('/', '\\', $name) . '\\ext'; $migrator = $this->container->get('migrator'); if (class_exists($extension_class_name)) { return new $extension_class_name($this->container, $this->get_finder(), $migrator, $name, $this->get_extension_path($name, true)); } else { return new \phpbb\extension\base($this->container, $this->get_finder(), $migrator, $name, $this->get_extension_path($name, true)); } } /** * Instantiates the metadata manager for the extension with the given name * * @param string $name The extension name * @return \phpbb\extension\metadata_manager Instance of the metadata manager */ public function create_extension_metadata_manager($name) { return new \phpbb\extension\metadata_manager($name, $this->config, $this, $this->phpbb_root_path); } /** * Runs a step of the extension enabling process. * * Allows the exentension to enable in a long running script that works * in multiple steps across requests. State is kept for the extension * in the extensions table. * * @param string $name The extension's name * @return bool False if enabling is finished, true otherwise */ public function enable_step($name) { // ignore extensions that are already enabled if (isset($this->extensions[$name]) && $this->extensions[$name]['ext_active']) { return false; } $old_state = (isset($this->extensions[$name]['ext_state'])) ? unserialize($this->extensions[$name]['ext_state']) : false; $extension = $this->get_extension($name); if (!$extension->is_enableable()) { return false; } $state = $extension->enable_step($old_state); $active = ($state === false); $extension_data = array( 'ext_name' => $name, 'ext_active' => $active, 'ext_state' => serialize($state), ); $this->extensions[$name] = $extension_data; $this->extensions[$name]['ext_path'] = $this->get_extension_path($extension_data['ext_name']); ksort($this->extensions); $sql = 'SELECT COUNT(ext_name) as row_count FROM ' . $this->extension_table . " WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; $result = $this->db->sql_query($sql); $count = $this->db->sql_fetchfield('row_count'); $this->db->sql_freeresult($result); if ($count) { $sql = 'UPDATE ' . $this->extension_table . ' SET ' . $this->db->sql_build_array('UPDATE', $extension_data) . " WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; $this->db->sql_query($sql); } else { $sql = 'INSERT INTO ' . $this->extension_table . ' ' . $this->db->sql_build_array('INSERT', $extension_data); $this->db->sql_query($sql); } if ($this->cache) { $this->cache->purge(); } if ($active) { $this->config->increment('assets_version', 1); } return !$active; } /** * Enables an extension * * This method completely enables an extension. But it could be long running * so never call this in a script that has a max_execution time. * * @param string $name The extension's name * @return null */ public function enable($name) { // @codingStandardsIgnoreStart while ($this->enable_step($name)); // @codingStandardsIgnoreEnd } /** * Disables an extension * * Calls the disable method on the extension's meta class to allow it to * process the event. * * @param string $name The extension's name * @return bool False if disabling is finished, true otherwise */ public function disable_step($name) { // ignore extensions that are already disabled if (!isset($this->extensions[$name]) || !$this->extensions[$name]['ext_active']) { return false; } $old_state = unserialize($this->extensions[$name]['ext_state']); $extension = $this->get_extension($name); $state = $extension->disable_step($old_state); // continue until the state is false if ($state !== false) { $extension_data = array( 'ext_state' => serialize($state), ); $this->extensions[$name]['ext_state'] = serialize($state); $sql = 'UPDATE ' . $this->extension_table . ' SET ' . $this->db->sql_build_array('UPDATE', $extension_data) . " WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; $this->db->sql_query($sql); if ($this->cache) { $this->cache->purge(); } return true; } $extension_data = array( 'ext_active' => false, 'ext_state' => serialize(false), ); $this->extensions[$name]['ext_active'] = false; $this->extensions[$name]['ext_state'] = serialize(false); $sql = 'UPDATE ' . $this->extension_table . ' SET ' . $this->db->sql_build_array('UPDATE', $extension_data) . " WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; $this->db->sql_query($sql); if ($this->cache) { $this->cache->purge(); } return false; } /** * Disables an extension * * Disables an extension completely at once. This process could run for a * while so never call this in a script that has a max_execution time. * * @param string $name The extension's name * @return null */ public function disable($name) { // @codingStandardsIgnoreStart while ($this->disable_step($name)); // @codingStandardsIgnoreEnd } /** * Purge an extension * * Disables the extension first if active, and then calls purge on the * extension's meta class to delete the extension's database content. * * @param string $name The extension's name * @return bool False if purging is finished, true otherwise */ public function purge_step($name) { // ignore extensions that do not exist if (!isset($this->extensions[$name])) { return false; } // disable first if necessary if ($this->extensions[$name]['ext_active']) { $this->disable($name); } $old_state = unserialize($this->extensions[$name]['ext_state']); $extension = $this->get_extension($name); $state = $extension->purge_step($old_state); // continue until the state is false if ($state !== false) { $extension_data = array( 'ext_state' => serialize($state), ); $this->extensions[$name]['ext_state'] = serialize($state); $sql = 'UPDATE ' . $this->extension_table . ' SET ' . $this->db->sql_build_array('UPDATE', $extension_data) . " WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; $this->db->sql_query($sql); if ($this->cache) { $this->cache->purge(); } return true; } unset($this->extensions[$name]); $sql = 'DELETE FROM ' . $this->extension_table . " WHERE ext_name = '" . $this->db->sql_escape($name) . "'"; $this->db->sql_query($sql); if ($this->cache) { $this->cache->purge(); } return false; } /** * Purge an extension * * Purges an extension completely at once. This process could run for a while * so never call this in a script that has a max_execution time. * * @param string $name The extension's name * @return null */ public function purge($name) { // @codingStandardsIgnoreStart while ($this->purge_step($name)); // @codingStandardsIgnoreEnd } /** * Retrieves a list of all available extensions on the filesystem * * @return array An array with extension names as keys and paths to the * extension as values */ public function all_available() { $available = array(); if (!is_dir($this->phpbb_root_path . 'ext/')) { return $available; } $iterator = new \RecursiveIteratorIterator( new \phpbb\recursive_dot_prefix_filter_iterator( new \RecursiveDirectoryIterator($this->phpbb_root_path . 'ext/', \FilesystemIterator::NEW_CURRENT_AND_KEY | \FilesystemIterator::FOLLOW_SYMLINKS) ), \RecursiveIteratorIterator::SELF_FIRST ); $iterator->setMaxDepth(2); foreach ($iterator as $file_info) { if ($file_info->isFile() && $file_info->getFilename() == 'composer.json') { $ext_name = $iterator->getInnerIterator()->getSubPath(); $ext_name = str_replace(DIRECTORY_SEPARATOR, '/', $ext_name); if ($this->is_available($ext_name)) { $available[$ext_name] = $this->phpbb_root_path . 'ext/' . $ext_name . '/'; } } } ksort($available); return $available; } /** * Retrieves all configured extensions. * * All enabled and disabled extensions are considered configured. A purged * extension that is no longer in the database is not configured. * * @param bool $phpbb_relative Whether the path should be relative to phpbb root * * @return array An array with extension names as keys and and the * database stored extension information as values */ public function all_configured($phpbb_relative = true) { $configured = array(); foreach ($this->extensions as $name => $data) { $data['ext_path'] = ($phpbb_relative ? $this->phpbb_root_path : '') . $data['ext_path']; $configured[$name] = $data; } return $configured; } /** * Retrieves all enabled extensions. * @param bool $phpbb_relative Whether the path should be relative to phpbb root * * @return array An array with extension names as keys and and the * database stored extension information as values */ public function all_enabled($phpbb_relative = true) { $enabled = array(); foreach ($this->extensions as $name => $data) { if ($data['ext_active']) { $enabled[$name] = ($phpbb_relative ? $this->phpbb_root_path : '') . $data['ext_path']; } } return $enabled; } /** * Retrieves all disabled extensions. * * @param bool $phpbb_relative Whether the path should be relative to phpbb root * * @return array An array with extension names as keys and and the * database stored extension information as values */ public function all_disabled($phpbb_relative = true) { $disabled = array(); foreach ($this->extensions as $name => $data) { if (!$data['ext_active']) { $disabled[$name] = ($phpbb_relative ? $this->phpbb_root_path : '') . $data['ext_path']; } } return $disabled; } /** * Check to see if a given extension is available on the filesystem * * @param string $name Extension name to check NOTE: Can be user input * @return bool Depending on whether or not the extension is available */ public function is_available($name) { // Not available if the folder does not exist if (!file_exists($this->get_extension_path($name, true))) { return false; } $composer_file = $this->get_extension_path($name, true) . 'composer.json'; // Not available if there is no composer.json. if (!is_readable($composer_file) || !($ext_info = file_get_contents($composer_file))) { return false; } $ext_info = json_decode($ext_info, true); // Not available if malformed name or if the directory structure // does not match the name value specified in composer.json. if (substr_count($name, '/') !== 1 || !isset($ext_info['name']) || $name != $ext_info['name']) { return false; } return true; } /** * Check to see if a given extension is enabled * * @param string $name Extension name to check * @return bool Depending on whether or not the extension is enabled */ public function is_enabled($name) { return isset($this->extensions[$name]) && $this->extensions[$name]['ext_active']; } /** * Check to see if a given extension is disabled * * @param string $name Extension name to check * @return bool Depending on whether or not the extension is disabled */ public function is_disabled($name) { return isset($this->extensions[$name]) && !$this->extensions[$name]['ext_active']; } /** * Check to see if a given extension is configured * * All enabled and disabled extensions are considered configured. A purged * extension that is no longer in the database is not configured. * * @param string $name Extension name to check * @return bool Depending on whether or not the extension is configured */ public function is_configured($name) { return isset($this->extensions[$name]); } /** * Check the version and return the available updates (for an extension). * * @param \phpbb\extension\metadata_manager $md_manager The metadata manager for the version to check. * @param bool $force_update Ignores cached data. Defaults to false. * @param bool $force_cache Force the use of the cache. Override $force_update. * @param string $stability Force the stability (null by default). * @return string * @throws runtime_exception */ public function version_check(\phpbb\extension\metadata_manager $md_manager, $force_update = false, $force_cache = false, $stability = null) { $meta = $md_manager->get_metadata('all'); if (!isset($meta['extra']['version-check'])) { throw new runtime_exception('NO_VERSIONCHECK'); } $version_check = $meta['extra']['version-check']; $version_helper = new \phpbb\version_helper($this->cache, $this->config, new file_downloader()); $version_helper->set_current_version($meta['version']); $version_helper->set_file_location($version_check['host'], $version_check['directory'], $version_check['filename']); $version_helper->force_stability($stability); return $updates = $version_helper->get_suggested_updates($force_update, $force_cache); } /** * Check to see if a given extension is purged * * An extension is purged if it is available, not enabled and not disabled. * * @param string $name Extension name to check * @return bool Depending on whether or not the extension is purged */ public function is_purged($name) { return $this->is_available($name) && !$this->is_configured($name); } /** * Instantiates a \phpbb\finder. * * @param bool $use_all_available Should we load all extensions, or just enabled ones * @return \phpbb\finder An extension finder instance */ public function get_finder($use_all_available = false) { $finder = new \phpbb\finder($this->filesystem, $this->phpbb_root_path, $this->cache, $this->php_ext, $this->cache_name . '_finder'); if ($use_all_available) { $finder->set_extensions(array_keys($this->all_available())); } else { $finder->set_extensions(array_keys($this->all_enabled())); } return $finder; } }
javiexin/extdepend
phpbb3200/phpbb/extension/manager.php
PHP
gpl-3.0
17,960
#define BROKEN_WEAPON(weaponName) \ class weaponName; \ class broken_##weaponName : weaponName { \ scope = public; \ }; BROKEN_WEAPON(launch_RPG7_F) BROKEN_WEAPON(CUP_launch_RPG7V) BROKEN_WEAPON(CUP_launch_RPG7V_NSPU) BROKEN_WEAPON(CUP_launch_RPG7V_PGO7V) BROKEN_WEAPON(CUP_launch_RPG7V_PGO7V2) BROKEN_WEAPON(CUP_launch_RPG7V_PGO7V3) BROKEN_WEAPON(CUP_launch_RPG18)
finesseseth/SOCOMD
modsets/socomd_content/configs/weapons/override/malfunctions.hpp
C++
gpl-3.0
367
package mobop.booklist.app.data.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import android.text.TextUtils; import mobop.booklist.app.adapter.BookAdapter; import mobop.booklist.app.data.database.builder.Column; import mobop.booklist.app.data.database.builder.ColumnType; import mobop.booklist.app.data.database.builder.Table; import mobop.booklist.app.data.generic.IAdapter; import mobop.booklist.app.data.generic.IPersistentSearchManager; import mobop.booklist.app.data.generic.book.IApiBook; import mobop.booklist.app.data.generic.book.IPersistentBook; import mobop.booklist.app.data.generic.book.IPersistentBookManager; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BookManager implements IPersistentBookManager, IPersistentSearchManager<IApiBook> { private static final String COLUMN_API_ID = "api_id"; private static final String COLUMN_NAME = "name"; private static final String COLUMN_PAGES = "pages"; private static final String COLUMN_GENRE = "genre"; private static final String COLUMN_RATING = "rating"; private static final String COLUMN_IMAGE_PATH = "image_path"; private static final String COLUMN_AUTHORS = "authors"; private static final String COLUMN_DESCRIPTION = "description"; private static final String COLUMN_NOTES = "notes"; private static final String COLUMN_TO_READ = "to_read"; private static final String COLUMN_OWN = "own"; private static final String COLUMN_WISH = "wish"; private static final String COLUMN_FAVORITE = "favorite"; private final Context mContext; private final DbHelper mDbHelper; private final BookAdapter mAdapter; private final List<IApiBook> mListbook; private String filterColumns = null; private String[] filterValues = null; public BookManager(Context context) { mDbHelper = new DbHelper(context); mContext = context; mListbook = new ArrayList<>(); mAdapter = new BookAdapter(mContext, mListbook, "bookManager"); } public static final Table TABLE = new Table("books" , new Column(COLUMN_API_ID, ColumnType.Text) , new Column(COLUMN_NAME, ColumnType.Text) , new Column(COLUMN_GENRE, ColumnType.Text) , new Column(COLUMN_PAGES, ColumnType.Int) , new Column(COLUMN_RATING, ColumnType.Int) , new Column(COLUMN_IMAGE_PATH, ColumnType.Text) , new Column(COLUMN_AUTHORS, ColumnType.Text) , new Column(COLUMN_DESCRIPTION, ColumnType.Text) , new Column(COLUMN_NOTES, ColumnType.Text) , new Column(COLUMN_TO_READ, ColumnType.Bool) , new Column(COLUMN_OWN, ColumnType.Bool) , new Column(COLUMN_WISH, ColumnType.Bool) , new Column(COLUMN_FAVORITE, ColumnType.Bool) ); private void filterBool(String columnName, boolean value) { filter(columnName + "= ?", new String[]{String.valueOf(boolToDb(value))}); } private void filter(String columnsWhere, String[] valuesWhere) { filterColumns = columnsWhere; filterValues = valuesWhere; reload(); } @Override public void reload() { if (filterColumns == null || filterValues == null) { throw new IllegalStateException("Filters must no be null !"); } mListbook.clear(); Cursor c = mDbHelper.getReadableDatabase().query( TABLE.getName(), // The table to query TABLE.getColumnsNames(), // The columns to return filterColumns, // The columns for the WHERE clause filterValues, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups null // The sort order ); while (c.moveToNext()) { Book book = cursorToBook(c); mListbook.add(book); } c.close(); mAdapter.notifyDataSetChanged(); } @NonNull private Book cursorToBook(Cursor c) { Book book = new Book(); book.setDbId(c.getInt(0)); book.setId(c.getString(1)); book.setName(c.getString(2)); book.setGenre(c.getString(3)); book.setPages(c.getInt(4)); book.setRatings(c.getInt(5)); book.setImagePath(c.getString(6)); String[] authors = c.getString(7).split(";"); book.setAuthors(Arrays.asList(authors)); book.setDescription(c.getString(8)); book.setNotes(c.getString(9)); book.setToRead(dbToBool(c.getInt(10))); book.setOwn(dbToBool(c.getInt(11))); book.setWish(dbToBool(c.getInt(12))); book.setFavorite(dbToBool(c.getInt(13))); return book; } private static void loadAllInfomations(IPersistentBook to, IApiBook item) { loadApiInfomation(to, item); if (item instanceof IPersistentBook) { loadPersistentInformations(to, (IPersistentBook) item); } } private static void loadApiInfomation(IPersistentBook to, IApiBook item) { to.setId(item.getId()); to.setName(item.getName()); to.setGenre(item.getGenre()); to.setPages(item.getPages()); to.setRatings(item.getRatings()); to.setImagePath(item.getImagePath()); to.setAuthors(item.getAuthors()); to.setDescription(item.getDescription()); } private static void loadPersistentInformations(IPersistentBook to, IPersistentBook item) { to.setNotes(item.getNotes()); to.setToRead(item.isToRead()); to.setOwn(item.isOwn()); to.setDbId(item.getDbId()); to.setWish(item.isWish()); to.setFavorite(item.isFavorite()); } private static boolean dbToBool(int value) { return value == 1; } private static int boolToDb(boolean value) { return value ? 1 : 0; } @Override public void clearFilter() { } @Override public IAdapter<IApiBook> adapter() { return mAdapter; } private void toContentValue(ContentValues values, IPersistentBook item) { values.put(COLUMN_API_ID, item.getId()); values.put(COLUMN_NAME, item.getName()); values.put(COLUMN_GENRE, item.getGenre()); values.put(COLUMN_PAGES, item.getPages()); values.put(COLUMN_RATING, item.getRatings()); values.put(COLUMN_IMAGE_PATH, item.getImagePath()); List<String> authors = item.getAuthors(); String stringAuthors = TextUtils.join(";", authors); values.put(COLUMN_AUTHORS, stringAuthors); values.put(COLUMN_DESCRIPTION, item.getDescription()); values.put(COLUMN_NOTES, item.getNotes()); values.put(COLUMN_TO_READ, boolToDb(item.isToRead())); values.put(COLUMN_OWN, boolToDb(item.isOwn())); values.put(COLUMN_WISH, boolToDb(item.isWish())); values.put(COLUMN_FAVORITE, boolToDb(item.isFavorite())); } private void add(IPersistentBook book) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); toContentValue(values, book); long id = db.insert(TABLE.getName(), null, values); book.setDbId(id); } private void update(IPersistentBook item) { SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); toContentValue(values, item); int nb = db.update( TABLE.getName(), values, Table.ID + "= ?", new String[]{ String.valueOf(item.getDbId()) } ); if (nb != 1) { throw new IllegalArgumentException(); } } @Override public IPersistentBook save(IApiBook item) { IPersistentBook book = null; if (item instanceof IPersistentBook) { book = (IPersistentBook) item; } else { book = get(item.getId()); if (book == null){ book = new Book(); } loadAllInfomations(book, item); } if (book.getDbId() > 0) { update(book); } else { add(book); } return book; } private IPersistentBook get(String id) { IPersistentBook book = null; Cursor c = mDbHelper.getReadableDatabase().query( TABLE.getName(), // The table to query TABLE.getColumnsNames(), // The columns to return COLUMN_API_ID + " = ?", // The columns for the WHERE clause new String[]{id}, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups null // The sort order ); if (c.moveToNext()) { book = cursorToBook(c); } c.close(); return book; } @Override public IPersistentBook loadInformation(IApiBook item) { IPersistentBook book = get(item.getId()); if (book != null) { loadApiInfomation(book, item); return save(book); } else { return save(item); } } @Override public void filterOwn() { filterBool(COLUMN_OWN, true); } @Override public void filterWish() { filterBool(COLUMN_WISH, true); } @Override public void filterToRead() { filterBool(COLUMN_TO_READ, true); } @Override public void filterFavorite() { filterBool(COLUMN_FAVORITE, true); } }
JoeButikofer/BookList
app/src/main/java/mobop/booklist/app/data/database/BookManager.java
Java
gpl-3.0
10,081
<?php class ControllerCommonCurrency extends Controller { public function index() { $this->load->language('common/currency'); $data['action'] = $this->url->link('common/currency/currency', ''); $data['code'] = $this->session->data['currency']; $this->load->model('localisation/currency'); $data['currencies'] = []; $results = $this->model_localisation_currency->getCurrencies(); foreach ($results as $result) { if ($result['status']) { $data['currencies'][] = array( 'title' => $result['title'], 'code' => $result['code'], 'symbol_left' => $result['symbol_left'], 'symbol_right' => $result['symbol_right'] ); } } if (!isset($this->request->get['route'])) { $data['redirect'] = $this->url->link('common/home'); } else { $url_data = $this->request->get; unset($url_data['_route_']); $route = $url_data['route']; unset($url_data['route']); $url = ''; if ($url_data) { $url = '&' . urldecode(http_build_query($url_data, '', '&')); } $data['redirect'] = $this->url->link($route, $url); } return $this->load->view('common/currency', $data); } public function currency() { if (isset($this->request->post['code'])) { $this->session->data['currency'] = $this->request->post['code']; unset($this->session->data['shipping_method']); unset($this->session->data['shipping_methods']); } if (isset($this->request->post['redirect'])) { $this->response->redirect($this->request->post['redirect']); } else { $this->response->redirect($this->url->link('common/home')); } } }
lucasjkr/opencommerce
public_html/catalog/controller/common/currency.php
PHP
gpl-3.0
1,616
set :application, "leihs2demo" set :scm, :git set :repository, "git://github.com/psy-q/leihs.git" set :branch, "master" set :deploy_via, :remote_cache set :db_config, "/home/rails/leihs/leihs2demo/database.yml" set :ldap_config, "/home/rails/leihs/leihs2demo/LDAP.yml" set :use_sudo, false set :rails_env, "production" default_run_options[:shell] = false # DB credentials needed by Sphinx, mysqldump etc. set :sql_database, "rails_leihs2_demo" set :sql_host, "db.zhdk.ch" set :sql_username, "leihs2demo" set :sql_password, "l31hsd3m00" # User Variables and Settings set :contract_lending_party_string, "Zürcher Hochschule der Künste\nAusstellungsstr. 60\n8005 Zürich" set :default_email, "ausleihe.benachrichtigung\@zhdk.ch" set :email_server, "smtp.zhdk.ch" set :email_port, 25 set :email_domain, "ausleihe.zhdk.ch" set :email_charset, "utf-8" set :email_content_type, "text/html" set :email_signature, "Your leihs test installation" # These are false by default. TODO: Actually set them to true if this is true. set :deliver_order_notifications, false set :perform_deliveries, false set :local_currency, "CHF" # Escape double-quotes using triple-backslashes in this string: \\\" set :contract_terms, 'Put your legalese here.' # If you aren't deploying to /u/apps/#{application} on the target # servers (which is the default), you can specify the actual location # via the :deploy_to variable: set :deploy_to, "/home/rails/leihs/#{application}" role :app, "leihs@webapp.zhdk.ch" role :web, "leihs@webapp.zhdk.ch" role :db, "leihs@webapp.zhdk.ch", :primary => true task :link_config do on_rollback { run "rm #{release_path}/config/database.yml" } run "rm #{release_path}/config/database.yml" run "rm #{release_path}/config/LDAP.yml" run "ln -s #{db_config} #{release_path}/config/database.yml" run "ln -s #{ldap_config} #{release_path}/config/LDAP.yml" end task :link_attachments do run "rm -rf #{release_path}/public/images/attachments" run "ln -s #{deploy_to}/#{shared_dir}/attachments #{release_path}/public/images/attachments" run "rm -rf #{release_path}/public/attachments" run "ln -s #{deploy_to}/#{shared_dir}/attachments #{release_path}/public/attachments" end task :link_db_backups do run "rm -rf #{release_path}/db/backups" run "ln -s #{deploy_to}/#{shared_dir}/db_backups #{release_path}/db/backups" end task :link_sphinx do run "rm -rf #{release_path}/db/sphinx" run "ln -s #{deploy_to}/#{shared_dir}/sphinx #{release_path}/db/sphinx" end task :remove_htaccess do # Kill the .htaccess file as we are using passenger, so this file # will only confuse the web server if parsed. run "rm #{release_path}/public/.htaccess" end task :make_tmp do run "mkdir -p #{release_path}/tmp/sessions #{release_path}/tmp/cache" end task :modify_config do set :configfile, "#{release_path}/config/environment.rb" run "sed -i 's|CONTRACT_LENDING_PARTY_STRING.*|CONTRACT_LENDING_PARTY_STRING = \"#{contract_lending_party_string}\"|' #{configfile}" run "sed -i 's|DEFAULT_EMAIL.*|DEFAULT_EMAIL = \"#{default_email}\"|' #{configfile}" run "sed -i 's|:address.*|:address => \"#{email_server}\",|' #{configfile}" run "sed -i 's|:port.*|:port => #{email_port},|' #{configfile}" run "sed -i 's|:domain.*|:domain => \"#{email_domain}\"|' #{configfile}" run "sed -i 's|ActionMailer::Base.default_charset.*|ActionMailer::Base.default_charset = \"#{email_charset}\"\nActionMailer::Base.default_content_type = \"#{email_content_type}\"|' #{configfile}" run "sed -i 's|EMAIL_SIGNATURE.*|EMAIL_SIGNATURE = \"#{email_signature}\"|' #{configfile}" run "sed -i 's|:encryption|#:encryption|' #{release_path}/app/controllers/authenticator/ldap_authentication_controller.rb" run "sed -i 's|CONTRACT_TERMS.*|CONTRACT_TERMS = \"#{contract_terms}\"|' #{configfile}" run "sed -i 's|LOCAL_CURRENCY_STRING.*|LOCAL_CURRENCY_STRING = \"#{local_currency}\"|' #{configfile}" run "echo 'config.action_mailer.perform_deliveries = false' >> #{release_path}/config/environments/production.rb" if perform_deliveries == false end task :chmod_tmp do run "chmod g-w #{release_path}/tmp" end task :configure_sphinx do run "cd #{release_path} && RAILS_ENV='production' rake ts:config" run "sed -i 's/listen = 127.0.0.1:3342/listen = 127.0.0.1:3382/' #{release_path}/config/production.sphinx.conf" run "sed -i 's/listen = 127.0.0.1:3343/listen = 127.0.0.1:3383/' #{release_path}/config/production.sphinx.conf" run "sed -i 's/listen = 127.0.0.1:3344/listen = 127.0.0.1:3384/' #{release_path}/config/production.sphinx.conf" run "sed -i 's/sql_host =.*/sql_host = #{sql_host}/' #{release_path}/config/production.sphinx.conf" run "sed -i 's/sql_user =.*/sql_user = #{sql_username}/' #{release_path}/config/production.sphinx.conf" run "sed -i 's/sql_pass =.*/sql_pass = #{sql_password}/' #{release_path}/config/production.sphinx.conf" run "sed -i 's/sql_db =.*/sql_db = #{sql_database}/' #{release_path}/config/production.sphinx.conf" run "sed -i 's/sql_sock.*//' #{release_path}/config/production.sphinx.conf" run "sed -i 's/port: 3342/port: 3382/' #{release_path}/config/sphinx.yml" run "sed -i 's/port: 3343/port: 3383/' #{release_path}/config/sphinx.yml" run "sed -i 's/port: 3344/port: 3384/' #{release_path}/config/sphinx.yml" end task :stop_sphinx do run "cd #{previous_release} && RAILS_ENV='production' rake ts:stop" end task :start_sphinx do run "cd #{release_path} && RAILS_ENV='production' rake ts:reindex" run "cd #{release_path} && RAILS_ENV='production' rake ts:start" end task :migrate_database do # Produce a string like 2010-07-15T09-16-35+02-00 date_string = DateTime.now.to_s.gsub(":","-") dump_dir = "#{deploy_to}/#{shared_dir}/db_backups" dump_path = "#{dump_dir}/#{sql_database}-#{date_string}.sql" # If mysqldump fails for any reason, Capistrano will stop here # because run catches the exit code of mysqldump run "mysqldump -h #{sql_host} --user=#{sql_username} --password=#{sql_password} -r #{dump_path} #{sql_database}" run "bzip2 #{dump_path}" # Migration here # deploy.migrate should work, but is buggy and is run in the _previous_ release's # directory, thus never runs anything? Strange. #deploy.migrate run "cd #{release_path} && RAILS_ENV='production' rake db:migrate" end task :install_gems do run "cd #{release_path} && bundle install --deployment --without cucumber profiling" run "sed -i 's/BUNDLE_DISABLE_SHARED_GEMS: \"1\"/BUNDLE_DISABLE_SHARED_GEMS: \"0\"/' #{release_path}/.bundle/config" end namespace :deploy do task :start do # we do absolutely nothing here, as we currently aren't # using a spinner script or anything of that sort. end task :restart, :roles => :app, :except => { :no_release => true } do run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}" end end after "deploy:symlink", :link_config after "deploy:symlink", :link_attachments after "deploy:symlink", :link_db_backups after "deploy:symlink", :modify_config after "deploy:symlink", :chmod_tmp before "migrate_database", :install_gems after "deploy:symlink", :migrate_database after "migrate_database", :configure_sphinx before "deploy:restart", :remove_htaccess before "deploy:restart", :make_tmp before "deploy", :stop_sphinx before "start_sphinx", :link_sphinx after "deploy", :start_sphinx after "deploy", "deploy:cleanup"
toco/leihs
config/deploy/demo.rb
Ruby
gpl-3.0
7,357
// besmellahe rahmane rahim // Allahomma ajjel le-valiyek al-faraj namespace IRI.Ket.Geometry { public enum PointPolygonRelation { In, On, Out } }
hosseinnarimanirad/IRI.Japey
IRI.Sta/IRI.Sta.Geometry/Relation/PointPolygonRelation.cs
C#
gpl-3.0
187
package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import java.util.List; import java.util.Map; import javax.annotation.Nullable; @GwtCompatible public abstract interface ListMultimap<K, V> extends Multimap<K, V> { public abstract Map<K, Collection<V>> asMap(); public abstract boolean equals(@Nullable Object paramObject); public abstract List<V> get(@Nullable K paramK); public abstract List<V> removeAll(@Nullable Object paramObject); public abstract List<V> replaceValues(K paramK, Iterable<? extends V> paramIterable); } /* Location: D:\开发工具\dex2jar-0.0.9.13\classes_dex2jar.jar * Qualified Name: com.google.common.collect.ListMultimap * JD-Core Version: 0.6.0 */
zhangjianying/12306-android-Decompile
src/com/google/common/collect/ListMultimap.java
Java
gpl-3.0
778
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("MyPets")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("MyPets")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("1cc56eaf-a08a-4586-975f-a2e4d4009424")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
bandaca/MyPets
MyPets/Properties/AssemblyInfo.cs
C#
gpl-3.0
1,361
from django.conf.urls import url from django.contrib.auth.decorators import login_required from consultas.views import * urlpatterns = [ url(r'confirmar/crear/$',login_required(ConfirmacionesCrearView.as_view()), name="confirmaciones_crear"), url(r'confirmar/lista/$',(ConfirmacionListView.as_view()), name="confirmacion_lista"), url(r'confirmar/lista/pendientes/excel/$',(ConfirmacionPendientesExcelView.as_view()), name="confirmacion_pendiente_excel"), url(r'confirmar/lista/pendientes/$',(ConfirmacionPendientesListView.as_view()), name="confirmacion_pendiente_lista"), url(r'confirmar/gracias/$',ConfirmacionGraciasView.as_view(), name="confirmacion_gracias"), url(r'consulta/editar/(?P<pk>\d+)/$',login_required(ConfirmacionUpdateView.as_view()), name="confirmacion_editar"), url(r'confirmar/(?P<pk>\d+)/(?P<password>\w+)/$',ConfirmacionContestarView.as_view(), name="confirmacion_contestar"), #url(r'confirmar/enviar/$',login_required(ConfirmacionSendView.as_view()), name="confirmacion_envio"), url(r'nueva/$',login_required(ConsultaCreateView.as_view()), name="consulta_nueva"), url(r'enviar/(?P<pk>\d+)/$',login_required(ConsultaEnviarView.as_view()), name="consulta_enviar"), url(r'consultas/$', login_required(ConsultaListView.as_view()),name="consulta_lista"), url(r'respuesta/(?P<consulta_id>\d+)/(?P<alumno_id>\d+)$', RespuestaCreateView.as_view(),name="consulta_responder"), url(r'consulta/(?P<pk>\d+)/$',login_required(ConsultaDetailView.as_view()), name="consulta_detalle"), url(r'consulta/(?P<pk>\d+)/borrar/$',login_required(ConsultaDeleteView.as_view()), name="consulta_borrar"), url(r'consulta/(?P<pk>\d+)/editar/$',login_required(ConsultaUpdateView.as_view()), name="consulta_editar"), ]
Etxea/gestioneide
consultas/urls.py
Python
gpl-3.0
1,772
<?php namespace PJM\AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Validator\Constraints as Assert; /** * Responsabilite. * * @ORM\Table() * @ORM\Entity(repositoryClass="PJM\AppBundle\Entity\ResponsabiliteRepository") * @UniqueEntity({"libelle","boquette"}) */ class Responsabilite { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="libelle", type="string", length=255) * @Assert\NotBlank() */ private $libelle; /** * @var string * * @ORM\Column(name="role", type="string", length=255, nullable=true) */ private $role; /** * Niveau hiérarchique de la responsabilité, 0 étant le plus important. * * @var int * * @ORM\Column(name="niveau", type="smallint") * @Assert\NotBlank() */ private $niveau; /** * Si la responsabilité existe au tabagn'ss ou pas. * * @var bool * * @ORM\Column(name="active", type="boolean") */ private $active; /** * @ORM\OneToMany(targetEntity="Responsable", mappedBy="responsabilite") **/ private $responsables; /** * @ORM\ManyToOne(targetEntity="Boquette", inversedBy="responsabilites") * @Assert\NotBlank() **/ private $boquette; public function __construct() { $this->responsables = new \Doctrine\Common\Collections\ArrayCollection(); } public function __toString() { return '['.$this->boquette->getNomCourt().'] '.$this->libelle; } /** * Get id. * * @return int */ public function getId() { return $this->id; } /** * Set libelle. * * @param string $libelle * * @return Responsabilite */ public function setLibelle($libelle) { $this->libelle = $libelle; return $this; } /** * Get libelle. * * @return string */ public function getLibelle() { return $this->libelle; } /** * Set role. * * @param string $role * * @return Responsabilite */ public function setRole($role) { $this->role = $role; return $this; } /** * Get role. * * @return string */ public function getRole() { return $this->role; } /** * Set niveau. * * @param int $niveau * * @return Responsabilite */ public function setNiveau($niveau) { $this->niveau = $niveau; return $this; } /** * Get niveau. * * @return int */ public function getNiveau() { return $this->niveau; } /** * Set boquette. * * @param \PJM\AppBundle\Entity\Boquette $boquette * * @return Responsabilite */ public function setBoquette(\PJM\AppBundle\Entity\Boquette $boquette = null) { $this->boquette = $boquette; return $this; } /** * Get boquette. * * @return \PJM\AppBundle\Entity\Boquette */ public function getBoquette() { return $this->boquette; } /** * Add responsables. * * @param \PJM\AppBundle\Entity\Responsable $responsables * * @return Responsabilite */ public function addResponsable(\PJM\AppBundle\Entity\Responsable $responsables) { $this->responsables[] = $responsables; return $this; } /** * Remove responsables. * * @param \PJM\AppBundle\Entity\Responsable $responsables */ public function removeResponsable(\PJM\AppBundle\Entity\Responsable $responsables) { $this->responsables->removeElement($responsables); } /** * Get responsables. * * @return \Doctrine\Common\Collections\Collection */ public function getResponsables() { return $this->responsables; } /** * Set active. * * @param bool $active * * @return Responsabilite */ public function setActive($active) { $this->active = $active; return $this; } /** * Get active. * * @return bool */ public function getActive() { return $this->active; } }
Minishlink/physbook
src/PJM/AppBundle/Entity/Responsabilite.php
PHP
gpl-3.0
4,507
#!/usr/bin/python version=1.0 # orangen.py: simplified default pin generator for livebox 2.1 and livebox next # usage: python orangen.py <4 last digits from wan mac> <4 last digits from serial> # It will just return the PIN # Algorithm and vulnerability by wifi-libre. For more details check https://www.wifi-libre.com/topic-869-todo-sobre-al-algoritmo-wps-livebox-arcadyan-orange-xxxx.html # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # Contact script author: kcdtv@wifi-libre.com # Copyleft (C) 2017 kcdtv @ www.wifi-libre.com import sys def wps_checksum(x): accum = 0 t = x while (t): accum += 3 * (t % 10) t /= 10 accum += t % 10 t /= 10 return (10 - accum % 10) % 10 mac = sys.argv[1] seri = sys.argv[2] s1 = int(seri[0], 16) s2 = int(seri[1], 16) s3 = int(seri[2], 16) s4 = int(seri[3], 16) m1 = int(mac[0], 16) m2 = int(mac[1], 16) m3 = int(mac[2], 16) m4 = int(mac[3], 16) k1 = ( s1 + s2 + m3 + m4 ) & 0xf k2 = ( s3 + s4 + m1 + m2 ) & 0xf d1 = k1 ^ s4 d2 = k1 ^ s3 d3 = k2 ^ m2 d4 = k2 ^ m3 d5 = s4 ^ m3 d6 = s3 ^ m4 d7 = k1 ^ s2 pin = int("0x%1x%1x%1x%1x%1x%1x%1x"%(d1, d2, d3, d4, d5, d6, d7), 16) % 10000000 pin = "%.7d%d" %(pin, wps_checksum(pin)) print (pin)
kcdtv/nmk
orangen.py
Python
gpl-3.0
1,843
notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] def chords(root): n = notes + notes i = n.index(root) return [[n[i], n[i + 4], n[i + 7]], [n[i], n[i + 3], n[i + 7]]]
VladKha/CodeWars
7 kyu/Chords/solve.py
Python
gpl-3.0
206
<?php // check/set default config settings for wikipediacalls function wikipediacalls_defaultsettings( $force=false ) { global $CFG; if (!isset($CFG->filter_wikipediacalls_showkeys) or $force) { if (isset($CFG->filter_wikipediacalls_showkeys)) { set_config( 'filter_wikipediacalls_showkeys', !$CFG->filter_wikipediacalls_showkeys ); set_config( 'filter_wikipediacalls_showkeys', '' ); } else { set_config( 'filter_wikipediacalls_showkeys', 1 ); } } if (!isset($CFG->filter_wikibaseurl) or $force) { if (isset($CFG->filter_wikibaseurl)) { set_config( 'filter_wikibaseurl', !$CFG->filter_wikibaseurl ); set_config( 'filter_wikibaseurl', '' ); } else { $lang = substr($CFG->lang, 0, 2); set_config( 'filter_wikibaseurl', "http://<%%LANG%%>.wikipedia.org/wiki/" ); } } } ?>
nitro2010/moodle
filter/wikipediacalls/defaultsettings.php
PHP
gpl-3.0
957
// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sessions import ( "encoding/gob" "fmt" "net/http" "time" "github.com/gorilla/context" ) // Default flashes key. const flashesKey = "_flash" // Options -------------------------------------------------------------------- // Options stores configuration for a session or session store. // // Fields are a subset of http.Cookie fields. type Options struct { Path string Domain string // MaxAge=0 means no 'Max-Age' attribute specified. // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'. // MaxAge>0 means Max-Age attribute present and given in seconds. MaxAge int Secure bool HttpOnly bool } // Session -------------------------------------------------------------------- // NewSession is called by session stores to create a new session instance. func NewSession(store Store, name string) *Session { return &Session{ Values: make(map[interface{}]interface{}), store: store, name: name, Options: new(Options), } } // Session stores the values and optional configuration for a session. type Session struct { // The ID of the session, generated by stores. It should not be used for // user data. ID string // Values contains the user-data for the session. Values map[interface{}]interface{} Options *Options IsNew bool store Store name string } // Flashes returns a slice of flash messages from the session. // // A single variadic argument is accepted, and it is optional: it defines // the flash key. If not defined "_flash" is used by default. func (s *Session) Flashes(vars ...string) []interface{} { var flashes []interface{} key := flashesKey if len(vars) > 0 { key = vars[0] } if v, ok := s.Values[key]; ok { // Drop the flashes and return it. delete(s.Values, key) flashes = v.([]interface{}) } return flashes } // AddFlash adds a flash message to the session. // // A single variadic argument is accepted, and it is optional: it defines // the flash key. If not defined "_flash" is used by default. func (s *Session) AddFlash(value interface{}, vars ...string) { key := flashesKey if len(vars) > 0 { key = vars[0] } var flashes []interface{} if v, ok := s.Values[key]; ok { flashes = v.([]interface{}) } s.Values[key] = append(flashes, value) } // Save is a convenience method to save this session. It is the same as calling // store.Save(request, response, session). You should call Save before writing to // the response or returning from the handler. func (s *Session) Save(r *http.Request, w http.ResponseWriter) error { return s.store.Save(r, w, s) } // Name returns the name used to register the session. func (s *Session) Name() string { return s.name } // Store returns the session store used to register the session. func (s *Session) Store() Store { return s.store } // Registry ------------------------------------------------------------------- // sessionInfo stores a session tracked by the registry. type sessionInfo struct { s *Session e error } // contextKey is the type used to store the registry in the context. type contextKey int // registryKey is the key used to store the registry in the context. const registryKey contextKey = 0 // GetRegistry returns a registry instance for the current request. func GetRegistry(r *http.Request) *Registry { registry := context.Get(r, registryKey) if registry != nil { return registry.(*Registry) } newRegistry := &Registry{ request: r, sessions: make(map[string]sessionInfo), } context.Set(r, registryKey, newRegistry) return newRegistry } // Registry stores sessions used during a request. type Registry struct { request *http.Request sessions map[string]sessionInfo } // Get registers and returns a session for the given name and session store. // // It returns a new session if there are no sessions registered for the name. func (s *Registry) Get(store Store, name string) (session *Session, err error) { if !isCookieNameValid(name) { return nil, fmt.Errorf("sessions: invalid character in cookie name: %s", name) } if info, ok := s.sessions[name]; ok { session, err = info.s, info.e } else { session, err = store.New(s.request, name) session.name = name s.sessions[name] = sessionInfo{s: session, e: err} } session.store = store return } // Save saves all sessions registered for the current request. func (s *Registry) Save(w http.ResponseWriter) error { var errMulti MultiError for name, info := range s.sessions { session := info.s if session.store == nil { errMulti = append(errMulti, fmt.Errorf( "sessions: missing store for session %q", name)) } else if err := session.store.Save(s.request, w, session); err != nil { errMulti = append(errMulti, fmt.Errorf( "sessions: error saving session %q -- %v", name, err)) } } if errMulti != nil { return errMulti } return nil } // Helpers -------------------------------------------------------------------- func init() { gob.Register([]interface{}{}) } // Save saves all sessions used during the current request. func Save(r *http.Request, w http.ResponseWriter) error { return GetRegistry(r).Save(w) } // NewCookie returns an http.Cookie with the options set. It also sets // the Expires field calculated based on the MaxAge value, for Internet // Explorer compatibility. func NewCookie(name, value string, options *Options) *http.Cookie { cookie := &http.Cookie{ Name: name, Value: value, Path: options.Path, Domain: options.Domain, MaxAge: options.MaxAge, Secure: options.Secure, HttpOnly: options.HttpOnly, } if options.MaxAge > 0 { d := time.Duration(options.MaxAge) * time.Second cookie.Expires = time.Now().Add(d) } else if options.MaxAge < 0 { // Set it to the past to expire now. cookie.Expires = time.Unix(1, 0) } return cookie } // Error ---------------------------------------------------------------------- // MultiError stores multiple errors. // // Borrowed from the App Engine SDK. type MultiError []error func (m MultiError) Error() string { s, n := "", 0 for _, e := range m { if e != nil { if n == 0 { s = e.Error() } n++ } } switch n { case 0: return "(0 errors)" case 1: return s case 2: return s + " (and 1 other error)" } return fmt.Sprintf("%s (and %d other errors)", s, n-1) }
tanji/replication-manager
vendor/github.com/gorilla/sessions/sessions.go
GO
gpl-3.0
6,457
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2015 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * AverageClusteringCoefficient.java * * Created on 30. toukokuuta 2007, 14:43 * */ package org.wandora.application.tools.statistics; import org.wandora.application.*; import org.wandora.application.tools.*; import org.wandora.topicmap.*; import org.wandora.application.contexts.*; import java.util.*; import javax.swing.*; import org.wandora.application.gui.*; import org.wandora.topicmap.layered.*; /** * * @author olli */ public class AverageClusteringCoefficient extends AbstractWandoraTool { public AverageClusteringCoefficient() { } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/clustering_coefficient.png"); } @Override public String getName() { return "Topic map clustering coefficient"; } @Override public String getDescription() { return "Tool is used calculate average clustering coefficient in layer."; } @Override public boolean requiresRefresh() { return false; } @Override public void execute(Wandora admin, Context context) throws TopicMapException { TopicMap tm = solveContextTopicMap(admin, context); String tmTitle = solveNameForTopicMap(admin, tm); if(tm==null) return; int numTopics=-1; if(!(tm instanceof LayerStack)) numTopics=tm.getNumTopics(); setDefaultLogger(); if(numTopics!=-1) setProgressMax(numTopics); TopicClusteringCoefficient.TopicNeighborhood n = new TopicClusteringCoefficient.DefaultNeighborhood(); log("Calculating clustering coefficient of '"+tmTitle+"'"); log("Preparing topics 1/3"); Iterator<Topic> iter=tm.getTopics(); TopicHashMap<Integer> ids=new TopicHashMap<Integer>(); int counter=0; while(iter.hasNext() && !forceStop()){ if((counter%100)==0) setProgress(counter); Topic t = iter.next(); ids.put(t,counter); counter++; } log("Preparing connections 2/3"); HashMap<Integer,HashSet<Integer>> connections=new HashMap<Integer,HashSet<Integer>>(); iter=tm.getTopics(); counter=0; while(iter.hasNext() && !forceStop()){ if((counter%100)==0) setProgress(counter); Topic topic = iter.next(); Integer t=ids.get(topic); counter++; if(t==null) continue; // happens if topic has no basename, subject identifiers or subject locator HashSet<Integer> cs=new HashSet<Integer>(); connections.put(t,cs); for(Topic p : n.getNeighborhood(topic)){ Integer pint=ids.get(p); if(pint==null) continue; cs.add(pint); } } log("Calculating clustering coefficient 3/3"); double sum=0.0; counter=0; iter=tm.getTopics(); while(iter.hasNext() && !forceStop()){ if((counter%100)==0) setProgress(counter); Topic topic = iter.next(); int associationCounter=0; Integer t=ids.get(topic); counter++; if(t==null) continue; // happens if topic has no basename, subject identifiers or subject locator HashSet<Integer> tn=connections.get(t); if(tn.size()<=1) continue; for(Integer p : tn){ HashSet<Integer> pn=connections.get(p); for(Integer r : pn){ if(p.equals(r)) continue; if(tn.contains(r)) associationCounter++; } } sum+=(double)associationCounter/(double)(tn.size()*(tn.size()-1)); } /* double sum=0.0; int counter=0; Iterator<Topic> iter=tm.getTopics(); while(iter.hasNext()){ if((counter%100)==0) setProgress(counter); Topic t = iter.next(); sum+=TopicClusteringCoefficient.getClusteringCoefficientFor(t,n); counter++; } */ double c=sum/(double)counter; if(forceStop()) { log("Operation cancelled!"); } else { log("Average coefficient for layer "+(tmTitle==null?"":(tmTitle+" "))+"is "+c); } setState(WAIT); } }
Anisorf/ENCODE
encode/src/org/wandora/application/tools/statistics/AverageClusteringCoefficient.java
Java
gpl-3.0
5,374
<?php /* ---------------------------------------------------------------------- * app/lib/pawtucket/BaseMultiSearchController.php : * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2013-2015 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * ---------------------------------------------------------------------- */ require_once(__CA_APP_DIR__.'/helpers/searchHelpers.php'); require_once(__CA_LIB_DIR__.'/ca/ResultContext.php'); abstract class BaseMultiSearchController extends ActionController { # ------------------------------------------------------- /** * */ protected $ops_find_type = 'multisearch'; /** * */ protected $opa_result_contexts = array(); /** * List of searches to execute */ protected $opa_search_blocks = array(); /** * */ protected $opa_access_values = array(); /** * Search configuation file */ protected $config = null; # ------------------------------------------------------- public function __construct(&$po_request, &$po_response, $pa_view_paths=null) { parent::__construct($po_request, $po_response, $pa_view_paths); $this->config = Configuration::load(__CA_THEME_DIR__.'/conf/search.conf'); $this->opa_search_blocks = $this->config->getAssoc('multisearchTypes'); // Create result context for each block $va_tables = array(); foreach($this->opa_search_blocks as $vs_block => $va_block_info) { $va_tables[$va_block_info['table']] = 1; $this->opa_result_contexts[$vs_block] = new ResultContext($po_request, $va_block_info['table'], $this->ops_find_type, $vs_block); $this->opa_result_contexts[$vs_block]->setAsLastFind(false); } // Create generic contexts for each table in multisearch (no specific block); used to house search history and overall counts // when there is more than one block for a given table foreach(array_keys($va_tables) as $vs_table) { $this->opa_result_contexts["_multisearch_{$vs_table}"] = new ResultContext($po_request, $vs_table, $this->ops_find_type); } $this->opa_access_values = caGetUserAccessValues($po_request); } # ------------------------------------------------------- /** * Search handler (returns search form and results, if any) * Most logic is contained in the BaseSearchController->Search() method; all you usually * need to do here is instantiate a new subject-appropriate subclass of BaseSearch * (eg. ObjectSearch for objects, EntitySearch for entities) and pass it to BaseSearchController->Search() */ public function Index($pa_options=null) { if (!is_array($this->opa_result_contexts) || !sizeof($this->opa_result_contexts)) { // TODO: throw error - no searches are defined return false; } $o_first_result_context = array_shift(array_values($this->opa_result_contexts)); $vs_search = $o_first_result_context->getSearchExpression(); $vs_search_display = $o_first_result_context->getSearchExpressionForDisplay(); $this->view->setVar('search', $vs_search); $this->view->setVar('searchForDisplay', $vs_search_display); $this->view->setVar("config", $this->config); $this->view->setVar('blocks', $this->opa_search_blocks); $this->view->setVar('blockNames', array_keys($this->opa_search_blocks)); $this->view->setVar('results', $va_results = caPuppySearch($this->request, $vs_search, $this->opa_search_blocks, array('access' => $this->opa_access_values, 'contexts' => $this->opa_result_contexts, 'matchOnStem' => (bool)$this->config->get('matchOnStem')))); if ($this->request->isAjax() && ($vs_block = $this->request->getParameter('block', pString))) { if (!isset($va_results[$vs_block]['html'])) { // TODO: throw error - no results return false; } $this->response->addContent($va_results[$vs_block]['html']); if (($o_context = $this->opa_result_contexts[$vs_block])) { if (isset($va_results[$vs_block]['sort'])) { $o_context->setCurrentSort($va_results[$vs_block]['sort']); } if (isset($va_results[$vs_block]['sortDirection'])) { $o_context->setCurrentSortDirection($va_results[$vs_block]['sortDirection']); } $o_context->setResultList(is_array($va_results[$vs_block]['ids']) ? $va_results[$vs_block]['ids'] : array()); $o_context->saveContext(); } return; } foreach($this->opa_result_contexts as $vs_block => $o_context) { $o_context->setParameter('search', $vs_search); if (!isset($va_results[$vs_block]['ids']) || !is_array($va_results[$vs_block]['ids'])) { continue; } $o_context->setResultList(is_array($va_results[$vs_block]['ids']) ? $va_results[$vs_block]['ids'] : array()); if($va_results[$vs_block]['sort']) { $o_context->setCurrentSort($va_results[$vs_block]['sort']); } if (isset($va_results[$vs_block]['sortDirection'])) { $o_context->setCurrentSortDirection($va_results[$vs_block]['sortDirection']); } $o_context->saveContext(); } $this->render('Search/multisearch_results_html.php'); } # ------------------------------------------------------- abstract public static function getReturnToResultsUrl($po_request); # ------------------------------------------------------- } ?>
libis/pa_cct
app/lib/pawtucket/BaseMultiSearchController.php
PHP
gpl-3.0
6,189
// __ // ____ ___ ___ ____ ___ ____ / /__ __ // / __ `__ \/ _ \/ __ `__ \/ __ \ / __/ | / / // / / / / / / __/ / / / / / /_/ // /_ | |/ / // /_/ /_/ /_/\___/_/ /_/ /_/\____(_)__/ |___/ // // // Created by Memo Akten, www.memo.tv // // ofxMSAControlFreak // #include "ofxMSAControlFreak/src/ofxMSAControlFreak.h" namespace msa { namespace controlfreak { //-------------------------------------------------------------- Parameter::Parameter(string name, ParameterGroup *parent, ParameterValueI *pv) : _pparent(parent), _name(name) { _paramValue = pv; if(pv) { _paramValue->setParameter(this); } _xmlTag = "Parameter"; _xmlTagId = 0; Master::instance().add(this); // ofLogVerbose() << "msa::controlfreak::Parameter::Parameter: " << getPath(); } //-------------------------------------------------------------- Parameter::~Parameter() { ofLogVerbose() << "msa::controlfreak::Parameter::~Parameter(): " << getPath(); if(_paramValue) delete _paramValue; // TODO } //-------------------------------------------------------------- Parameter& Parameter::setName(string s) { // ofLogVerbose() << "msa::controlfreak::Parameter::setName: " << s; _name = s; return *this; } //-------------------------------------------------------------- string Parameter::getName() const { return _name; } //-------------------------------------------------------------- Parameter& Parameter::setTooltip(string s) { _tooltip = s; return *this; } //-------------------------------------------------------------- string Parameter::getTooltip() const { return _tooltip; } //-------------------------------------------------------------- string Parameter::getPath() const { return _pparent ? _pparent->getPath() + getPathDivider() + _name : _name; } //-------------------------------------------------------------- void Parameter::setParent(ParameterGroup *parent) { ofLogVerbose() << "msa::controlfreak::Parameter::setParent: '" << getPath() << "' to '" << (parent ? parent->getName(): "NULL") << "'"; _pparent = parent; } //-------------------------------------------------------------- ParameterGroup* Parameter::getParent() const { return _pparent; } //-------------------------------------------------------------- string Parameter::getTypeName() const { return typeid(*this).name(); } //-------------------------------------------------------------- ParameterValueI* Parameter::getParamValue() { return _paramValue; } //-------------------------------------------------------------- void Parameter::writeToXml(ofxXmlSettings &xml, bool bFullSchema) { ofLogVerbose() << "msa::controlfreak::Parameter::writeToXml: " << getPath(); _xmlTagId = xml.addTag(_xmlTag); xml.addAttribute(_xmlTag, "type", getTypeName(), _xmlTagId); xml.addAttribute(_xmlTag, "name", getName(), _xmlTagId); if(_paramValue) _paramValue->writeToXml(xml, bFullSchema); if(bFullSchema) { xml.addAttribute(_xmlTag, "path", getPath(), _xmlTagId); xml.addAttribute(_xmlTag, "tooltip", getTooltip(), _xmlTagId); // xml.addAttribute(_xmlTag, "parent", _pparent ? _pparent->getName(): "none", _xmlTagId); } } //-------------------------------------------------------------- void Parameter::readFromXml(ofxXmlSettings &xml, bool bFullSchema) { ofLogVerbose() << "msa::controlfreak::Parameter::readFromXml: " << getPath(); if(_paramValue) _paramValue->readFromXml(xml, bFullSchema); if(bFullSchema) { setTooltip(xml.getAttribute(_xmlTag, "tooltip", "", _xmlTagId)); } } //-------------------------------------------------------------- // // Controller stuff // void Parameter::addSender(ControllerI *controller) { // controllers.addSender(controller); // controller->setParam(this); // } // // //-------------------------------------------------------------- // void Parameter::addReceiver(ControllerI *controller) { // controllers.addReceiver(controller); // controller->setParam(this); // } } }
memo/VolumeRunner
addons/ofxMSAControlFreak/src/Parameter.cpp
C++
gpl-3.0
4,844
//Game.cpp #include "Game.h" #include "Load.h" #include <sound.hpp> #include <report.hpp> extern int stateID; extern int nextState; extern std::vector<Texture*>textureList; extern AudioEngine *audio; extern AudioSoundFX *snd_bonusget, *snd_hit, *snd_pow; extern AudioMusic *audio_music; extern GLFT_Font font; extern GLFT_Font fontLevel; extern GLFT_Font font_small; Game::Game() { currentState = NULL; } Game::~Game() { report("Game destructor", MSG_DEBUG); } int Game::Exec() { report("Game::Exec started", MSG_DEBUG); if(!Init()) { report("Game::Init() failed", MSG_DEBUG); report("Error initializing game engine", MSG_ERROR); return -1; } report("Game::Exec finished", MSG_DEBUG); } bool Game::Init() { Window window; report("This is DEBUG build! It will log some debug info. If this is not what you want please recompile without -DDEBUG definition.", MSG_DEBUG); report("Game::Init started", MSG_DEBUG); if(window.error() == true) { report("error in window", MSG_ERROR); return 1; } if(InitGL() == false) { return false; } report("Loading files...", MSG_DEBUG); if(LoadFiles() == false) { report("Some files failed to load :(", MSG_ERROR); return false; } stateID = STATE_INTRO; //Set the current game state object currentState = new Intro(); MainLoop(); return true; } void Game::change_state() { //If the state needs to be changed if( nextState != STATE_NULL ) { //Delete the current state if( nextState != STATE_EXIT ) { delete currentState; } //Change the state switch( nextState ) { case STATE_TITLE: currentState = new Title(); break; case STATE_HELP: currentState = new Help(); break; case STATE_LEVEL_1: currentState = new Level_1(1,"level_1.map"); break; case STATE_LEVEL_2: currentState = new Level_1(2,"level_2.map"); break; case STATE_LEVEL_3: currentState = new Level_1(3,"level_3.map"); break; case STATE_INTRO: currentState = new Title(); break; case STATE_GAMEOVER: currentState = new Title(); break; } //Change the current state ID stateID = nextState; //NULL the next state ID nextState = STATE_NULL; } } bool Game::Start() { return true; } bool Game::InitGL() { SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 32); glEnable( GL_TEXTURE_2D ); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glClearColor(0,0,0,1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if(glGetError() != GL_NO_ERROR) { report("gl not init, " + glGetError(), MSG_ERROR); return false; } return true; } bool Game::LoadFiles() { std::string filename; /* Load bricks */ report("Loading bricks...", MSG_DEBUG); LoadBrick("brick_beton.png"); LoadBrick("brick_strong.png"); LoadBrick("brick_portal_a.png"); LoadBrick("brick_portal_b.png"); LoadBrick("brick.png"); report("Finished loading bricks.", MSG_DEBUG); /* Load other textures */ report("Loading other textures...", MSG_DEBUG); LoadTexture("bita.bmp"); LoadTexture("ball.png"); LoadTexture("bg.png"); LoadTexture("bg_intro.png"); LoadTexture("bg_title.png"); LoadTexture("bg_Help.png"); LoadTexture("bonus_speed_up.png"); LoadTexture("bonus_speed_down.png"); LoadTexture("bonus_life.png"); LoadTexture("bonus_die.png"); LoadTexture("bonus_add.png"); LoadTexture("heart.png"); LoadTexture("particle.png"); report("Finished loading other textures", MSG_DEBUG); /* Load fonts */ report("Loading fonts...", MSG_DEBUG); filename = path_construct("fonts", "aerial.ttf"); font.open(filename, 10); fontLevel.open(filename, 50); font_small.open(filename, 20); report("Finished loading fonts", MSG_DEBUG); /* Load sounds */ report("Loading sounds...", MSG_DEBUG); snd_bonusget = new AudioSoundFX("bonus_get.ogg"); snd_hit = new AudioSoundFX("hit.ogg"); snd_pow = new AudioSoundFX("pow.ogg"); report("Finished loading sounds...", MSG_DEBUG); /* Load music */ audio_music = new AudioMusic(); return true; } bool Game::MainLoop() { Timer fps; Window window; while(stateID != STATE_EXIT) { fps.Start(); while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_q)) { currentState->set_next_state( STATE_EXIT ); } window.handle_events(event); currentState->handle_events(event); } //deltaTicks = fps.Get_Ticks(); // if(window.error() == true) // { // return 1; // } currentState->logic(); fps.Start(); //Change state if needed change_state(); //Do state rendering glClear(GL_COLOR_BUFFER_BIT); currentState->render(); SDL_GL_SwapBuffers(); audio_music->CheckPlay(); if(fps.Get_Ticks() < 1000/FRAMES_PER_SECOND) { SDL_Delay((1000/FRAMES_PER_SECOND) - fps.Get_Ticks()); } } return true; } void Game::Close() { report("Game::Close()", MSG_DEBUG); font.release(); fontLevel.release(); for(unsigned int i = 0; i < textureList.size(); i++) { textureList.erase(textureList.begin(), textureList.end()); } //imageList.erase(imageList.begin(),imageList.end()); Mix_HaltMusic(); delete audio_music; }
duganet/arkilloid
src/Game.cpp
C++
gpl-3.0
5,836
<?php /** * This file is part of the Eki-NRP package. * * (c) Ekipower * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Eki\NRP\Common\Tests\Working\PlanItem; use Eki\NRP\Common\Working\PlanItemTypeInterface; use PHPUnit\Framework\TestCase; class BasedPlanItemTest extends TestCase { public function testDummy() { } protected function createPlanItemType($matchThing) { $planItemType = $this->getMockBuilder(PlanItemTypeInterface::class) ->setMethods(['is']) ->getMockForAbstractClass() ; $planItemType->expects($this->any()) ->method('is') ->will($this->returnCallback(function ($thing) use ($matchThing) { if ($thing === $matchThing) return true; return false; })) ; return $planItemType; } }
eki-nrp/common
src/Tests/Working/PlanItem/BasedPlanItemTest.php
PHP
gpl-3.0
834
/** * Copyright (C) 2017 Order of the Bee * * This file is part of Community Support Tools * * Community Support Tools is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Community Support Tools is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Community Support Tools. If not, see <http://www.gnu.org/licenses/>. */ /* * Linked to Alfresco * Copyright (C) 2005-2017 Alfresco Software Limited. */ function getSitesCount() { var list = monitorJobSearchService.getJobsHistory("1", "SITES_COUNT","FINISHED"); if (list) { var node = search.findNode(list.get(0).nodeRef); model.node = jsonUtils.toObject(node.content); } else { model.node = {'sitesCount': "UNKNOWN"}; } }
Vitezslav-Sliz/tieto-alfresco-repository_monitor
health-monitor-repo/src/main/resources/alfresco/extension/templates/webscripts/com/tieto/healthy-addon/admin/healthy-repo-addon/sites.lib.js
JavaScript
gpl-3.0
1,177
package mathe.strukturen; import java.io.Serializable; public interface Kategorie<OBJ extends Serializable, MOR extends Serializable> { Menge<OBJ> objecte(); Menge<MOR> morphismen(OBJ from, OBJ to); }
ThoNill/Mathe
Mathe/src/mathe/strukturen/Kategorie.java
Java
gpl-3.0
213
/* TrafficSim is simulation of road traffic Copyright (C) 2009 Mariusz Ceier, Adam Rutkowski This file is part of TrafficSim TrafficSim is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TrafficSim is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with TrafficSim. If not, see <http://www.gnu.org/licenses/>. */ package trafficsim; // imports {{{ import trafficsim.data.CarData; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedList; import java.util.SortedMap; //}}} /** * * @author Adam Rutkowski */ @SuppressWarnings("serial") public class Car implements Serializable //{{{ { // Variables {{{ private final int id; private static int carsCount = 0; private float nextCarDistance; private Position position; private float speed; private float acceleration; private float maxSpeed = 80; private final float maxAcceleration; private boolean collided = false; // if there was a collision private Parking currentParking; /** * The route that this car is about to move on. */ private LinkedList<Lane> plannedRoute; private boolean newCar = true; //}}} private synchronized int getNewId() //{{{ { return Car.carsCount++; } //}}} /** * Default constructor - Car doesn't know anything */ public Car() //{{{ { this.id = getNewId(); this.currentParking = null; this.maxAcceleration = 10; this.position = new Position(); } //}}} public Car(CarData data, Model model) {//{{{ this.id = data.id; this.speed = data.speed; this.acceleration = data.acceleration; this.collided = data.collided; this.currentParking = model.getParkingById(data.parkingId); this.maxAcceleration = data.maxAcceleration; this.maxSpeed = data.maxSpeed; this.plannedRoute = new LinkedList<Lane>(); for(int i : data.plannedRoute) { plannedRoute.add(model.getLaneById(i)); } if (data.parkingId == -1) this.currentParking = null; else this.currentParking = model.getParkingById(data.parkingId); this.position = new Position(); this.position.setCoord(data.positionCoord); this.position.setLane(model.getLaneById(data.positionLane)); this.position.setInfo(data.positionInfo); }//}}} public synchronized boolean isParked() //{{{ { return (this.currentParking != null); } //}}} public synchronized void park(Parking parking) //{{{ { this.currentParking = parking; this.position.setLane(null); this.position.info = Position.e_info.NOT_DRIVING; parking.park(this); } //}}} public synchronized void goToParkingOutQueue() //{{{ { if (isParked() == false) return ; this.currentParking.goToLeavingQueue(this); this.plannedRoute = new LinkedList<Lane>(); this.plannedRoute.add(this.currentParking.laneOut()); }//}}} public boolean leaveParking() //{{{ { if (this.currentParking == null) return false; this.currentParking.goToLeavingQueue(this); if (currentParking.canLeaveParking(this)) { this.currentParking.carIsLeaving(this); this.currentParking = null; this.position.setLane(this.plannedRoute.get(0)); this.plannedRoute.remove(0); this.position.setCoord(0); return true; } else return false; } //}}} /*** * Calculates new position and speed after specified time period. * @param timeUnits * @throws java.lang.Exception */ public synchronized void move(int timeMiliseconds) //{{{ { if (this.position.info == Position.e_info.NOT_DRIVING) return; // check what will be the car position after one time period Position newPosition = positionAfterTime(timeMiliseconds, 1); // if position has been calculated successfully - set the new position if (newPosition.info == Position.e_info.OK) { // car approached new lane? if (this.position.getLane() != newPosition.getLane()) { // try to put the car on new lane this.position.getLane().carIsLeaving(this.position.getCoord()); if (!newPosition.getLane().putCar(newPosition.getCoord(), this)) return; } else // try to move car on current lane if (!this.position.getLane().moveCar( this.position.getCoord(), newPosition.getCoord() )) return; this.position.setLane(newPosition.getLane()); this.position.setCoord(newPosition.getCoord()); this.speed += this.acceleration / 1000 * timeMiliseconds; } } //}}} // Not synchronized - id is a final field public int getId() //{{{ { return this.id; } //}}} public synchronized void setRoute(LinkedList<Lane> route) //{{{ { this.plannedRoute = route; } //}}} public synchronized LinkedList<Lane> getRoute() //{{{ { return this.plannedRoute; } //}}} public synchronized boolean canLeaveParking(int safeDistance) //{{{ { if (this.currentParking != null) if (this.currentParking.canLeaveParking(this)) { if (this.plannedRoute.isEmpty()) return false; Lane laneOut = this.currentParking.laneOut(); if (this.plannedRoute.get(0) != laneOut) return false; getNextCar(); float nextDistance = getNextCarDistance(); if (nextDistance > laneOut.getLength()) return true; if (nextDistance >= safeDistance) return true; else return false; } return false; } //}}} public synchronized Position positionAfterTime( int timeMiliseconds, int periodsCount ) {//{{{ Position result = new Position(); result.setLane(this.position.getLane()); result.setCoord(this.position.getCoord()); float timeSeconds = (float) timeMiliseconds / 1000; if (this.position.getLane() == null) { result.info = Position.e_info.NOT_DRIVING; return result; } float newCoordinate; float current_speed = this.speed; float current_acceleration = this.acceleration; for (int i=0; i<periodsCount; i++) { newCoordinate =result.getCoord() + timeSeconds*current_speed; current_speed += (timeSeconds * current_acceleration); if (current_speed > this.maxSpeed) { current_speed = this.maxSpeed; current_acceleration = 0; } else if (current_speed < 0) { current_speed = 0; current_acceleration = 0; } result.info = Position.e_info.OK; if (newCoordinate <= result.getLane().getLength()) { result.setCoord(newCoordinate); } else { /* calculate on which lane we are at the moment */ int sum = result.getLane().getLength(); while(sum <= newCoordinate) { // get the next lane in g boolean routeIsEmpty = this.plannedRoute.isEmpty(); boolean endOfRoute = (this.plannedRoute.indexOf(result.getLane()) == this.plannedRoute.size()-1 ); if (routeIsEmpty || endOfRoute) { Lane laneAterRoute = result.getLane().getDefaultLane(); if (laneAterRoute == null) { result.setCoord(result.getLane().getLength()); this.collided = true; // Collision - end of // route return result; } else { result.info = Position.e_info.OUT_OF_RANGE; result.setLane(laneAterRoute); } } else { if(plannedRoute.contains(result.getLane())) { result.setLane(this.plannedRoute.get( this.plannedRoute.indexOf(result.getLane()) )); } else result.setLane(plannedRoute.get(0)); } sum += result.getLane().getLength(); } result.setCoord(newCoordinate - (sum - result.getLane().getLength())); } } return result; }//}}} public synchronized Position getPosition() //{{{ { return this.position; } //}}} /** * Returns car preceding this one on its planned route. * @return */ public synchronized Car getNextCar() //{{{ { if (this.position.getLane() != null) // car is on some lane { SortedMap<Integer, Car> carsOnLane = this.position.getLane().getCars(); // is the lane empty? if (carsOnLane.isEmpty() == false) // is the car on this lane? (if no, something is wrong) if (carsOnLane.containsValue(this)) // is 'car' not the last car on the lane? if (carsOnLane.lastKey() != this.position.getCoord()) { // get the part of car list starting with this car Iterator<Car> iter = carsOnLane.tailMap( (int) this.position.getCoord() ).values().iterator(); // get this car element of the list iter.next(); if (iter.hasNext()) { // get next element of the list Car next = iter.next(); // calculate distance to that car this.nextCarDistance = next.getPosition().getCoord() - position.getCoord(); // return the next car return next; } } // preceding car not found on current lane. Calculate distance from // this car to the end of the lane for use in further calculations. this.nextCarDistance = this.position.getLane().getLength() - this.position.getCoord(); } else this.nextCarDistance = 0; //since the car is not riding, the // distance to next car will be calculated basing on the // planned route <B>only</B>, so for now the distance is 0. if (this.plannedRoute.isEmpty() == false) // are there some lanes { // planned to move on? // try to find the closest car on planned route int i = 0; Lane laneOnRoute = null; while(i < this.plannedRoute.size()) { laneOnRoute = this.plannedRoute.get(i); if (laneOnRoute.isEmpty() == false) break; // No car on this lane, distance to next car is increased by // this lane length. this.nextCarDistance += laneOnRoute.getLength(); i++; } if (i==this.plannedRoute.size()) // whole planned car route is empty return null; // distance to the next car is increased by that car position // on its lane this.nextCarDistance = laneOnRoute.getFirstCar().getPosition().getCoord(); return laneOnRoute.getFirstCar(); } else return null; } //}}} /** * Works properly only after successful call to getNextCar(). * @return distance to the next car on this car planned route. */ public synchronized float getNextCarDistance() //{{{ { return this.nextCarDistance; } //}}} /** * Sets the car on the beginning of its planned route */ public synchronized void startMoving(float accel) //{{{ { // check if we can move on if ( this.position.getLane() != null || this.plannedRoute.isEmpty() || !this.currentParking.canLeaveParking(this)) { return; } // try to put car on the lane if (!this.plannedRoute.get(0).putCar(0, this)) return; // set up new position this.position.setLane(this.plannedRoute.get(0)); this.position.setCoord(0); this.position.info = Position.e_info.OK; this.plannedRoute.remove(0); // leave the parking this.currentParking.carIsLeaving(this); this.currentParking = null; // set new state if (accel > maxAcceleration) accel = maxAcceleration; this.speed = 0; this.acceleration = accel; } //}}} public synchronized float getAcceleration() //{{{ { return this.acceleration; } //}}} public float getMaxAcceleration() { return this.maxAcceleration; } public float getSpeed() //{{{ { return this.speed; } //}}} public void changeAcceleration(float newAcceleration) //{{{ { } //}}} public synchronized static int getCarsCount() { return carsCount; } public synchronized float getMaxSpeed() { return maxSpeed; } public synchronized Parking getCurrentParking() { return currentParking; } public synchronized LinkedList<Lane> getPlannedRoute() { return plannedRoute; } public synchronized void setPlannedRoute(LinkedList<Lane> plannedRoute) { this.plannedRoute = plannedRoute; } public synchronized void setAcceleration(float newAcceleration) { if (newAcceleration > maxAcceleration || -1.0*newAcceleration > maxAcceleration) { if (newAcceleration < 0) this.acceleration = (float)-1.0*maxAcceleration; else this.acceleration = maxAcceleration; } else this.acceleration = newAcceleration; } public synchronized boolean isCollided() { return collided; } public synchronized void setCollided(boolean collided) { this.collided = collided; } public boolean isNewCar() { return newCar; } public void setNewCar(boolean newCar) { this.newCar = newCar; } } //}}} /* vim: set ts=4 sw=4 sts=4 et foldmethod=marker: */
mceier/trafficsim
simulation/src/trafficsim/Car.java
Java
gpl-3.0
16,937
// // Vivado(TM) // rundef.js: a Vivado-generated Runs Script for WSH 5.1/5.6 // Copyright 1986-2017 Xilinx, Inc. All Rights Reserved. // var WshShell = new ActiveXObject( "WScript.Shell" ); var ProcEnv = WshShell.Environment( "Process" ); var PathVal = ProcEnv("PATH"); if ( PathVal.length == 0 ) { PathVal = "C:/Xilinx/Vivado/2017.2/ids_lite/ISE/bin/nt64;C:/Xilinx/Vivado/2017.2/ids_lite/ISE/lib/nt64;C:/Xilinx/Vivado/2017.2/bin;"; } else { PathVal = "C:/Xilinx/Vivado/2017.2/ids_lite/ISE/bin/nt64;C:/Xilinx/Vivado/2017.2/ids_lite/ISE/lib/nt64;C:/Xilinx/Vivado/2017.2/bin;" + PathVal; } ProcEnv("PATH") = PathVal; var RDScrFP = WScript.ScriptFullName; var RDScrN = WScript.ScriptName; var RDScrDir = RDScrFP.substr( 0, RDScrFP.length - RDScrN.length - 1 ); var ISEJScriptLib = RDScrDir + "/ISEWrap.js"; eval( EAInclude(ISEJScriptLib) ); ISEStep( "vivado", "-log board_top.vds -m64 -product Vivado -mode batch -messageDb vivado.pb -notrace -source board_top.tcl" ); function EAInclude( EAInclFilename ) { var EAFso = new ActiveXObject( "Scripting.FileSystemObject" ); var EAInclFile = EAFso.OpenTextFile( EAInclFilename ); var EAIFContents = EAInclFile.ReadAll(); EAInclFile.Close(); return EAIFContents; }
rongcuid/lots-of-subleq-cpus
Subleq V2/SubLEQV2Viv/SubLEQV2Viv.runs/synth_1/rundef.js
JavaScript
gpl-3.0
1,239
from opc.colormap import Colormap from opc.colors import BLACK, BLUE, YELLOW, RED, GREEN from .baseclasses.diamondsquare import DiamondSquare class Art(DiamondSquare): description = "Thin plasma using DiamondSquare and colormap rotation" def __init__(self, matrix, config): super(Art, self).__init__(matrix, self.generate, maxticks=20, interpolate=False) self.colormap = Colormap(130) self.colormap.flat(0, 130, BLACK) self.colormap.flat(20, 30, BLUE) self.colormap.flat(50, 60, YELLOW) self.colormap.flat(80, 90, RED) self.colormap.flat(110, 120, GREEN) self.colormap.soften() self.diamond.generate() def generate(self, matrix, diamond): self.colormap.rotate() self.diamond.translate(matrix, colormap=self.colormap)
ak15199/rop
art/plasma2.py
Python
gpl-3.0
861
<?php /** * Customizer functionality for the Slider section. * * @package Hestia * @since Hestia 1.0 */ /** * Hook controls for Slider section to Customizer. * * @since Hestia 1.0 * @modified 1.1.30 */ function hestia_big_title_customize_register( $wp_customize ) { $selective_refresh = isset( $wp_customize->selective_refresh ) ? true : false; $wp_customize->add_section( 'hestia_big_title', array( 'title' => esc_html__( 'Big Title Section', 'hestia-pro' ), 'panel' => 'hestia_frontpage_sections', 'priority' => 1, ) ); /** * Control for big title background */ $wp_customize->add_setting( 'hestia_big_title_background', array( 'sanitize_callback' => 'esc_url_raw', 'transport' => $selective_refresh ? 'postMessage' : 'refresh', ) ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'hestia_big_title_background', array( 'label' => esc_html__( 'Big Title Background', 'hestia-pro' ), 'section' => 'hestia_big_title', 'priority' => 10, ) ) ); /** * Control for header title */ $wp_customize->add_setting( 'hestia_big_title_title', array( 'sanitize_callback' => 'wp_kses_post', 'transport' => $selective_refresh ? 'postMessage' : 'refresh', ) ); $wp_customize->add_control( 'hestia_big_title_title', array( 'label' => esc_html__( 'Title', 'hestia-pro' ), 'section' => 'hestia_big_title', 'priority' => 15, ) ); /** * Control for header text */ $wp_customize->add_setting( 'hestia_big_title_text', array( 'sanitize_callback' => 'wp_kses_post', 'transport' => $selective_refresh ? 'postMessage' : 'refresh', ) ); $wp_customize->add_control( 'hestia_big_title_text', array( 'label' => esc_html__( 'Text', 'hestia-pro' ), 'section' => 'hestia_big_title', 'priority' => 20, ) ); /** * Control for button text */ $wp_customize->add_setting( 'hestia_big_title_button_text', array( 'sanitize_callback' => 'sanitize_text_field', 'transport' => $selective_refresh ? 'postMessage' : 'refresh', ) ); $wp_customize->add_control( 'hestia_big_title_button_text', array( 'label' => esc_html__( 'Button text', 'hestia-pro' ), 'section' => 'hestia_big_title', 'priority' => 25, ) ); /** * Control for button link */ $wp_customize->add_setting( 'hestia_big_title_button_link', array( 'sanitize_callback' => 'esc_url_raw', 'transport' => $selective_refresh ? 'postMessage' : 'refresh', ) ); $wp_customize->add_control( 'hestia_big_title_button_link', array( 'label' => esc_html__( 'Button URL', 'hestia-pro' ), 'section' => 'hestia_big_title', 'priority' => 30, ) ); $hestia_slider_content = get_theme_mod( 'hestia_slider_content' ); if ( empty( $hestia_slider_content ) ) { $wp_customize->get_setting( 'hestia_big_title_background' )->default = esc_url( get_template_directory_uri() . '/assets/img/slider2.jpg' ); $wp_customize->get_setting( 'hestia_big_title_title' )->default = esc_html__( 'Change in the Customizer', 'hestia-pro' ); $wp_customize->get_setting( 'hestia_big_title_text' )->default = esc_html__( 'Change this subtitle in the customizer.', 'hestia-pro' ); $wp_customize->get_setting( 'hestia_big_title_button_text' )->default = esc_html__( 'Change in the Customizer', 'hestia-pro' ); $wp_customize->get_setting( 'hestia_big_title_button_link' )->default = esc_url( '#' ); } } add_action( 'customize_register', 'hestia_big_title_customize_register' ); /** * Add selective refresh for big title section controls. * * @param WP_Customize_Manager $wp_customize Theme Customizer object. * @since 1.1.31 * @access public */ function hestia_register_big_title_partials( $wp_customize ) { $wp_customize->selective_refresh->add_partial( 'hestia_big_title_title', array( 'selector' => '.carousel .title', 'settings' => 'hestia_big_title_title', 'render_callback' => 'hestia_big_title_title_render_callback', ) ); $wp_customize->selective_refresh->add_partial( 'hestia_big_title_text', array( 'selector' => '.carousel h4', 'settings' => 'hestia_big_title_text', 'render_callback' => 'hestia_big_title_text_render_callback', ) ); $wp_customize->selective_refresh->add_partial( 'hestia_big_title_button', array( 'selector' => '.carousel .buttons', 'settings' => array( 'hestia_big_title_button_text', 'hestia_big_title_button_link' ), 'render_callback' => 'hestia_big_title_button_render_callback', ) ); $wp_customize->selective_refresh->add_partial( 'hestia_big_title_background', array( 'selector' => '.big-title-image', 'settings' => 'hestia_big_title_background', 'render_callback' => 'hestia_big_title_image_callback', )); } add_action( 'customize_register', 'hestia_register_big_title_partials' ); /** * Render callback function for header title selective refresh * * @return string */ function hestia_big_title_title_render_callback() { return get_theme_mod( 'hestia_big_title_title' ); } /** * Render callback function for header subtitle selective refresh * * @return string */ function hestia_big_title_text_render_callback() { return get_theme_mod( 'hestia_big_title_text' ); } /** * Render callback function for header button selective refresh * * @return string */ function hestia_big_title_button_render_callback() { $button_text = get_theme_mod( 'hestia_big_title_button_text' ); $button_link = get_theme_mod( 'hestia_big_title_button_link' ); $output = '<a href="' . $button_link . '" title="' . $button_text . '" class="btn btn-primary btn-lg">' . $button_text . '</a>'; return wp_kses_post( $output ); } /** * Callback function for big title background selective refresh. * * @since 1.1.31 * @access public */ function hestia_big_title_image_callback() { $hestia_big_title_background = get_theme_mod( 'hestia_big_title_background' ); if ( ! empty( $hestia_big_title_background ) ) { ?> <style class="big-title-image-css"> #carousel-hestia-generic .page-header { background-image: url(<?php echo esc_url( $hestia_big_title_background ); ?>) !important; } </style> <?php } }
fletch0098/TripToGo
wp-content/themes/hestia-pro/inc/features/feature-big-title-section.php
PHP
gpl-3.0
6,140
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="fr_FR"> <defaultcodec>UTF-8</defaultcodec> <context> <name>BcdDate</name> <message> <source>encodedDate</source> <translation>Date</translation> </message> </context> <context> <name>BcdMonthYear</name> <message> <source>encodedDate</source> <translation>Date</translation> </message> </context> <context> <name>Block11</name> <message> <source>Unknown Block with TREP 0x11</source> <translation>Type de Bloc Inconnu avec TREP 0x11</translation> </message> <message> <source>header</source> <translation>En-Tête</translation> </message> <message> <source>block11Records</source> <translation>Type d&apos;Entrée Inconnu</translation> </message> </context> <context> <name>Block11Record</name> <message> <source>time</source> <translation>Temps</translation> </message> <message> <source>payloadData</source> <translation>Informations additionnelles</translation> </message> <message> <source>sometimesDuration</source> <translation>Peut être Permanent</translation> </message> <message> <source>cardNumber</source> <translation>Numéro de la Carte</translation> </message> </context> <context> <name>Block13</name> <message> <source>Unknown Block with TREP 0x13</source> <translation>Type de Bloc Inconnu avec TREP 0x13</translation> </message> <message> <source>header</source> <translation>En Tête</translation> </message> <message> <source>block11Records</source> <translation>Type d&apos;Entrée Inconnue</translation> </message> </context> <context> <name>Block14</name> <message> <source>data</source> <translation>Données</translation> </message> <message> <source>Unknown Block with TREP 0x14</source> <translation>Type de Bloc Inconnu avec TREP 0x14</translation> </message> </context> <context> <name>CardActivityDailyRecord</name> <message> <source>activityRecordDate</source> <translation>Date de la Période</translation> </message> <message> <source>activityChangeInfos</source> <translation>Nombre de Modifications d&apos;Activités</translation> </message> <message> <source>activityRecordPreviousLength</source> <translation>Taille de l&apos;enregistrement précédent </translation> </message> <message> <source>Activities on %1</source> <translation>En Activité Depuis %1</translation> </message> <message> <source>activityPresenceCounter</source> <translation>Nombre de Périodes Enregistrées</translation> </message> <message> <source>activityDayDistance</source> <translation>Distance Parcourue</translation> </message> <message> <source>activityRecordLength</source> <translation>Taille des Données de cette période</translation> </message> <message> <source>Visualization</source> <translation>Visualisation</translation> </message> </context> <context> <name>CardCertificate</name> <message> <source>Card Certificate</source> <translation>Certificat de la Carte</translation> </message> <message> <source>certificate</source> <translation>Certificat</translation> </message> </context> <context> <name>CardChipIdentification</name> <message> <source>Card chip identification</source> <translation>Identification du circuit intégré de la carte </translation> </message> <message> <source>icManufacturingReference</source> <translation>Certificat d&apos;Identification de l&apos;Editeur de la carte</translation> </message> <message> <source>icSerialNumber</source> <translation>Numéro de SérieIC selon EN-726-3</translation> </message> </context> <context> <name>CardControlActivityDataRecord</name> <message> <source>controlCardNumber</source> <translation>Numéro de la Carte Contrôle</translation> </message> <message> <source>controlTime</source> <translation>Heure du Contrôle</translation> </message> <message> <source>controlType</source> <translation>Type de Contrôle</translation> </message> <message> <source>Control Activity Data</source> <translation>Vue d&apos;ensemble des contrôles </translation> </message> <message> <source>controlDownloadPeriod</source> <translation>Période du Contrôle</translation> </message> <message> <source>controlVehicleRegistration</source> <translation>Numéro d&apos;immatriculation du Véhicule Contrôlé</translation> </message> </context> <context> <name>CardCurrentUse</name> <message> <source>sessionOpenTime</source> <translation>Début de la Période</translation> </message> <message> <source>Current Usage</source> <translation>Utilisation Actuelle</translation> </message> <message> <source>sessionOpenVehicle</source> <translation>Véhicule utilisé au début de la Période</translation> </message> </context> <context> <name>CardDriverActivity</name> <message> <source>cyclicData</source> <translation>Données Cycliques</translation> </message> <message> <source>Timesheet</source> <translation>Synthèse Mensuelle</translation> </message> <message> <source>Driver Activity Data</source> <translation>Données de l&apos;Activité du Conducteur</translation> </message> <message> <source>cardActivityDailyRecords</source> <translation>Espace affecté à l&apos;enregistrement des activités du conducteur pour chaque jour civil </translation> </message> <message> <source>Timesheet for %1</source> <translation>Synthèse Mensuelle Pour %1</translation> </message> <message> <source>newestRecord</source> <translation>Nouvel Enregistrement</translation> </message> <message> <source>oldestRecord</source> <translation>Ancien Eregistrement</translation> </message> <message> <source>Driving</source> <translation>Conduite</translation> </message> <message> <source>Working</source> <translation>Travail</translation> </message> <message> <source>Rest</source> <translation>Repos</translation> </message> <message> <source>Available</source> <translation>Disponible</translation> </message> <message> <source>Summary</source> <translation>Total</translation> </message> </context> <context> <name>CardDrivingLicenseInformation</name> <message> <source>drivingLicenseNumber</source> <translation>Numéro du Permis de Conduire</translation> </message> <message> <source>drivingLicenseIssuingNation</source> <translation>Pays d&apos;émission du Permis de Conduire</translation> </message> <message> <source>drivingLicenseIssuingAuthorithy</source> <translation>Autorité délivrant le Permis de Conduire</translation> </message> <message> <source>Driving License Info</source> <translation>Information du Permis de Conduire</translation> </message> </context> <context> <name>CardEventData</name> <message> <source>cardEventRecords</source> <translation>Entrées des événements</translation> </message> <message> <source>Events Data</source> <translation>Données des événements</translation> </message> </context> <context> <name>CardEventRecord</name> <message> <source>eventVehicleRegistration</source> <translation>Identification de l&apos;immatriculation du véhicule</translation> </message> <message> <source>eventTime</source> <translation>Heure de l&apos;événement</translation> </message> <message> <source>eventType</source> <translation>Type d&apos;événement</translation> </message> </context> <context> <name>CardFaultData</name> <message> <source>cardFaultRecords</source> <translation>Enregistrement des erreurs</translation> </message> <message> <source>Faults Data</source> <translation>Données des erreurs</translation> </message> </context> <context> <name>CardIccIdentification</name> <message> <source>Card ICC identification</source> <translation>Information et Identification de la Puce </translation> </message> <message> <source>cardExtendedSerialNumber</source> <translation>Identfication complète de la Carte</translation> </message> <message> <source>cardApprovalNumber</source> <translation>Numéro d&apos;homologation de la Carte</translation> </message> <message> <source>icIdentifier</source> <translation>Identification de l&apos;Editeur de la Puce</translation> </message> <message> <source>embedderIcAssemblerId</source> <translation>Fabricant et Identifiant de l&apos;assembleur de la Carte selon (EN 926-3)</translation> </message> <message> <source>clockStop</source> <translation>Mode &quot;ClocStop&quot; (EN 726-3)</translation> </message> <message> <source>cardPersonaliserID</source> <translation>Personalisation de la Carte(EN 796-3)</translation> </message> </context> <context> <name>CardPlaceDailyWorkPeriod</name> <message> <source>Places</source> <translation>Pays</translation> </message> <message> <source>placePointerNewestRecord</source> <translation>Emplacement du nouvel enregistrement</translation> </message> <message> <source>placeRecords</source> <translation>Liste de Pays</translation> </message> </context> <context> <name>CardSlots</name> <message> <source>cardNumberCoDriverSlotBegin</source> <translation>Numéro de la carte du Conducteur 2 au début de l&apos;événement </translation> </message> <message> <source>cardNumberCoDriverSlot</source> <translation>Numéro de la Carte Conducteur 2</translation> </message> <message> <source>cardNumberDriverSlotEnd</source> <translation>Numéro de Carte du Conducteur à la Fin de l&apos;événement</translation> </message> <message> <source>cardNumberCoDriverSlotEnd</source> <translation>Numéro de la carte du Conducteur 2 à la Fin de l&apos;événement</translation> </message> <message> <source>cardNumberDriverSlotBegin</source> <translation>Numéro de Carte du Conducteur au début de l&apos;événement</translation> </message> <message> <source>cardNumberDriverSlot</source> <translation>Numéro de Carte du Conducteur</translation> </message> </context> <context> <name>CardVehicleRecord</name> <message> <source>vehicleOdometerBegin</source> <translation>Kilométrage de.Départ</translation> </message> <message> <source>%1 km on %2 (%3)</source> <translation>%1 km sur %2 (%3)</translation> </message> <message> <source>vehicleOdometerEnd</source> <translation>Kilométrage à l&apos;Arrivée</translation> </message> <message> <source>registration</source> <translation>Numéro d&apos;Immatriculation</translation> </message> <message> <source>vuDataBlockCounter</source> <translation>Valeur affichée du Compteur de Bblocs à la Dernière Extraction </translation> </message> <message> <source>vehicleUse</source> <translation>Véhicules Utilisés</translation> </message> </context> <context> <name>CardVehiclesUsed</name> <message> <source>vehiclePointerNewestRecord</source> <translation>Référence des dernières données Véhicule</translation> </message> <message> <source>Vehicles Used</source> <translation>Véhicules Utilisés</translation> </message> <message> <source>cardVehicleRecords</source> <translation>Véhicules Enregistrés</translation> </message> </context> <context> <name>CertificateAuthority</name> <message> <source>nationNumeric</source> <translation>Pays (numérique)</translation> </message> <message> <source>nationAlpha</source> <translation>Pays (Alphabétique)</translation> </message> <message> <source>caIdentifer</source> <translation>Identification de l&apos;Organisme de Certification</translation> </message> <message> <source>additionalInfo</source> <translation>Informations Complémentaires</translation> </message> <message> <source>keySerialNumber</source> <translation>Clé du Numéro de Série</translation> </message> </context> <context> <name>CertificateHolderAuthorization</name> <message> <source>tachographApplicationId</source> <translation>Identification de l&apos;Application du Chronotachygraphe</translation> </message> <message> <source>equipmentType</source> <translation>Type d&apos;Equipement</translation> </message> </context> <context> <name>DecryptedCertificate</name> <message> <source>rsaPublicKey</source> <translation>Clé publique RSA </translation> </message> <message> <source>certificateAuthorityReference</source> <translation>Certificat de l&apos;Autorité de Référence</translation> </message> <message> <source>certificateProfileIdentifier</source> <translation>Version du Certificat</translation> </message> <message> <source>certificateHolderReference</source> <translation>Identification de l&apos;Emetteur du Certificat</translation> </message> <message> <source>endOfValidity</source> <translation>Fin de Validité du Certificat</translation> </message> <message> <source>certificateHolderAuthorization</source> <translation>Droit de l&apos;Emetteur du Certificat</translation> </message> </context> <context> <name>DriverCardApplicationIdentification</name> <message> <source>noOfCardPlaceRecords</source> <translation>Nombre des relevés dePays enregistrés sur la Carte </translation> </message> <message> <source>Application Identification</source> <translation>Identification de l&apos;Application</translation> </message> <message> <source>typeOfTachographCardId</source> <translation>Type de carte Inserée </translation> </message> <message> <source>noOfCardVehicleRecords</source> <translation>Nombre des relevés de Véhicule enregistrés sur la Carte </translation> </message> <message> <source>noOfFaultsPerType</source> <translation>Nombre et Type d&apos;Erreur que la Carte peut Enregistrer</translation> </message> <message> <source>noOfEventsPerType</source> <translation>Nombre et Type d&apos;Evénement que la Carte peut Enregistrer</translation> </message> <message> <source>activityStructureLength</source> <translation>Espace Disponible pour les Changements d&apos;Activité</translation> </message> <message> <source>cardStructureVersion</source> <translation>Version de Structure de la Carte</translation> </message> </context> <context> <name>ESMFile</name> <message> <source>%1 to %2</source> <translation>%1 à %2</translation> </message> <message> <source>Could not read any data from file &apos;%1&apos;.</source> <translation>Ne peut lire Aucune Données à partir de&apos;%1&apos;.</translation> </message> </context> <context> <name>EncryptedCertificate</name> <message> <source>sign</source> <translation>Signature</translation> </message> <message> <source>Unverified certificate, needs verification from:</source> <translation>Certificat non Vérifié.Nécéssite une Vérification par:</translation> </message> <message> <source>certificateAuthorityReference</source> <translation>Identification de l&apos;Autorité de Référence</translation> </message> <message> <source>cndash</source> <translation>Cndash(Index)</translation> </message> <message> <source>Certificate verified from:</source> <translation>Certificat Vérifié par:</translation> </message> </context> <context> <name>ExtendedSerialNumber</name> <message> <source>date</source> <translation>Date</translation> </message> <message> <source>manufacturerCode</source> <translation>Code du Constructeur</translation> </message> <message> <source>serialNumber</source> <translation>Numéro de Série</translation> </message> <message> <source>equipmentType</source> <translation>Type d&apos;Equipement</translation> </message> </context> <context> <name>FullCardNumber</name> <message> <source>cardIssuingMemberState</source> <translation>Pays d&apos;Emission de la Carte</translation> </message> <message> <source>cardType</source> <translation>Type de Carte</translation> </message> <message> <source>cardNumber</source> <translation>Numéro de la Carte</translation> </message> <message> <source>%1, card holder: %2</source> <translation>%1, Titulaire de la Carte: %2</translation> </message> </context> <context> <name>HtmlReporter</name> <message> <source>hide</source> <translation>Masquer</translation> </message> <message> <source>show</source> <translation>Afficher</translation> </message> <message> <source>No %1.</source> <translation>Pas de %1.</translation> </message> <message> <source>Content</source> <translation>Contenu</translation> </message> </context> <context> <name>Identification</name> <message> <source>cardHolderPreferredLanguage</source> <translation>Langue Préférée du Titulaire de la Carte</translation> </message> <message> <source>cardIssuingMemberState</source> <translation>Pays d&apos;Emission de la Carte</translation> </message> <message> <source>cardHolderName</source> <translation>Nom du Titulaire de la Carte</translation> </message> <message> <source>cardHolderBirthDate</source> <translation>Date de Naissance du Titulaire de la Carte</translation> </message> <message> <source>cardIssueDate</source> <translation>Date d&apos;Emission de la Carte</translation> </message> <message> <source>Card identification and card holder identification</source> <translation>Identification de la Carte et du Titulaire de la Carte</translation> </message> <message> <source>cardIssuingAuthorityName</source> <translation>Autorité Délivrant la Carte</translation> </message> <message> <source>cardValidityBegin</source> <translation>Début de Validité de la Carte</translation> </message> <message> <source>cardExpiryDate</source> <translation>Expire le</translation> </message> <message> <source>cardNumber</source> <translation>Numéro de la Carte</translation> </message> </context> <context> <name>KeyIdentifier</name> <message> <source>date</source> <translation>Date</translation> </message> <message> <source>type</source> <translation>Type</translation> </message> <message> <source>manufacturerCode</source> <translation>Code Constructeur</translation> </message> <message> <source>certificateRequestSerialNumber</source> <translation>Numéro de série de la demande de certificat</translation> </message> </context> <context> <name>LastCardDownload</name> <message> <source>lastCardDownload</source> <translation>Dernier Téléchargement de la Carte</translation> </message> <message> <source>Card Download</source> <translation>Téléchargement de la Carte</translation> </message> </context> <context> <name>MemberStateCertificate</name> <message> <source>CA Certificate</source> <translation>Certificat.CA</translation> </message> <message> <source>certificate</source> <translation>Certificat</translation> </message> </context> <context> <name>Name</name> <message> <source>firstNames</source> <translation>Prénom</translation> </message> <message> <source>surname</source> <translation>Nom</translation> </message> </context> <context> <name>OptionParser</name> <message> <source>Possible Options:</source> <translation>Options Possibles:</translation> </message> <message> <source>Show help text</source> <translation>Afficher l&apos;Aide</translation> </message> <message> <source>Possible Flags:</source> <translation>Drapeaux Possibles:</translation> </message> </context> <context> <name>PlaceRecord</name> <message> <source>vehicleOdometerValue</source> <translation>Kilométrage</translation> </message> <message> <source>entryTypeDailyWorkPeriod</source> <translation>Type d&apos;Entrée journalière</translation> </message> <message> <source>dailyWorkPeriodRegion</source> <translation>Code Numérique Régional</translation> </message> <message> <source>entryTime</source> <translation>Heure d&apos;Entrée</translation> </message> <message> <source>dailyWorkPeriodCountry</source> <translation>Code numérique national (Pays d&apos;Entrée)</translation> </message> </context> <context> <name>PlainCertificate</name> <message> <source>rsaPublicKey</source> <translation>Clé publique RSA </translation> </message> <message> <source>keyIdentifier</source> <translation>Clé d&apos;Identification</translation> </message> </context> <context> <name>QObject</name> <message> <source>only</source> <translation>Seulement</translation> </message> <message> <source>Daily driving time</source> <translation>Temps de Conduite Journalier</translation> </message> <message> <source>recorded</source> <translation>Enregistré</translation> </message> <message> <source>driven for </source> <translation>Conduite Depuis</translation> </message> <message> <source>signature</source> <translation>Signature</translation> </message> </context> <context> <name>RawData</name> <message> <source>All %1 Byte are zeroed.</source> <translation>Tous %1 les Octets sont à Zéro.</translation> </message> </context> <context> <name>RsaPublicKey</name> <message> <source>e</source> <translation>Cryptage exposant e </translation> </message> <message> <source>n</source> <translation>RSA-Module N</translation> </message> </context> <context> <name>SpecificConditionRecord</name> <message> <source>entryTime</source> <translation>Heure d&apos;Entrée</translation> </message> <message> <source>specificConditionType</source> <translation>Type de Conditions Spécifiques</translation> </message> </context> <context> <name>SpecificConditions</name> <message> <source>Specific Conditions</source> <translation>Conditions Spécifiques</translation> </message> <message> <source>specificConditionRecords</source> <translation>Relevés des Conditions Spécifiques</translation> </message> </context> <context> <name>SvgDayActivity</name> <message> <source>short break</source> <translation>Courte Pause</translation> </message> <message> <source>break/rest</source> <translation>Repos</translation> </message> <message> <source>available</source> <translation>Disponibilité</translation> </message> <message> <source>driving</source> <translation>Conduite</translation> </message> <message> <source>unknown</source> <translation>Non Précisé</translation> </message> <message> <source>working</source> <translation>Travail</translation> </message> </context> <context> <name>SvgDayGraph</name> <message> <source>Time of day (UTC)</source> <translation>Heure Universelle (UTC)</translation> </message> </context> <context> <name>TimeReal</name> <message> <source>undefined</source> <translation>Indéfini</translation> </message> </context> <context> <name>Timespan</name> <message> <source>On %1, from %2 to %3 (%4)</source> <translation>Le %1, de %2 à %3 (%4)</translation> </message> <message> <source>From %1 to %2 (%4)</source> <translation>De %1 à %2 (%4)</translation> </message> <message> <source>%1 days</source> <translation>%1 Jours</translation> </message> <message> <source>undefined</source> <translation>Indéfini</translation> </message> <message> <source>From undefined time until %1</source> <translation>Heure de début non précisée à %1</translation> </message> <message> <source>From %1 on, end undefined</source> <translation>De %1 à, Heure de fin non précisée</translation> </message> </context> <context> <name>TopLevelBlock</name> <message> <source>Unknown block type 0x%1</source> <translation>Type de Bloc Inconnu: 0x%1</translation> </message> <message> <source>Beware: Block has invalid signature</source> <translation>Attention:Ce Bloc a une signature Invalide</translation> </message> <message> <source>Block has valid signature</source> <translation>Ce Bloc a une signature Valide</translation> </message> <message> <source>no crypto support compiled in</source> <translation>Compilé sans Cryptogramme</translation> </message> <message> <source>Block not signed</source> <translation>Bloc non Signé</translation> </message> </context> <context> <name>VehicleRegistration</name> <message> <source>vehicleRegistrationNumber</source> <translation>Numéro d&apos;Immatriculation</translation> </message> <message> <source>vehicleRegistrationNation</source> <translation>Pays d&apos;Immatriculation</translation> </message> </context> <context> <name>VuActivities</name> <message> <source>timeReal</source> <translation>Heure Locale</translation> </message> <message> <source>vuCardIWRecords</source> <translation>Relevés des cycles d&apos;insertion et de retrait des cartes</translation> </message> <message> <source>activityChangeInfos</source> <translation>Notes de mise à jour de l&apos;activité</translation> </message> <message> <source>Activities on %1</source> <translation>Activité depuis %1</translation> </message> <message> <source>odometerValueMidnight</source> <translation>Kilométrage à 0H00</translation> </message> <message> <source>Activities Codriver</source> <translation>Activités du Conducteur 2</translation> </message> <message> <source>Activities Driver</source> <translation>Activité du Conducteur</translation> </message> <message> <source>vuPlaceDailyWorkPeriodRecords</source> <translation>Pays du Début et de Fin de la Période</translation> </message> <message> <source>specificConditionRecords</source> <translation>Enregistrement des Conditions Spécifiques</translation> </message> <message> <source>Drivers</source> <translation>Conducteur</translation> </message> <message> <source>%1 (%2 to %3)</source> <translation>%1 (%2 à %3)</translation> </message> </context> <context> <name>VuCalibrationRecord</name> <message> <source>tyreSize</source> <translation>Dimension des Pneus</translation> </message> <message> <source>authorisedSpeed</source> <translation>Vitesse Autorisée</translation> </message> <message> <source>kConstantOfRecordingEquipment</source> <translation>Unité de contrôle constant k </translation> </message> <message> <source>wVehicleCharacteristicConstant</source> <translation>Coefficient caractéristique du véhicule w </translation> </message> <message> <source>workshopCardNumber</source> <translation>Numéro de la Carte Atelier</translation> </message> <message> <source>lTyreCircumference</source> <translation>Dimension Effective des Pneus </translation> </message> <message> <source>oldTimeValue</source> <translation>Ancienne Heure</translation> </message> <message> <source>newTimeValue</source> <translation>Nouvelle Heure</translation> </message> <message> <source>VuCalibrationRecord</source> <translation>Ensemble de données de calibration </translation> </message> <message> <source>vehicleRegistrationIdentification</source> <translation>Numéro d&apos;Immatriculation</translation> </message> <message> <source>newOdometerValue</source> <translation>Nouveau Kilométrage</translation> </message> <message> <source>oldOdometerValue</source> <translation>Ancien Kilométrage</translation> </message> <message> <source>calibrationPurpose</source> <translation>Étalonnage de base </translation> </message> <message> <source>nextCalibrationDate</source> <translation>Date de la Prochaine Calibration</translation> </message> <message> <source>workshopName</source> <translation>Nom de l&apos;Atelier</translation> </message> <message> <source>workshopCardExpiryDate</source> <translation>Date d&apos;expiration de la Carte Atelier</translation> </message> <message> <source>vehicleIdentificationNumber</source> <translation>Numéro d&apos;Immatriculation</translation> </message> <message> <source>workshopAddress</source> <translation>Adresse de l&apos;Atelier</translation> </message> </context> <context> <name>VuCardData</name> <message> <source>Card Data</source> <translation>Données de la Carte</translation> </message> </context> <context> <name>VuCardIWRecord</name> <message> <source>cardInsertionTime</source> <translation>Heure d&apos;insertion de la Carte</translation> </message> <message> <source>previousVehicleRegistration</source> <translation>Immatriculation du Véhicule Précédent</translation> </message> <message> <source>cardSlotNumber</source> <translation>Numéro du Boîtier</translation> </message> <message> <source>cardHolderName</source> <translation>Nom du Titulaire de la Carte</translation> </message> <message> <source>manualInputFlag</source> <translation>Type d&apos;Entrée Manuelle</translation> </message> <message> <source>previousCardWithdrawalTime</source> <translation>Heure du retrait précédent de la Carte</translation> </message> <message> <source>vehicleOdometerValueAtWithdrawal</source> <translation>Kilométrage au retrait de la Carte</translation> </message> <message> <source>cardExpiryDate</source> <translation>Expire le</translation> </message> <message> <source>cardNumber</source> <translation>Numéro de la Carte</translation> </message> <message> <source>cardWithdrawalTime</source> <translation>Heure de retrait de la carte </translation> </message> <message> <source>vehicleOdometerValueAtInsertion</source> <translation>Kilométrage à l&apos;insertion de la Carte</translation> </message> </context> <context> <name>VuCompanyLocksRecord</name> <message> <source>companyCardNumber</source> <translation>Numéro de la Carte Entreprise</translation> </message> <message> <source>companyAddress</source> <translation>Adresse de l&apos;Entreprise</translation> </message> <message> <source>lockTime</source> <translation>Relevé des verrouillage d&apos;entreprise</translation> </message> <message> <source>companyName</source> <translation>Nom de l&apos;Entreprise</translation> </message> </context> <context> <name>VuControlActivityRecord</name> <message> <source>controlCardNumber</source> <translation>Numéro de la Carte Contrôle</translation> </message> <message> <source>controlTime</source> <translation>Heure du Contrôle</translation> </message> <message> <source>controlType</source> <translation>Type de Contrôle</translation> </message> <message> <source>downloadPeriod</source> <translation>Heure du téléchargement</translation> </message> </context> <context> <name>VuDetailedSpeedBlock</name> <message> <source>speedBlockBeginDate</source> <translation>Temps de la première valeur de vitesse dans le bloc </translation> </message> <message> <source>speedsPerSecond</source> <translation>Vitesse à la seconde</translation> </message> </context> <context> <name>VuDetailedSpeedData</name> <message> <source>vuDetailedSpeedBlocks</source> <translation>Entrées sur les vitesses détaillés </translation> </message> <message> <source>Detailed Speed</source> <translation>Vitesse détaillée</translation> </message> </context> <context> <name>VuEventRecord</name> <message> <source>cardSlots</source> <translation>Satus du logement de la carte</translation> </message> <message> <source>eventRecordPurpose</source> <translation>Enregistrement de base</translation> </message> <message> <source>eventTime</source> <translation>Heure de l&apos;événement</translation> </message> <message> <source>eventType</source> <translation>Type d&apos;événement</translation> </message> <message> <source>similarEventsNumber</source> <translation>Nombre d&apos;événements similaires</translation> </message> </context> <context> <name>VuEventsFaults</name> <message> <source>vuFaultRecords</source> <translation>Défaut ou erreur de l&apos;UV</translation> </message> <message> <source>vuEventRecords</source> <translation>Entrées sur les événements</translation> </message> <message> <source>vuTimeAdjustmentRecords</source> <translation>Modifications de l&apos;heure</translation> </message> <message> <source>lastOverspeedControlTime</source> <translation>Dernière Validation sur excès de vitesse </translation> </message> <message> <source>firstOverspeedSince</source> <translation>Premier excès de vitesse depuis </translation> </message> <message> <source>Events and faults</source> <translation>Evénement ou erreur</translation> </message> <message> <source>numberOfOverspeedSince</source> <translation>Nombre d&apos;excès de vitesse depuis </translation> </message> <message> <source>vuOverspeedingEventRecords</source> <translation>Nombre d&apos;excès de vitesse enregistrés dans l&apos;UV</translation> </message> </context> <context> <name>VuFaultRecord</name> <message> <source>cardSlots</source> <translation>Satus du logement de la carte</translation> </message> <message> <source>eventRecordPurpose</source> <translation>Enregistrement de base</translation> </message> <message> <source>eventTime</source> <translation>Heure de l&apos;événement</translation> </message> <message> <source>eventType</source> <translation>Type d&apos;événement</translation> </message> </context> <context> <name>VuOverspeedingEventRecord</name> <message> <source>maxSpeedValue</source> <translation>Vitesse maximale</translation> </message> <message> <source>eventRecordPurpose</source> <translation>Enregistrement basic </translation> </message> <message> <source>averageSpeedValue</source> <translation>Vitesse moyenne</translation> </message> <message> <source>cardNumberDriverSlotBegin</source> <translation>Numero de carte conducteur au début</translation> </message> <message> <source>eventTime</source> <translation>Heure de l&apos;événement</translation> </message> <message> <source>eventType</source> <translation>Type d&apos;événement</translation> </message> <message> <source>similarEventsNumber</source> <translation>Nombre d&apos;événements similaires</translation> </message> </context> <context> <name>VuOverview</name> <message> <source>CardSlotsStatus</source> <translation>Status du logement de la carte</translation> </message> <message> <source>vuCompanyLocksRecords</source> <translation>Entrées verrouillées de l&apos;entreprise</translation> </message> <message> <source>currentDateTime</source> <translation>Heure du téléchargement des données</translation> </message> <message> <source>downloadingTime</source> <translation>Données disponibles au téléchargement à </translation> </message> <message> <source>vuCertificate</source> <translation>Certificat de l&apos;UV</translation> </message> <message> <source>vuDownloadablePeriod</source> <translation>Activités stockées sur l&apos;UV</translation> </message> <message> <source>vehicleRegistrationIdentification</source> <translation>Numéro d&apos;immatriculation</translation> </message> <message> <source>cardNumber</source> <translation>Numéro de Carte</translation> </message> <message> <source>vehicleIdentificationNumber</source> <translation>Numéro d&apos;immatriculation</translation> </message> <message> <source>Overview</source> <translation>Vue d&apos;ensemble</translation> </message> <message> <source>memberStateCertificate</source> <translation>Certificat de l&apos;État membre </translation> </message> <message> <source>companyOrWorkshopName</source> <translation>Nom de l&apos;Atelier</translation> </message> <message> <source>vuControlActivityRecords</source> <translation>Comptes rendus des contrôles </translation> </message> </context> <context> <name>VuPlaceDailyWorkPeriodRecord</name> <message> <source>fullCardNumber</source> <translation>Numéro complet de la carte</translation> </message> <message> <source>placeRecord</source> <translation>Nombre de pays enregistrés sur la carte </translation> </message> </context> <context> <name>VuTechnical</name> <message> <source>vuPartNumber</source> <translation>Numéro d&apos;identification de l&apos;UV</translation> </message> <message> <source>vuSoftwareVersion</source> <translation>Numéro de version de l&apos;UV</translation> </message> <message> <source>sensorSerialNumber</source> <translation>Numéro de série du capteur de mouvement</translation> </message> <message> <source>vuSoftInstallationDate</source> <translation>Date d&apos;installation du logiciel de l&apos;UV</translation> </message> <message> <source>vuManufacturerName</source> <translation>Nom du constructeur de l&apos;UV</translation> </message> <message> <source>sensorPairingDateFirst</source> <translation>Date de l&apos;appairage du capteur</translation> </message> <message> <source>vuApprovalNumber</source> <translation>Numéro d&apos;homologation de l&apos;UV</translation> </message> <message> <source>vuCalibrationRecords</source> <translation>Données de calibrage de l&apos;UV</translation> </message> <message> <source>vuSerialNumber</source> <translation>Numéro de série de l&apos;UV</translation> </message> <message> <source>sensorApprovalNumber</source> <translation>Numéro d&apos;homologation du capteur d mouvement</translation> </message> <message> <source>Technical Data</source> <translation>Données Techniques</translation> </message> <message> <source>vuManufacturerAddress</source> <translation>Adresse du constructeur de l&apos;UV</translation> </message> <message> <source>vuManufacturingDate</source> <translation>Date de construction de l&apos;UV</translation> </message> </context> <context> <name>VuTimeAdjustmentRecord</name> <message> <source>workshopCardNumber</source> <translation>Numéro de Carte Atelier</translation> </message> <message> <source>oldTimeValue</source> <translation>Ancienne heure</translation> </message> <message> <source>newTimeValue</source> <translation>Nouvelle heure</translation> </message> <message> <source>workshopName</source> <translation>Nom de l&apos;Atelier</translation> </message> <message> <source>workshopAddress</source> <translation>Werkstattaddresse</translation> </message> </context> <context> <name>VuUnknownBlock</name> <message> <source>Unknown Vu block, TREP %1</source> <translation>Bloc inconnu, TREP %1</translation> </message> </context> <context> <name>activityChangeInfo</name> <message> <source>crew</source> <translation>Double équipage</translation> </message> <message> <source>time</source> <translation>Durée</translation> </message> <message> <source>work</source> <translation>Travail</translation> </message> <message> <source>availability</source> <translation>Disponibilité</translation> </message> <message> <source>Card not inserted or withdrawn</source> <translation>Carte non insérée </translation> </message> <message> <source>short break</source> <translation>Courte pause</translation> </message> <message> <source>%1 for %2 h</source> <translation>%1, %2 Heures</translation> </message> <message> <source>single</source> <translation>Solo</translation> </message> <message> <source>slot status</source> <translation>État du logement de la carte </translation> </message> <message> <source>break/rest</source> <translation>Repos</translation> </message> <message> <source>Raw data</source> <translation>données brutes</translation> </message> <message> <source>following activity unknown</source> <translation>Activités suivantes inconnues</translation> </message> <message> <source>activity</source> <translation>Activité</translation> </message> <message> <source>driving</source> <translation>Conduite</translation> </message> <message> <source>following activity manually entered</source> <translation>Activités suivantes entrées manuellement</translation> </message> <message> <source>Card inserted</source> <translation>Carte insérée</translation> </message> <message> <source>driver slot</source> <translation>Logement de la carte conducteur</translation> </message> <message> <source>unknown</source> <translation>Inconnu</translation> </message> <message> <source>from %1 to %2 (%3 h)</source> <translation>de %1 à %2 (%3 Heure)</translation> </message> <message> <source>co-driver slot</source> <translation>Logement de la carte conducteur 2</translation> </message> <message> <source>unknown activity</source> <translation>Activité inconnue</translation> </message> </context> <context> <name>formatStrings</name> <message> <source>RFU</source> <translation>Réservé pour Utilisation Ultérieure</translation> </message> <message> <source>Turkmenistan</source> <translation>Turkmenisthan</translation> </message> <message> <source>End, related time assumed by VU </source> <translation>Fin :Référence de temps de l&apos;UV</translation> </message> <message> <source>General events: </source> <translation>Événements généraux: </translation> </message> <message> <source>Italy</source> <translation>Italie</translation> </message> <message> <source>Malta</source> <translation>Malte</translation> </message> <message> <source>Spain</source> <translation>Espagne</translation> </message> <message> <source>VU downloaded</source> <translation>UV téléchargée</translation> </message> <message> <source>Display fault</source> <translation>Défaut d&apos;affichage</translation> </message> <message> <source>Over speeding</source> <translation>Excès de Vitesse</translation> </message> <message> <source>Ireland</source> <translation>Irlande</translation> </message> <message> <source>Switzerland</source> <translation>Suisse</translation> </message> <message> <source>one of the 5 most serious events over the last 365 days</source> <translation>Un des 5 événements les plus sérieux en un an</translation> </message> <message> <source>Company Card</source> <translation>Carte Entreprise</translation> </message> <message> <source>Last card session not correctly closed</source> <translation>Dernière Session Incorrectement Cloturée</translation> </message> <message> <source>Sensor related security breach attempt events: </source> <translation>Atteinte sécuritaire de l&apos;intégrité du capteur de Mouvement: </translation> </message> <message> <source>Control Card</source> <translation>Carte Contrôle</translation> </message> <message> <source>Card faults: </source> <translation>Défaut de carte: </translation> </message> <message> <source>reserved value (should not appear)</source> <translation>Réservé (ne doit pas apparaître)</translation> </message> <message> <source>No information available</source> <translation>Pas d&apos;informations supplémentaires</translation> </message> <message> <source>Sensor fault</source> <translation>Défaut du capteur de Mouvement</translation> </message> <message> <source>Motion Sensor</source> <translation>Capteur de mouvement</translation> </message> <message> <source>Unauthorised change of motion sensor</source> <translation>Modification non autorisée du Capteur de Mouvement</translation> </message> <message> <source>(not specified: %1)</source> <translation>Non spécifié, %1)</translation> </message> <message> <source>Power supply interruption</source> <translation>Rupture d&apos;Alimentation</translation> </message> <message> <source>printing done</source> <translation>Impression terminée</translation> </message> <message> <source>La Rioja</source> <translation>La Rioja</translation> </message> <message> <source>Slovakia</source> <translation>Slovaquie</translation> </message> <message> <source>Slovenia</source> <translation>Slowenie</translation> </message> <message> <source>Time overlap</source> <translation>Chevauchement Temporel</translation> </message> <message> <source>Vatican City</source> <translation>Cité du Vatican</translation> </message> <message> <source>Printer fault</source> <translation>Défaut d&apos;imprimante</translation> </message> <message> <source>Begin, related time manually entered (start time)</source> <translation>Début:Référence de temps en entrée manuelle</translation> </message> <message> <source>installation: first calibration of the VU in the current vehicle</source> <translation>Installation :Premiercalibrage de l&apos;UV dans le véhicule</translation> </message> <message> <source>Aragón</source> <translation>Aragonien</translation> </message> <message> <source>Navarra</source> <translation>Navarre</translation> </message> <message> <source>Cyprus</source> <translation>Chypre</translation> </message> <message> <source>France</source> <translation>France</translation> </message> <message> <source>Greece</source> <translation>Grèce</translation> </message> <message> <source>Insertion of a non-valid card</source> <translation>Insertion d&apos;une Carte non Valide</translation> </message> <message> <source>United Kingdom</source> <translation>Rouyaume Uni</translation> </message> <message> <source>Latvia</source> <translation>Lettonie</translation> </message> <message> <source>Madrid</source> <translation>Madrid</translation> </message> <message> <source>San Marino</source> <translation>Saint Marin</translation> </message> <message> <source>Motion data error</source> <translation>Défaut du Capteur de Mouvement</translation> </message> <message> <source>Monaco</source> <translation>Monaco</translation> </message> <message> <source>Murcia</source> <translation>Murcie</translation> </message> <message> <source>first installation: first calibration of the VU after its activation</source> <translation>Premiere mise en service:Premier calibrage post-activation</translation> </message> <message> <source>Norway</source> <translation>Norvège</translation> </message> <message> <source>País Vasco</source> <translation>Pays-Basque</translation> </message> <message> <source>Poland</source> <translation>Pologne</translation> </message> <message> <source>Serbia</source> <translation>Serbie</translation> </message> <message> <source>Cantabria</source> <translation>Cantabrie</translation> </message> <message> <source>Sweden</source> <translation>Suède</translation> </message> <message> <source>Turkey</source> <translation>Turquie</translation> </message> <message> <source>Republic of Moldova</source> <translation>République de Moldavie</translation> </message> <message> <source>the first event or fault having occurred after the last calibration</source> <translation>Le premier événement ou erreur depuis la dernière calibration</translation> </message> <message> <source>Manufacturing Card</source> <translation>Editeur de la Carte</translation> </message> <message> <source>No further details</source> <translation>Pas d&apos;Information Complémentaires</translation> </message> <message> <source>Portugal</source> <translation>Portugal</translation> </message> <message> <source>Yugoslavia</source> <translation>Yougoslavie</translation> </message> <message> <source>RFU: %1</source> <translation>Réservé pour Utilisation Utérieure %1]</translation> </message> <message> <source>RFU groups</source> <translation>[Groupe Résevé pour Utilisation Ultérieure]</translation> </message> <message> <source>Europe, but not EC and not registered</source> <translation>Europe, Mais non repertorié UE</translation> </message> <message> <source>Card data input integrity error</source> <translation>Défaut d&apos;Intégrité des données de la Carte</translation> </message> <message> <source>Faeroe Islands</source> <translation>Iles Féroé</translation> </message> <message> <source>error in nationNumeric</source> <translation>Erreur de code Pays</translation> </message> <message> <source>Castilla-La-Mancha</source> <translation>Castille-La Manche</translation> </message> <message> <source>Vehicle Unit</source> <translation>Unité Véhicule (UV)</translation> </message> <message> <source>the longest event for one of the last 10 days of occurrence</source> <translation>Le plus long événement des 10 derniers jours</translation> </message> <message> <source>End, related time = card withdrawal time or time of entry</source> <translation>Fin : référence de temps à l&apos;extraction de la carte</translation> </message> <message> <source>%1 (formerly %2)</source> <translation>%1 (Ancienement %2)</translation> </message> <message> <source>Kazakhstan</source> <translation>Kasaksthan</translation> </message> <message> <source>Albania</source> <translation>Albanie</translation> </message> <message> <source>Baleares</source> <translation>Iles Baléares</translation> </message> <message> <source>Valencia</source> <translation>Valence</translation> </message> <message> <source>Canarias</source> <translation>Iles Canaries</translation> </message> <message> <source>Andorra</source> <translation>Andorre</translation> </message> <message> <source>Workshop Card</source> <translation>Carte Atelier</translation> </message> <message> <source>Azerbaijan</source> <translation>Azerbaïdjan</translation> </message> <message> <source>Armenia</source> <translation>Armenie</translation> </message> <message> <source>Cataluña</source> <translation>Catalogne</translation> </message> <message> <source>End, related time manually entered (end of work period)</source> <translation>Fin:Référence de temps en entrée manuelle</translation> </message> <message> <source>Belarus</source> <translation>Biélorussie</translation> </message> <message> <source>Belgium</source> <translation>Belgique</translation> </message> <message> <source>Austria</source> <translation>Autriche</translation> </message> <message> <source>Motion sensor authentication failure</source> <translation>Défaut d&apos;Autentification du Capteur de Mouvement</translation> </message> <message> <source>(err:blame programmer)</source> <translation>(Erreur :Imputable au Programmateur)</translation> </message> <message> <source>Out of scope - Begin</source> <translation>Hors-Champs :Début</translation> </message> <message> <source>Romania</source> <translation>Roumanie</translation> </message> <message> <source>the most serious event for one of the last 10 days of occurrence</source> <translation>Le plus sérieux événement des 10 derniers jours</translation> </message> <message> <source>Bosnia and Herzegovina</source> <translation>Bosnie-Herzégovine</translation> </message> <message> <source>Macedonia</source> <translation>Macédoine</translation> </message> <message> <source>Card insertion while driving</source> <translation>Carte Inserrée pendant la Conduite</translation> </message> <message> <source>Authentication failure</source> <translation>Erreur d&apos;Autentification</translation> </message> <message> <source>Internal data transfer error</source> <translation>Erreur Interne lors du !transfert</translation> </message> <message> <source>Unauthorised case opening</source> <translation>Ouverture non autorisée du Boîtier</translation> </message> <message> <source>Out of scope - End</source> <translation>Hors-Champs:Fin</translation> </message> <message> <source>Hardware sabotage</source> <translation>Manipulation Technique Frauduleuse</translation> </message> <message> <source>Downloading fault</source> <translation>Défaut de téléchargement</translation> </message> <message> <source>Andalucía</source> <translation>Andalousie</translation> </message> <message> <source>Croatia</source> <translation>Croatie</translation> </message> <message> <source>Liechtenstein</source> <translation>Liechtenstein</translation> </message> <message> <source>Asturias</source> <translation>Asturies</translation> </message> <message> <source>Montenegro</source> <translation>Montenegro</translation> </message> <message> <source>Denmark</source> <translation>Danemark</translation> </message> <message> <source>Reserved value</source> <translation>Réservé</translation> </message> <message> <source>Lithuania</source> <translation>Lituanie</translation> </message> <message> <source>Unknown region %1</source> <translation>Région inconnue %1</translation> </message> <message> <source>VU internal fault</source> <translation>Défaut Interne de l&apos;UV</translation> </message> <message> <source>Castilla-León</source> <translation>Castille-León</translation> </message> <message> <source>one of the 10 most recent (or last) events or faults</source> <translation>Un des 10 derniers événements</translation> </message> <message> <source>Driver Card</source> <translation>Carte Conducteur</translation> </message> <message> <source>Uzbekistan</source> <translation>Ouzbekisthan</translation> </message> <message> <source>Ukraine</source> <translation>Ukraine</translation> </message> <message> <source>Bulgaria</source> <translation>Bulgarie</translation> </message> <message> <source>Luxembourg</source> <translation>Luxemburg</translation> </message> <message> <source>%1 - Reserved for future use</source> <translation>[%1 - Réservé pour Utilisation Ultérieure]</translation> </message> <message> <source>Extremadura</source> <translation>Extrémadure</translation> </message> <message> <source>Reserved</source> <translation>Réservé</translation> </message> <message> <source>Estonia</source> <translation>Estonie</translation> </message> <message> <source>Unknown Manufacturer %1 or equipment not type approved</source> <translation>Constructeur inconnu %1 ou équipement non homologué</translation> </message> <message> <source>the last event for one of the last 10 days of occurrence</source> <translation>Le dernier événement des 10 derniers recensés</translation> </message> <message> <source>Recording equipment faults: </source> <translation>Défaut d&apos;enregistrement: </translation> </message> <message> <source>Czech Republic</source> <translation>République Tchèque</translation> </message> <message> <source>Netherlands</source> <translation>Pays Bas</translation> </message> <message> <source>Finland</source> <translation>Finnlande</translation> </message> <message> <source>Vehicle unit related security breach attempt events: </source> <translation>Atteinte Sécuritaire de l&apos;intégrité de l&apos;UV: </translation> </message> <message> <source>card downloaded</source> <translation>Carte téléchargée</translation> </message> <message> <source>Galicia</source> <translation>Galice</translation> </message> <message> <source>European Community</source> <translation>Communauté Européenne</translation> </message> <message> <source>Ferry/Train crossing</source> <translation>Ferry/Train</translation> </message> <message> <source>(error: blame programmer)</source> <translation>(Erreur :Imputable au Programmateur)</translation> </message> <message> <source>Card conflict</source> <translation>Carte en Conflit</translation> </message> <message> <source>Georgia</source> <translation>Georgie</translation> </message> <message> <source>Germany</source> <translation>Allemagne</translation> </message> <message> <source>Driving without an appropriate card</source> <translation>Conduite sans Carte ou Carte Invalide</translation> </message> <message> <source>Tachograph card authentication failure</source> <translation>Défaut d&apos;Atentification de la Carte</translation> </message> <message> <source>display used</source> <translation>Utilisation</translation> </message> <message> <source>Stored user data integrity error</source> <translation>Défaut d&apos;Intégrité des données téléchargées depuis la Carte</translation> </message> <message> <source>outside of Europe, not registered</source> <translation>Hors Europe .Non répertorié</translation> </message> <message> <source>Russian Federation</source> <translation>Fédération de Russie</translation> </message> <message> <source>periodic inspection</source> <translation>Vérifications périodiques</translation> </message> <message> <source>Begin, related time assumed by VU</source> <translation>Début Référence de temps de l&apos;UV</translation> </message> <message> <source>one of the 5 longest events over the last 365 days</source> <translation>Un des 5 plus longs événements depuis un an</translation> </message> <message> <source>Manufacturer specific</source> <translation>Spécifications du Constructeur</translation> </message> <message> <source>(not specified)</source> <translation>(non spécifié)</translation> </message> <message> <source>Iceland</source> <translation>Islande</translation> </message> <message> <source>Hungary</source> <translation>Hongrie</translation> </message> <message> <source>Begin, related time = card insertion time or time of entry</source> <translation>Début : référence de temps à l&apos;insertion de la carte</translation> </message> <message> <source>an active/on-going event or fault</source> <translation>Un événement ou erreur en cours</translation> </message> <message> <source>activation: recording of calibration parameters known, at the moment of the VU activation</source> <translation>Activation :Enregistrement des paramètres à la mise en service de l&apos;UV</translation> </message> <message> <source>%1 (formerly %2 and before that %3)</source> <translation>%1 (Ancienement %2 et avant %3)</translation> </message> <message> <source>Stored data integrity error</source> <translation>Erreur d&apos;Intégrité des données Téléchargées</translation> </message> </context> <context> <name>mainWindow</name> <message> <source>&amp;File</source> <translation>&amp;Fichier</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Aide</translation> </message> <message> <source>&amp;Quit</source> <translation>&amp;Fermer</translation> </message> <message> <source>E&amp;xport as HTML...</source> <translation type="obsolete">E&amp;xporter au format HTML...</translation> </message> <message> <source>Could not open file.</source> <translation>Ne Peut Ouvrir ce Type de Fichier.</translation> </message> <message> <source>Save &amp;As...</source> <translation type="obsolete">Sauver&amp;sous...</translation> </message> <message> <source>Tachograph Files</source> <translation>Fichiers Chronotachygraphes</translation> </message> <message> <source>Save XHtml file as</source> <translation>Sauver le format XHtml sous</translation> </message> <message> <source>&amp;Contents</source> <translation>&amp;Contenu</translation> </message> <message> <source>&amp;Open...</source> <translation type="obsolete">&amp;Ouvrir...</translation> </message> <message> <source>Saving not possible</source> <translation>Sauvegarde Impossible</translation> </message> <message> <source>About &amp;Qt</source> <translation>A propos de &amp;QT</translation> </message> <message> <source>Save Tachograph file as</source> <translation>Sauvegarder Fichier Tachotachygraphe sous</translation> </message> <message> <source>Could not read file</source> <translation>Ce Fichier ne peut être lu</translation> </message> <message> <source>Nothing opened, nothing to save.</source> <translation>Aucun Dossier Ouvert : Rien à été Enregistré.</translation> </message> <message> <source>&amp;Print...</source> <translation type="obsolete">&amp;Imprimmer...</translation> </message> <message> <source>readesm is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. readesm is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with readesm. If not, see &lt;http://www.gnu.org/licenses/&gt;.</source> <translation>Readesm est un logiciel libre. Vous pouvez l&apos;utiliser aux termes de la GNU General Public License telle que publiée par la Fondation de logiciel libre, et/ou le modifier, soit la version 3 de la licence, ou (à votre choix) toute version ultérieure .Ce programme est distribué dans l&apos;espoir qu&apos;il sera bénéfique, mais sans aucune garantie ; sans même la garantie implicite de merchandisation et d&apos;adaptation a un usage particulier. Voir détails dans les termes de la GNU General Public License.Vous avez dû obtenir avec ce programme, une copie de la GNU General Public License. Si tel n&apos;est pas le cas, voir &amp;lt;http://www.gnu.org/licenses/&amp;gt;.</translation> </message> <message> <source>Open Tachograph File</source> <translation>Ouvrir un fichier Chronotachygraphe</translation> </message> <message> <source>Version: </source> <translation>Version: </translation> </message> <message> <source>This program converts digital tachograph files into human-readable form.</source> <translation>Ce programme permet l&apos;interprétation des données issues d&apos;un Chronotachygraphe dans un format humainement compréhensible.</translation> </message> <message> <source>Copyright (C) 2011, 2012 by %1 (%2)</source> <translation>Copyright (C) 2011, 2012 durch %1 (%2)</translation> </message> <message> <source>Print Document</source> <translation>Impression du Document</translation> </message> <message> <source>XHtml files</source> <translation>Fichiers-XHtml</translation> </message> <message> <source>All files</source> <translation>Tous les Fichiers</translation> </message> <message> <source>&amp;About Readesm</source> <translation>&amp;A propos de Readesm</translation> </message> <message> <source>About Readesm</source> <translation>A propos de Readesm</translation> </message> <message> <source>&amp;Open…</source> <translation>&amp;Ouvrir...</translation> </message> <message> <source>Save &amp;As…</source> <translation>&amp;Enregistrer...</translation> </message> <message> <source>E&amp;xport as HTML…</source> <translation>E&amp;xporter en tant que HTML...</translation> </message> <message> <source>&amp;Print…</source> <translation>&amp;Imprimer...</translation> </message> </context> </TS>
roidelapluie/readesm
ressources/translations/readesm_fr.ts
TypeScript
gpl-3.0
72,763
from django.conf.urls.defaults import * urlpatterns = patterns('imaging.views', (r'^iframe_form/$', 'iframe_form'), (r'^ajax_delete/$', 'ajax_image_removal'), )
pielgrzym/django-minishop
imaging/urls.py
Python
gpl-3.0
174
#include <cstdlib> #include "CCDB/Helpers/PathUtils.h" using namespace std; using namespace ccdb; //______________________________________________________________________________ string ccdb::PathUtils::ExtractDirectory( const string& path ) { return path.substr( 0, path.find_last_of( '/' ) ); //will get directory without final / } //______________________________________________________________________________ string ccdb::PathUtils::ExtractObjectname( const string& path ) { return path.substr( path.find_last_of( '/' ) +1 ); } //______________________________________________________________________________ string ccdb::PathUtils::CombinePath( const string& left, const string& right ) { if(right.length()==0) return left; if(left.length()==0) return right; char separator = '/'; string result = left; bool needAddSeparator = false; char leftLast = left[left.length()-1]; char rightFirst = right[0]; if((leftLast == separator) && (rightFirst == separator)) { //it is a situation we have both "left/ + /right" //so erase one of them result.erase(result.length()); //needAddSeparator should be false by default so we dont touch it } else if((leftLast != separator) && (rightFirst != separator)) { //it is a situation we have "left + right" //needs separator needAddSeparator = true; } //The last case (leftLast != separator) || (rightFirst != separator) //gives us needAddSeparator = false, but it is false by default if(needAddSeparator) result += separator; return result+right; } //______________________________________________________________________________ bool ccdb::PathUtils::WildCardCheck( const char* pattern, const char* source ) { char *cp, *mp; while ((*source) && (*pattern != '*')) { if ((*pattern != *source) && (*pattern != '?')) { return 0; } pattern++; source++; } while (*source) { if (*pattern == '*') { if (!*++pattern) { return 1; } mp = const_cast<char *>(pattern); cp = const_cast<char *>(source+1); } else if ((*pattern == *source) || (*pattern == '?')) { pattern++; source++; } else { pattern = mp; source = cp++; } } while (*pattern == '*') { pattern++; } return !*pattern; } //______________________________________________________________________________ time_t ccdb::PathUtils::ParseTime( const string &timeStr, bool * succsess ) { /** @brief ParseTime * parses time as any part of * YYYY:MM:DD-hh:mm:ss * * 1) in place of ':' and '-' might be any ONE non digit character * * 2) One could place only part of the string, * the latest date for this part will be returned. * I.e. if timeString is "2011" - (it means the year 2011 and nothing more), * this function returns result as if it were 2011:12:31-23:59:59 * thus using such timestamp would get the latest constants for year 2011 * * @parameter [in] const string & timeString string to parse * @parameter [out] succsess true if success * @return time_t */ //default result tm time; time.tm_hour = 23; time.tm_mday = 31; time.tm_min = 59; time.tm_mon = 11; time.tm_sec = 59; time.tm_isdst=-1; //auto determine. It is not always work automatically. //See http://stackoverflow.com/questions/8558919/mktime-and-tm-isdst if(succsess!=NULL) *succsess = true; //some tmp values string tmpStr =""; //tmp string to buffer chars int delimCount=0; //number of delimeters we've met string workStr(timeStr); //we appended a work string for one more non digit symbol workStr.push_back(' '); //so the logic behind would work in any case bool lastIsDigit; //last symbol was digit //scan all symbols for (size_t i=0; i<workStr.size(); i++) { char symbol = workStr[i]; if(symbol>='0'&&symbol<='9') //Check if it is number { tmpStr.push_back(symbol); lastIsDigit = true; } else if(lastIsDigit) //it is a delimeter after the value; { delimCount++; if(delimCount ==1) //it was a year { if(tmpStr.length()!=4) //it is an error with lengtn of year { if(succsess!=NULL) *succsess = false; return 0; } time.tm_year = StringUtils::ParseInt(tmpStr) - 1900; //since in tm the year is from 1900 } if(delimCount ==2) //it was a month { if(tmpStr.length()!=2) //it is an error with lengtn of year { if(succsess!=NULL) *succsess = false; return 0; } time.tm_mon = StringUtils::ParseInt(tmpStr) - 1; // -1 becaouse months since January [0-11] //#check for 30 day month if((time.tm_mon == 9)||(time.tm_mon == 10)||(time.tm_mon == 4)||(time.tm_mon == 6)) { time.tm_mday = 30; } //February... if(time.tm_mon == 2) { if( (time.tm_year % 4 == 0 && time.tm_year % 100 != 0) || time.tm_year % 400 == 0) { time.tm_mday = 29; } else { time.tm_mday = 28; } } } if(delimCount ==3) //it was a day { if(tmpStr.length()!=2) //it is an error with lengtn of day { if(succsess!=NULL) *succsess = false; return 0; } time.tm_mday = StringUtils::ParseInt(tmpStr); //since in tm the year is from 1900 } if(delimCount ==4) //it was a hour { if(tmpStr.length()!=2) //it is an error with lengtn { if(succsess!=NULL) *succsess = false; return 0; } time.tm_hour = StringUtils::ParseInt(tmpStr); //since in tm the year is from 1900 } if(delimCount ==5) //it was a min { if(tmpStr.length()!=2) //it is an error with lengtn of min { if(succsess!=NULL) *succsess = false; return 0; } time.tm_min = StringUtils::ParseInt(tmpStr); //since in tm the year is from 1900 } if(delimCount ==6) //it was a sec { if(tmpStr.length()!=2) //it is an error with lengtn of sec { if(succsess!=NULL) *succsess = false; return 0; } time.tm_sec = StringUtils::ParseInt(tmpStr); //since in tm the year is from 1900 } //clear temp string for the next digit seria tmpStr.clear(); } else { tmpStr.clear(); //in this case we clear temp string too } } time_t result = mktime(&time); if( result == -1 && succsess!=NULL) *succsess = false; return result; } //______________________________________________________________________________ ccdb::RequestParseResult ccdb::PathUtils::ParseRequest( const string& requestStr ) { /** @brief Parses request string and returns corresponding * @see DParseRequestResult structure. * * This function is used to parse user requests. The user requests * full form of request is * /path/to/data:run:variation:time * but request might be given in any shorter form * /path/to/data - just path to date, no run, variation and timestamp specified * /path/to/data::mc - no run or date specified. * /path/to/data:::2029 - only path and date * * @parameter [in] requestStr - user request * @return structure that represent user result */ //Set default parameters RequestParseResult result; result.RunNumber=0; // Run number result.WasParsedRunNumber=false; // true if Run number was non empty result.IsInvalidRunNumber=false; // true if was an error parsing runnumber result.Path = ""; // Object path result.WasParsedPath=false; // true if Path was nonempty result.Variation=""; // Variation name result.WasParsedVariation=false; // true if variation was not empty result.Time=0; // Time stamp result.WasParsedTime=false; // true if time stamp was not empty result.TimeString=""; // Original string with time int colonCount=0; string runStr =""; for (size_t i=0; i<requestStr.size(); i++) { char symbol = requestStr[i]; if(symbol!=':') { //it is not a colon so we add this symbol somewhere switch(colonCount) { case 0: //it is a path result.Path.push_back(symbol); result.WasParsedPath=true; break; case 1: //it is a run range runStr.push_back(symbol); result.WasParsedRunNumber = true; break; case 2: //it is variation result.Variation.push_back(symbol); // Variation name result.WasParsedVariation=true; // true since we've got a variation break; default: //it should be a time than result.WasParsedTime=true; // true if time stampt was not empty result.TimeString.push_back(symbol); // Original string with time break; } } else //the symbol is colon (symbol==':') { colonCount++; //This addition is for situation when ':' is found in time string if (colonCount > 3) result.TimeString.push_back(':'); } } // at this point we parsed all symbols and it is time for final parsing //parse run number if(result.WasParsedRunNumber) { bool success = true; result.RunNumber = StringUtils::ParseInt(runStr, &success); result.IsInvalidRunNumber = !success || result.RunNumber<0; } //parse time if(result.WasParsedTime) { bool success=true; result.Time = ParseTime(result.TimeString, &success); } return result; } //______________________________________________________________________________ string & ccdb::PathUtils::MakeAbsolute( string &path ) { /** @brief Adds '/' to the beginning of the path if it is not there * * If one have 'the/path' this function will change the string as '/the/path' * If one gave '/the/path' this function does nothing * @parameter [in] string & path * @return void */ if(!IsAbsolute(path)) path.insert(0,1,'/'); return path; } //______________________________________________________________________________ bool ccdb::PathUtils::IsAbsolute( const string &path ) { /** @brief Check if the path is absolute - starts with / */ return (path.length()>0 && path[0]=='/'); } //______________________________________________________________________________ ccdb::ContextParseResult ccdb::PathUtils::ParseContext( const string& context ) { /** Parses JANA context string and returns ContextParseResult structure * * JANA_CONTEXT is a string that may contain default values for CCDB. * example of context string: * 'variation=default calibtime=2012' * parameters and values are separated by '=' (!) WITH NO SPACES */ ContextParseResult result; result.ConstantsTimeIsParsed = false; result.VariationIsParsed = false; //check empty string if(context.size()<=0) return result; //split context to name=value pairs vector<string> tokens = StringUtils::LexicalSplit(context); //iterate through pairs for(int i=0; i<tokens.size(); i++) { string token = tokens[i]; //variation is found? if(token.find("variation=")==0) //TODO move "variation=" to some define? { result.VariationIsParsed = true; result.Variation = StringUtils::Replace("variation=","",token); continue; } //calibtime is found? if(token.find("calibtime=")==0) { result.ConstantsTimeIsParsed = true; bool parseResult = false; result.ConstantsTime = PathUtils::ParseTime(StringUtils::Replace("calibtime=","",token), &parseResult); if(!parseResult) result.ConstantsTime = 0; } } return result; }
JeffersonLab/clas12-ccdb
ext/ccdb_1.05/src/Library/Helpers/PathUtils.cc
C++
gpl-3.0
13,177
package be.mira.jongeren.administration.controllers; import be.mira.jongeren.administration.domain.Event; import be.mira.jongeren.administration.domain.Partaking; import be.mira.jongeren.administration.repository.PartakingRepository; import be.mira.jongeren.administration.util.GenderOptions; import be.mira.jongeren.administration.domain.City; import be.mira.jongeren.administration.domain.Person; import be.mira.jongeren.administration.repository.CityRepository; import be.mira.jongeren.administration.repository.PersonRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; @Controller @RequestMapping("/persons") public class PersonController { @Autowired private PersonRepository personRepository; @Autowired private PartakingRepository partakingsRepository; @Autowired private CityRepository cityRepository; @RequestMapping(method = RequestMethod.GET) public ModelAndView index() { ModelAndView mav = new ModelAndView("persons/all"); List<Person> persons = personRepository.findAll(); mav.addObject("persons", persons); return mav; } @RequestMapping(value="/new", method = RequestMethod.GET) public ModelAndView navigateToAddForm(Model model, @Autowired GenderOptions genderOptions) { ModelAndView mav = new ModelAndView("persons/new"); mav.addObject("genderOptions", genderOptions.getOptions()); //mav.addObject("cities", cityRepository.findAll()); return mav; } @RequestMapping(value="{id}/edit", method = RequestMethod.GET) public ModelAndView navigateToEditForm(Model model, @PathVariable("id") UUID id, @Autowired GenderOptions genderOptions) { ModelAndView mav = new ModelAndView("persons/edit"); mav.addObject("genderOptions", genderOptions.getOptions()); Person person = personRepository.getOne(id); mav.addObject("person", person); return mav; } @RequestMapping(value="/", method = RequestMethod.POST) public ModelAndView add( @ModelAttribute Person person, @RequestParam("postcode") String postcode ){ City city = cityRepository.findByPostcode(postcode); person.setCity(city); if(person.getId()!=null) { Long version = personRepository.getOne(person.getId()).getVersion(); person.setVersion(version); } personRepository.save(person); ModelAndView mav = new ModelAndView("redirect:/persons"); return mav; } @RequestMapping(value="/{id}", method = RequestMethod.GET) public ModelAndView details(@PathVariable("id") UUID id) { Person person = personRepository.getOne(id); List<Event> events = partakingsRepository.findForPerson(id) .stream() .map(Partaking::getEvent) .collect(Collectors.toList()); ModelAndView mav = new ModelAndView("persons/details", "person", person); mav.addObject("events", events); return mav; } }
deVinnnie/magic-membership-management
src/main/java/be/mira/jongeren/administration/controllers/PersonController.java
Java
gpl-3.0
3,323
from django.apps import AppConfig class ProblemsAppConfig(AppConfig): name = "oioioi.problems"
sio2project/oioioi
oioioi/problems/apps.py
Python
gpl-3.0
101
<?php /* OpenSensorData.net OpenSensorData.net is a free (as in freedom) online database and API to store sensor data. Copyright (C) 2013 Sony Computer Science Laboratory Paris Author: Peter Hanappe This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once "error.inc.php"; require_once "db.inc.php"; require_once "input.inc.php"; require_once "datastream.inc.php"; require_once "selector.model.php"; function printCSVDatapoint($row, $d, $geolocated) { $value = $row['value']; if ($value == null) $value = "null"; if ($geolocated) { $longitude = $row['longitude']; if (!$longitude) $longitude = $datastream->longitude; if (!$longitude) $longitude = "0"; $latitude = $row['latitude']; if (!$latitude) $latitude = $datastream->latitude; if (!$latitude) $latitude = "0"; echo sprintf("%04d/%02d/%02d %02d:%02d:%02d,%s,%f,%f\n", $d->year, $d->month, $d->day, $d->hour, $d->minute, $d->second, $value, $longitude, $latitude); } else { echo sprintf("%04d/%02d/%02d %02d:%02d:%02d,%s\n", $d->year, $d->month, $d->day, $d->hour, $d->minute, $d->second, $value); } } function printJSONDatapoint($row, $d, $geolocated, $last) { $value = $row['avg']; if ($value == null) $value = "null"; if ($geolocated) { $longitude = $row['longitude']; if (!$longitude) $longitude = $datastream->longitude; if (!$longitude) $longitude = "0"; $latitude = $row['latitude']; if (!$latitude) $latitude = $datastream->latitude; if (!$latitude) $latitude = "0"; echo sprintf("[\"%04d/%02d/%02d %02d:%02d:%02d\",%s,%f,%f]", $d->year, $d->month, $d->day, $d->hour, $d->minute, $d->second, $value, $longitude, $latitude); } else { /* echo sprintf("[\"%04d/%02d/%02d %02d:%02d:%02d\",%s]", */ /* $d->year, $d->month, $d->day, */ /* $d->hour, $d->minute, $d->second, */ /* $value); */ echo sprintf("[\"%04d/%02d/%02d %02d:%02d:%02d\",[%s,%s,%s]]", $d->year, $d->month, $d->day, $d->hour, $d->minute, $d->second, $row['min'], $row['avg'], $row['max']); } if (!$last) echo ",\n"; else echo "\n"; } function printDatapoints($results, $timeformat, $default_timezone, $geolocated, $content_disposition, $format, $delta) { header('Content-Disposition: attachment; filename=' . $content_disposition); $osddatetime = new OSDDateTime(); if ($format == "csv") { header('Content-type: text/csv'); while ($row = $results->fetch_assoc()) { $osddatetime->import($row); printCSVDatapoint($row, $osddatetime, $geolocated); } } else if ($format == "json") { header("Content-type: application/json"); echo "[\n"; $last_stamp = 0; for ($i = 0; $i < $results->num_rows; $i++) { $row = $results->fetch_assoc(); $osddatetime->import($row); $last = ($i == $results->num_rows - 1); if (($i > 0) && ($row['timestamp'] - $last_stamp > $delta)) { echo sprintf("[\"%04d/%02d/%02d %02d:%02d:%02d\",[null,null,null]],", $osddatetime->year, $osddatetime->month, $osddatetime->day, $osddatetime->hour, $osddatetime->minute, $osddatetime->second); } printJSONDatapoint($row, $osddatetime, $geolocated, $last); $last_stamp = $row['timestamp']; } echo "]\n"; } } db_connect(); $timeformat = input_get_timeformat(); if (!is_valid_timeformat($timeformat)) badRequest("Invalid time format"); $geolocated = input_get_geolocated(); $geolocated = ($geolocated == "y")? true : false; $path = $_GET['path']; $selector = new Selector(); if (!$selector->parse($path)) badRequest($selector->err); if (($selector->format != "csv") && ($selector->format != "json")) badRequest("Unsupported output format"); $datastream = new Datastream(); if (!$datastream->load($selector->id)) badRequest("Invalid datastream ID: " . var_export($selector)); header('Access-Control-Allow-Origin: *'); $points = 1000; /* $query = Datastream::to_count_query($selector); */ /* $results = $mysqli->query($query); */ /* if (!$results) { */ /* internalServerError("Failed to read the datapoints, Query: " . $query); */ /* } */ /* $row = $results->fetch_assoc(); */ /* $count = $row['count']; */ if ($selector->date != NULL) { $diff = 86400; $delta = $diff / $points; $blank = 3600; } else if (($selector->from != NULL) && ($selector->to != NULL)) { $diff = $selector->to->diff($selector->from); if ($diff < 0) { $tmp = $selector->from; $selector->from = $selector->to; $selector->to = $tmp; $diff = -$diff; } if (!$selector->to->has_time()) { $diff += 86400; } if ($diff == 0) $delta = 1; else $delta = $diff / $points; $blank = 3 * $delta; } /* if ($count < 5 * $points) { */ /* $delta = 1; */ /* $blank = 3 * $diff / $count; */ /* } */ $query = Datastream::to_filter_query($selector, $delta); $filename = $selector->to_filename("datastream"); $results = $mysqli->query($query); if (!$results) { internalServerError("Failed to read the datapoints, Query: " . $query); } //echo $query . "\n"; printDatapoints($results, $timeformat, $datastream->timezone, $geolocated, $filename, $selector->format, $blank); db_close(); ?>
hanappe/opensensordata.net
processdata.php
PHP
gpl-3.0
7,528
// $Id: RosFill.hpp 1186 2019-07-12 17:49:59Z mueller $ // SPDX-License-Identifier: GPL-3.0-or-later // Copyright 2000-2011 by Walter F.J. Mueller <W.F.J.Mueller@gsi.de> // // Revision History: // Date Rev Version Comment // 2011-02-25 364 1.1 Support << also to string // 2011-01-30 359 1.0 Adopted from CTBosFill // 2000-02-06 - - Last change on CTBosFill // --------------------------------------------------------------------------- /*! \brief Declaration of class RosFill . */ #ifndef included_Retro_RosFill #define included_Retro_RosFill 1 #include <ostream> #include <string> namespace Retro { class RosFill { public: RosFill(int count=0, char fill=' '); int Count() const; char Fill() const; private: int fCount; //!< blank count char fFill; //!< fill character }; std::ostream& operator<<(std::ostream& os, const RosFill& obj); std::string& operator<<(std::string& os, const RosFill& obj); } // end namespace Retro #include "RosFill.ipp" #endif
wfjm/w11
tools/src/librtools/RosFill.hpp
C++
gpl-3.0
1,106
#ifndef QUAN_CAPACITANCE_HPP_INCLUDED #define QUAN_CAPACITANCE_HPP_INCLUDED #if (defined _MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif /* Copyright (c) 2003-2014 Andy Little. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses./ */ // // // See QUAN_ROOT/quan_matters/index.html for documentation. #include <quan/components/of_capacitance.hpp> namespace quan{ template< typename Value_type > struct capacitance_ : meta::components::of_capacitance{ typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::yocto // coherent-exponent -24 >, Value_type > yF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::zepto // coherent-exponent -21 >, Value_type > zF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::atto // coherent-exponent -18 >, Value_type > aF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::femto // coherent-exponent -15 >, Value_type > fF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::pico // coherent-exponent -12 >, Value_type > pF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::nano // coherent-exponent -9 >, Value_type > nF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::micro // coherent-exponent -6 >, Value_type > uF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::milli // coherent-exponent -3 >, Value_type > mF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::centi // coherent-exponent -2 >, Value_type > cF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::deci // coherent-exponent -1 >, Value_type > dF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::none // coherent-exponent 0 >, Value_type > F; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::deka // coherent-exponent 1 >, Value_type > daF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::hecto // coherent-exponent 2 >, Value_type > hF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::kilo // coherent-exponent 3 >, Value_type > kF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::mega // coherent-exponent 6 >, Value_type > MF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::giga // coherent-exponent 9 >, Value_type > GF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::tera // coherent-exponent 12 >, Value_type > TF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::peta // coherent-exponent 15 >, Value_type > PF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::exa // coherent-exponent 18 >, Value_type > EF; typedef fixed_quantity< quan::meta::unit< abstract_quantity, typename meta::si_unit::zetta // coherent-exponent 21 >, Value_type > ZF; typedef fixed_quantity< typename non_si_unit::abfarad, Value_type > abfarad; }; struct capacitance : capacitance_<quantity_traits::default_value_type>{}; }//quan #endif
andrewfernie/quan-trunk
quan/capacitance.hpp
C++
gpl-3.0
5,850
<?PHP require_once("website.php"); LibHtml::preventCaching(); $formItemId = LibEnv::getEnvHttpPOST("formItemId"); $languageCode = LibEnv::getEnvHttpPOST("languageCode"); $text = LibEnv::getEnvHttpPOST("text"); if ($formItem = $formItemUtils->selectById($formItemId)) { $formItem->setText($languageUtils->setTextForLanguage($formItem->getText(), $languageCode, $text)); $formItemUtils->update($formItem); } $notused = ''; $responseText = <<<HEREDOC { "notused" : "$notused" } HEREDOC; print($responseText); ?>
stephaneeybert/learnintouch
modules/form/item/updateItem.php
PHP
gpl-3.0
521
<?php /** * /settings/toggles/index.php * * This file is part of DomainMOD, an open source domain and internet asset manager. * Copyright (c) 2010-2016 Greg Chetcuti <greg@chetcuti.com> * * Project: http://domainmod.org Author: http://chetcuti.com * * DomainMOD is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * DomainMOD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with DomainMOD. If not, see * http://www.gnu.org/licenses/. * */ ?> <?php header("Location: ../../invalid.php"); exit;
koep/domainmod
settings/toggles/index.php
PHP
gpl-3.0
944
#include <vector> #include <string> #include <fstream> #include <algorithm> #include <iostream> #include "gbcodes3755.h" #include "OnlineHandwritingPicture.h" #include "SpatiallySparseDatasetPenDigits.h" struct iPoint { short x; short y; }; void readPenDigitsFile(std::vector<Picture *> &characters, const char *filename, int renderSize, OnlineHandwritingEncoding enc) { std::ifstream f(filename, std::ios::in | std::ios::binary); if (!f) { std::cout << "Cannot find " << filename << std::endl; std::cout << "Please download it from the UCI Machine Learning Repository:" << std::endl; std::cout << "http://archive.ics.uci.edu/ml/datasets/" "Pen-Based+Recognition+of+Handwritten+Digits" << std::endl; exit(EXIT_FAILURE); } std::vector<std::string> data; std::copy(std::istream_iterator<std::string>(f), std::istream_iterator<std::string>(), std::back_inserter(data)); int pen = 0; OnlineHandwritingPicture *character = new OnlineHandwritingPicture(renderSize, enc, -1); std::vector<iPoint> stroke; for (unsigned int i = 0; i < data.size(); i++) { if (data[i] == ".COMMENT") { if (character->ops.size() > 0) { character->normalize(); characters.push_back(character); character = new OnlineHandwritingPicture(renderSize, enc, -1); } character->label = atoi(data[i + 1].c_str()); } if (data[i] == ".PEN_UP") { pen = 0; character->ops.push_back(arma::mat(stroke.size(), 2)); for (unsigned int i = 0; i < stroke.size(); ++i) { character->ops.back()(i, 0) = stroke[i].x; character->ops.back()(i, 1) = stroke[i].y; } stroke.clear(); } if (pen == 1) { iPoint p; p.y = atoi(data[i].c_str()); i++; p.x = -atoi(data[i].c_str()); stroke.push_back(p); } if (data[i] == ".PEN_DOWN") pen = 1; } character->normalize(); characters.push_back(character); } SpatiallySparseDataset PenDigitsTrainSet(int renderSize, OnlineHandwritingEncoding enc) { SpatiallySparseDataset dataset; dataset.name = "Pendigits train set"; dataset.type = TRAINBATCH; dataset.nFeatures = OnlineHandwritingEncodingSize[enc]; dataset.nClasses = 10; readPenDigitsFile(dataset.pictures, "Data/pendigits/pendigits-orig.tra", renderSize, enc); return dataset; } SpatiallySparseDataset PenDigitsTestSet(int renderSize, OnlineHandwritingEncoding enc) { SpatiallySparseDataset dataset; dataset.name = "Pendigits test set"; dataset.type = TESTBATCH; dataset.nFeatures = OnlineHandwritingEncodingSize[enc]; dataset.nClasses = 10; readPenDigitsFile(dataset.pictures, "Data/pendigits/pendigits-orig.tes", renderSize, enc); return dataset; }
touren/SparseConvNet
SpatiallySparseDatasetPenDigits.cpp
C++
gpl-3.0
2,905
<? /**[N]** * JIBAS Education Community * Jaringan Informasi Bersama Antar Sekolah * * @version: 3.8 (January 25, 2016) * @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License **[N]**/ ?> <? require_once('../include/errorhandler.php'); require_once('../include/sessioninfo.php'); require_once('../include/common.php'); require_once('../include/config.php'); require_once('../include/db_functions.php'); require_once('../include/theme.php'); require_once('../library/departemen.php'); require_once('../cek.php'); $departemen = ""; if (isset($_REQUEST['departemen'])) $departemen = $_REQUEST['departemen']; $tahunajaran = ""; if (isset($_REQUEST['tahunajaran'])) $tahunajaran = $_REQUEST['tahunajaran']; $jadwal = $_REQUEST['jadwal']; $urut = "deskripsi"; if (isset($_REQUEST['urut'])) $urut = $_REQUEST['urut']; $urutan = "ASC"; if (isset($_REQUEST['urutan'])) $urutan = $_REQUEST['urutan']; $op = $_REQUEST['op']; if ($op == "dw8dxn8w9ms8zs22") { OpenDb(); $sql = "UPDATE infojadwal SET aktif = '$_REQUEST[newaktif]' WHERE replid = '$_REQUEST[replid]' "; QueryDb($sql); CloseDb(); $jadwal = $_REQUEST['replid']; } else if ($op == "xm8r389xemx23xb2378e23") { OpenDb(); $sql = "DELETE FROM infojadwal WHERE replid = '$_REQUEST[replid]'"; QueryDb($sql); CloseDb(); $jadwal = $_REQUEST['replid']; } OpenDb(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="../script/SpryValidationSelect.js" type="text/javascript"></script> <link href="../script/SpryValidationSelect.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="../style/style.css"> <link rel="stylesheet" type="text/css" href="../style/tooltips.css"> <script language="javascript" src="../script/tables.js"></script> <script language="javascript" src="../script/tools.js"></script> <script language="JavaScript" src="../script/tooltips.js"></script> <script language="javascript"> function change_departemen() { var departemen=document.getElementById("departemen").value; document.location.href = "info_jadwal.php?departemen="+departemen; } function change_tahunajaran() { var departemen=document.getElementById("departemen").value; var tahunajaran=document.getElementById("tahunajaran").value; document.location.href = "info_jadwal.php?departemen="+departemen+"&tahunajaran="+tahunajaran; } function tambah() { var departemen=document.getElementById("departemen").value; var tahunajaran=document.getElementById("tahunajaran").value; newWindow('info_jadwal_add.php?tahunajaran='+tahunajaran,'TambahInfoJadwal','390','250','resizable=1,scrollbars=1,status=0,toolbar=0') } function refresh(jadwal) { var departemen = document.getElementById('departemen').value; var tahunajaran = document.getElementById('tahunajaran').value; document.location.href = "info_jadwal.php?jadwal="+jadwal+"&departemen="+departemen+"&tahunajaran="+tahunajaran+"&urut=<?=$urut?>&urutan=<?=$urutan?>"; } function setaktif(aktif, replid) { var msg; var newaktif; var departemen = document.getElementById('departemen').value; var tahunajaran = document.getElementById('tahunajaran').value; if (aktif == 1) { msg = "Apakah anda yakin akan mengubah jadwal ini menjadi TIDAK AKTIF?"; newaktif = 0; } else { msg = "Apakah anda yakin akan mengubah jadwal ini menjadi AKTIF?"; newaktif = 1; } if (confirm(msg)) document.location.href = "info_jadwal.php?op=dw8dxn8w9ms8zs22&replid="+replid+"&newaktif="+newaktif+"&departemen="+departemen+"&tahunajaran="+tahunajaran; } function hapus(replid) { var departemen = document.getElementById('departemen').value; var tahunajaran = document.getElementById('tahunajaran').value; if (confirm("Apakah anda yakin akan menghapus info jadwal ini?")) document.location.href = "info_jadwal.php?op=xm8r389xemx23xb2378e23&replid="+replid+"&departemen="+departemen+"&tahunajaran="+tahunajaran+"&urut=<?=$urut?>&urutan=<?=$urutan?>"; } function tutup() { var jadwal= document.getElementById('jadwal').value; var departemen = document.getElementById('departemen').value; var tahunajaran = document.getElementById('tahunajaran').value; if (jadwal.length > 0) parent.opener.change(jadwal,tahunajaran,departemen); window.close(); } function change_urut(urut,urutan) { var departemen = document.getElementById('departemen').value; var tahunajaran = document.getElementById('tahunajaran').value; if (urutan =="ASC"){ urutan="DESC" } else { urutan="ASC" } document.location.href = "info_jadwal.php?departemen="+departemen+"&tahunajaran="+tahunajaran+"&urut="+urut+"&urutan="+urutan; } function focusNext(elemName, evt) { evt = (evt) ? evt : event; var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode); if (charCode == 13) { document.getElementById(elemName).focus(); return false; } return true; } locnm=location.href; pos=locnm.indexOf("indexb.htm"); locnm1=locnm.substring(0,pos); function ByeWin() { windowIMA=parent.opener.change(0); } </script> <title>JIBAS SIMAKA [Daftar Info Jadwal]</title> </head> <body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" style="background-color:#dcdfc4" onUnload="ByeWin()" onload="document.getElementById('departemen').focus();"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr height="58"> <td width="28" background="../<?=GetThemeDir() ?>bgpop_01.jpg">&nbsp;</td> <td width="*" background="../<?=GetThemeDir() ?>bgpop_02a.jpg"> <div align="center" style="color:#FFFFFF; font-size:16px; font-weight:bold"> .: Info Jadwal :. </div> </td> <td width="28" background="../<?=GetThemeDir() ?>bgpop_03.jpg">&nbsp;</td> </tr> <tr height="150"> <td width="28" background="../<?=GetThemeDir() ?>bgpop_04a.jpg">&nbsp;</td> <td width="0" style="background-color:#FFFFFF" height="335" valign="top"> <table border="0" width="100%" align="center"> <!-- TABLE CENTER --> <tr> <td align="left" valign="top"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <!-- TABLE LINK --> <tr> <td width="20%"><strong>Departemen </strong></td> <td width="20%"> <select name="departemen" id="departemen" onChange="change_departemen()" style="width:150px;"> <? $dep = getDepartemen(SI_USER_ACCESS()); foreach($dep as $value) { if ($departemen == "") $departemen = $value; ?> <option value="<?=$value ?>" <?=StringIsSelected($value, $departemen) ?> > <?=$value ?> </option> <? } ?> </select> </td> </tr> <tr> <td><strong>Tahun Ajaran</strong></td> <td> <select name="tahunajaran" id="tahunajaran" onChange="change_tahunajaran()" style="width:150px;"> <? OpenDb(); $sql = "SELECT replid,tahunajaran,aktif FROM tahunajaran where departemen='$departemen' ORDER BY aktif DESC, replid DESC"; $result = QueryDb($sql); CloseDb(); while ($row = @mysql_fetch_array($result)) { if ($tahunajaran == "") $tahunajaran = $row['replid']; if ($row['aktif']) $ada = '(Aktif)'; else $ada = ''; ?> <option value="<?=urlencode($row['replid'])?>" <?=IntIsSelected($row['replid'], $tahunajaran)?> ><?=$row['tahunajaran'].' '.$ada?></option> <? } ?> </select> </td> <? if ($tahunajaran <> "" && $departemen <> "") { OpenDb(); $sql = "SELECT i.deskripsi, i.aktif, i.replid FROM sklakademik.infojadwal i, sklakademik.tahunajaran t WHERE t.departemen ='$departemen' AND i.idtahunajaran = '$tahunajaran' AND i.idtahunajaran = t.replid ORDER BY $urut $urutan"; $result = QueryDb($sql); if (@mysql_num_rows($result) > 0) { ?> <td align="right"> <a href="#" onClick="document.location.reload()"><img src="../images/ico/refresh.png" border="0" onMouseOver="showhint('Refresh!', this, event, '80px')">&nbsp;Refresh</a>&nbsp;&nbsp; <a href="JavaScript:tambah()"><img src="../images/ico/tambah.png" border="0" onMouseOver="showhint('Tambah Info Jadwal!', this, event, '80px')">&nbsp;Tambah Info Jadwal</a></td> </tr> </table> </td> </tr> <tr> <td> <br /> <table class="tab" id="table" border="1" style="border-collapse:collapse" width="100%" align="left"> <tr class="header" height="30" align="center"> <td width="10%">No</td> <td width="*" onMouseOver="background='../style/formbg2agreen.gif';height=30;" onMouseOut="background='../style/formbg2.gif';height=30;" background="../style/formbg2.gif" style="cursor:pointer;" onClick="change_urut('deskripsi','<?=$urutan?>')">Info Jadwal <?=change_urut('deskripsi',$urut,$urutan)?></td> <td width="15%" onMouseOver="background='../style/formbg2agreen.gif';height=30;" onMouseOut="background='../style/formbg2.gif';height=30;" background="../style/formbg2.gif" style="cursor:pointer;" onClick="change_urut('i.aktif','<?=$urutan?>')">Status <?=change_urut('i.aktif',$urut,$urutan)?></td> <td width="15%">&nbsp;</td> </tr> <? $cnt=1; while ($row = @mysql_fetch_array($result)) { $replid=$row['replid']; ?> <tr height="25"> <td align="center"><?=$cnt?></td> <td><?=$row['deskripsi']?></td> <td align="center"> <? if ($row['aktif']==1){ ?> <img src="../images/ico/aktif.png" onClick="setaktif(<?=$row['aktif']?>,<?=$row['replid']?>)" onMouseOver="showhint('Status Aktif', this, event, '80px')"> <? } else { ?> <img src="../images/ico/nonaktif.png" onClick="setaktif(<?=$row['aktif']?>,<?=$row['replid']?>)" onMouseOver="showhint('Status Tidak Aktif', this, event, '80px')"> <? } ?> </td> <td align="center"> <a href="#" onClick="newWindow('info_jadwal_edit.php?replid=<?=$row['replid']?>', 'UbahInfoJadwal','390','250','resizable=1,scrollbars=1,status=0,toolbar=0')"><img src="../images/ico/ubah.png" border="0" onMouseOver="showhint('Ubah Info Jadwal!', this, event, '80px')"></a>&nbsp; <a href="JavaScript:hapus(<?=$row['replid']?>)" ><img src="../images/ico/hapus.png" border="0" onMouseOver="showhint('Hapus Info Jadwal!', this, event, '80px')"></a> </td> </tr> <? $cnt++; } //while CloseDb(); ?> <script language='JavaScript'> Tables('table', 1, 0); </script> </table> <? } else { ?> <td width = "48%"></td> </tr> </table> <table width="100%" border="0" align="center"> <tr> <td colspan="3"><hr style="border-style:dotted" color="#000000"/> </td> </tr> <tr> <td align="center" valign="middle" height="150"> <font size = "2" color ="red"><b>Tidak ditemukan adanya data. <br />Klik &nbsp;<a href="JavaScript:tambah()" ><font size = "2" color ="green">di sini</font></a>&nbsp;untuk mengisi data baru. </b></font> </td> </tr> </table> <? } } else { ?> <td width = "48%"></td> </tr> </table> <table width="100%" border="0" align="center"> <tr> <td colspan="3"><hr style="border-style:dotted" color="#000000" /> </td> </tr> <tr> <td align="center" valign="middle" height="150"> <? if ($departemen == "") { ?> <font size = "2" color ="red"><b>Belum ada data Departemen. <br />Silahkan isi terlebih dahulu di menu Departemen pada bagian Referensi. </b></font> <? } elseif ($tahunajaran == "") {?> <font size = "2" color ="red"><b>Belum ada data Tahun Ajaran. <br />Silahkan isi terlebih dahulu di menu Tahun Ajaran pada bagian Referensi. </b></font> <? } ?> </td> </tr> </table> <? } ?> </td> </tr> <tr height="35"> <td colspan="3" align="center"> <input class="but" type="button" value="Tutup" onClick="tutup()"> <input type="hidden" name="jadwal" id="jadwal" value="<?=$jadwal?>" /> </td> </tr> </table> </td> <td width="28" background="../<?=GetThemeDir() ?>bgpop_06a.jpg">&nbsp;</td> </tr> <tr height="28"> <td width="28" background="../<?=GetThemeDir() ?>bgpop_07.jpg">&nbsp;</td> <td width="*" background="../<?=GetThemeDir() ?>bgpop_08a.jpg">&nbsp;</td> <td width="28" background="../<?=GetThemeDir() ?>bgpop_09.jpg">&nbsp;</td> </tr> </table> </body> </html> <script language="javascript"> var spryselect1 = new Spry.Widget.ValidationSelect("departemen"); var spryselect1 = new Spry.Widget.ValidationSelect("tahunajaran"); </script>
dedefajriansyah/jibas
akademik/jadwal/info_jadwal.php
PHP
gpl-3.0
13,815
<?php /** * Kiwitrees: Web based Family History software * Copyright (C) 2012 to 2022 kiwitrees.net * * Derived from webtrees (www.webtrees.net) * Copyright (C) 2010 to 2012 webtrees development team * * Derived from PhpGedView (phpgedview.sourceforge.net) * Copyright (C) 2002 to 2010 PGV Development Team * * Kiwitrees is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with Kiwitrees. If not, see <http://www.gnu.org/licenses/>. */ if (!defined('KT_KIWITREES')) { header('HTTP/1.0 403 Forbidden'); exit; } // Add new site setting try { self::exec( "INSERT IGNORE INTO `##site_setting` (setting_name, setting_value) VALUES ". "('BLOCKED_EMAIL_ADDRESS_LIST', 'youremail@gmail.com')" ); } catch (PDOException $ex) { // Perhaps we have already added this data? } // add widgets to module table try { self::exec("ALTER TABLE `##module` ADD COLUMN footer_order INTEGER NULL"); } catch (PDOException $ex) { // If this fails, it has probably already been done. } self::exec("ALTER TABLE `##block` CHANGE location location ENUM('main', 'side', 'footer')"); // Add the initial default footer block settings self::exec("INSERT IGNORE INTO `##block` (gedcom_id, location, block_order, module_name) VALUES (-1, 'footer', 1, 'footer_contacts'), (-1, 'footer', 2, 'footer_html'), (-1, 'footer', 3, 'footer_logo')"); // Rename tab to tabi and add tabf try { self::exec("ALTER TABLE `##module` CHANGE `tab_order` `tabi_order` INTEGER NULL;"); } catch (PDOException $ex) { // If this fails, it has probably already been done. } try { self::exec("ALTER TABLE `##module` ADD COLUMN `tabf_order` INTEGER NULL;"); } catch (PDOException $ex) { // If this fails, it has probably already been done. } try { self::exec("DELETE FROM `kt_module_privacy` WHERE `component` = 'tab';"); } catch (PDOException $ex) { // If this fails, it has probably already been done. } try { self::exec("ALTER TABLE `##module_privacy` CHANGE component component ENUM('block', 'chart', 'footer', 'list', 'menu', 'report', 'sidebar', 'tabi', 'widget', 'tabf')"); } catch (PDOException $ex) { // If this fails, it has probably already been done. } // Update the version to indicate success KT_Site::preference($schema_name, $next_version);
kiwi3685/kiwitrees-nova
includes/db_schema/db_schema_36_37.php
PHP
gpl-3.0
2,741
<?php /** * Description of HtmlList * * @author bs4300280 */ class DataFieldToHtmlListBoolean extends HtmlListBoolean { use TraitDataFieldToHtml; function __construct(DatabaseDataField $paramDataField) { $this->setDataField($paramDataField); parent::__construct(); parent::initAbstractHtmlSelect( $this->getHtmlName() , $this->getDataField()->getFieldLabel() , $this->getDataField()->getFieldValue() , $this->getDataField()->isFieldDiff() , HtmlListBoolean::getArrayListContentBoolean() , $this->getDataField()->getDataValidationSuccessful() , $this->getDataField()->getDataWarningMessage() , $this->getDataField()->getIsFieldLock() , $this->getDataField()->getLinkFieldLock() ); $this->getEventsForm()->setOnChangeWithAjaxAutoSave( $this->getDataField()->getTableName() , $this->getDataField()->getKeyName() , $this->getDataField()->getKeyValue() , $this->getDataField()->getFieldName() ); /** * Détermine si le datafield encours doit être non éditiable */ $this->setContentLocked($paramDataField->getFieldsToLock()); } public function getHtmlViewedContent() { $return = ''; if ($this->getSelectedValue()) { $return = Html::showValue(self::YES_LABEL); } else { $return = Html::showValue(self::NO_LABEL); } return $return; } }
SalokineTerata/intranet
apps/lib/class/html/DataFieldToHtmlListBoolean.php
PHP
gpl-3.0
1,617
/** * $Id$ * * This file is part of the Fhtagn! C++ Library. * Copyright (C) 2009 Jens Finkhaeuser <unwesen@users.sourceforge.net>. * * Author: Author's Name <author@users.sourceforge.net> * ... * * This program is licensed as free software for personal, educational or * other non-commerical uses: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Alternatively, licenses for commercial purposes are available as well. * Please send your enquiries to the copyright holder's address above. **/ namespace fhtagn { } // namespace fhtagn
jfinkhaeuser/fhtagn
templates/template.cpp
C++
gpl-3.0
1,118
using CronEspresso.NETCore.Resources; using CronEspresso.NETCore.Utils; using NUnit.Framework; namespace CronEspresso.NETCore.Test.ValidateCron.MonthValueValidation.StringSlashSeparatedValue { [TestFixture] public class when_a_user_passes_in_a_slash_month_string_value_with_multiple_slashes { private const string CronValue = "* * * * JAN//DEC *"; private CronValidationResults _validationResult; [SetUp] public void SetUp() { _validationResult = CronHelpers.ValidateCron(CronValue); } [Test] public void it_gives_the_correct_result() { Assert.False(_validationResult.IsValidCron); } [Test] public void it_gives_the_correct_validation_message() { Assert.AreEqual(string.Format(ValidationMessages.InvalidMonth, CronValue), _validationResult.ValidationMessage); } } }
conway91/CronEspresso
CronEspresso.NETCore.Test/ValidateCron/MonthValueValidation/StringSlashSeparatedValue/when_a_user_passes_in_a_slash_month_string_value_with_multiple_slashes.cs
C#
gpl-3.0
937
package edu.hm.cs.smc.channels.linkedin.models; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.OneToOne; import edu.hm.cs.smc.database.models.BaseEntity; @Entity public class LinkedInStatusUpdateStatistics extends BaseEntity { @OneToOne(cascade=CascadeType.ALL) private LinkedInViewsMyMonth viewsByMonth; public LinkedInViewsMyMonth getViewsByMonth() { return viewsByMonth; } public void setViewsByMonth(LinkedInViewsMyMonth viewsByMonth) { this.viewsByMonth = viewsByMonth; } }
CCWI/SocialMediaCrawler
src/edu/hm/cs/smc/channels/linkedin/models/LinkedInStatusUpdateStatistics.java
Java
gpl-3.0
563
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. class companyrep{ // Get the jsmodule setup thingy. public function getjsmodule() { $jsmodule = array( 'name' => 'local_report_completion', 'fullpath' => '/local/report_completion/module.js', 'requires' => array('base', 'node', 'charts', 'json'), 'strings' => array( ) ); return $jsmodule; } // Create the select list of companies. // If the user is in the company managers table then the list is restricted. public static function companylist( $user ) { global $DB; // Create "empty" array. $companylist = array(); // Get the companies they manage. $managedcompanies = array(); if ($managers = $DB->get_records_sql("SELECT * from {company_users} WHERE userid = :userid AND managertype != 0", array('userid' => $user->id))) { foreach ($managers as $manager) { $managedcompanies[] = $manager->companyid; } } // Get companies information. if (!$companies = $DB->get_records('company', array(), 'name')) { return $companylist; } // And finally build the list. foreach ($companies as $company) { // If managers found then only allow selected companies. if (!empty($managedcompanies)) { if (!in_array($company->id, $managedcompanies)) { continue; } } $companylist[$company->id] = $company; } return $companylist; } // Append the company managers to companies. public static function addmanagers( &$companies ) { global $DB; // Iterate over companies adding their managers. foreach ($companies as $company) { $companymanagers = array(); $managers = array(); if ($companymanagers = $DB->get_records_sql("SELECT * from {company_users} WHERE companyid = :companyid AND managertype = 1", array('companyid' => $company->id))) { foreach ($companymanagers as $companymanager) { if ($user = $DB->get_record( 'user', array('id' => $companymanager->userid))) { $managers[$user->id] = $user; } } } $company->managers['company'] = $managers; $managers = array(); if ($companymanagers = $DB->get_records_sql("SELECT * from {company_users} WHERE companyid = :companyid AND managertype = 2", array('companyid' => $company->id))) { foreach ($companymanagers as $companymanager) { if ($user = $DB->get_record( 'user', array('id' => $companymanager->userid))) { $managers[$user->id] = $user; } } } $company->managers['department'] = $managers; } } // Append the company users to companies. public static function addusers( &$companies ) { global $DB; // Iterate over companies adding their managers. foreach ($companies as $company) { $users = array(); if ($companyusers = $DB->get_records('company_users', array('companyid' => $company->id))) { foreach ($companyusers as $companyuser) { if ($user = $DB->get_record( 'user', array('id' => $companyuser->userid))) { $users[$user->id] = $user; } } } $company->users = $users; } } // Append the company courses to companies. public static function addcourses( &$companies ) { global $DB; // Iterate over companies adding their managers. foreach ($companies as $company) { $courses = array(); if ($companycourses = $DB->get_records( 'company_course', array('companyid' => $company->id))) { foreach ($companycourses as $companycourse) { if ($course = $DB->get_record( 'course', array('id' => $companycourse->courseid))) { $courses[$course->id] = $course; } } } $company->courses = $courses; } } // List users. public static function listusers( $users ) { global $CFG; echo "<ul class=\"iomad_user_list\">\n"; foreach ($users as $user) { if (!empty($user->id) && !empty($user->email) && !empty($user->firstname) && !empty($user->lastname)) { $link = "{$CFG->wwwroot}/user/view.php?id={$user->id}"; echo "<li><a href=\"$link\">".fullname( $user )."</a> ({$user->email})</li>\n"; } } echo "</ul>\n"; } }
lernlink/iomad-ll
local/report_companies/lib.php
PHP
gpl-3.0
5,835
// -*- C++ -*- // // This is the implementation of the non-inlined, non-templated member // functions of the MEPP2GammaGammaPowheg class. // #include "MEPP2GammaGammaPowheg.h" #include "ThePEG/Interface/ClassDocumentation.h" #include "ThePEG/Interface/Switch.h" #include "ThePEG/Interface/Parameter.h" #include "ThePEG/Interface/Reference.h" #include "ThePEG/Persistency/PersistentOStream.h" #include "ThePEG/Persistency/PersistentIStream.h" #include "ThePEG/PDT/EnumParticles.h" #include "ThePEG/MatrixElement/Tree2toNDiagram.h" #include "ThePEG/Cuts/Cuts.h" #include "ThePEG/Utilities/SimplePhaseSpace.h" #include "Herwig/Models/StandardModel/StandardModel.h" #include "Herwig/Utilities/Maths.h" #include "Herwig/Shower/RealEmissionProcess.h" #include "ThePEG/Utilities/DescribeClass.h" using namespace Herwig; // The following static variable is needed for the type // description system in ThePEG. DescribeClass<MEPP2GammaGammaPowheg,Herwig::HwMEBase> describeMEPP2GammaGammaPowheg("Herwig::MEPP2GammaGammaPowheg", "HwMEHadron.so HwPowhegMEHadron.so"); unsigned int MEPP2GammaGammaPowheg::orderInAlphaS() const { return 0; } unsigned int MEPP2GammaGammaPowheg::orderInAlphaEW() const { return 2; } IBPtr MEPP2GammaGammaPowheg::clone() const { return new_ptr(*this); } IBPtr MEPP2GammaGammaPowheg::fullclone() const { return new_ptr(*this); } MEPP2GammaGammaPowheg::MEPP2GammaGammaPowheg() : contrib_(1), power_(0.1), process_(0), threeBodyProcess_(0), maxflavour_(5), alphaS_(0.), fixedAlphaS_(false), supressionFunction_(0), supressionScale_(0), lambda_(20.*GeV), preQCDqqbarq_(5.), preQCDqqbarqbar_(0.5), preQCDqg_(50.), preQCDgqbar_(50.), preQEDqqbarq_(40.), preQEDqqbarqbar_(0.5), preQEDqgq_(1.), preQEDgqbarqbar_(1.), minpT_(2.*GeV), scaleChoice_(0), scalePreFactor_(1.) {} void MEPP2GammaGammaPowheg::getDiagrams() const { tcPDPtr gamma = getParticleData(ParticleID::gamma); tcPDPtr g = getParticleData(ParticleID::g); for(int ix=1;ix<=maxflavour_;++ix) { tcPDPtr qk = getParticleData(ix); tcPDPtr qb = qk->CC(); // gamma gamma if(process_==0 || process_ == 1) { add(new_ptr((Tree2toNDiagram(3), qk, qk, qb, 1, gamma, 2, gamma, -1))); add(new_ptr((Tree2toNDiagram(3), qk, qk, qb, 2, gamma, 1, gamma, -2))); } // gamma +jet if(process_==0 || process_ == 2) { add(new_ptr((Tree2toNDiagram(3), qk, qb, qb, 1, gamma, 2, g, -4))); add(new_ptr((Tree2toNDiagram(3), qk, qk, qb, 2, gamma, 1, g, -5))); add(new_ptr((Tree2toNDiagram(3), qk, qk, g, 1, gamma, 2, qk, -6))); add(new_ptr((Tree2toNDiagram(2), qk, g, 1, qk, 3, gamma, 3, qk, -7))); add(new_ptr((Tree2toNDiagram(3), g, qb, qb, 2, gamma, 1, qb, -8))); add(new_ptr((Tree2toNDiagram(2), g, qb, 1, qb, 3, gamma, 3, qb, -9))); } // gamma + jet + gamma if((process_==0 && contrib_==1) || process_ == 3) { // gamma + g + gamma if(threeBodyProcess_==0 || threeBodyProcess_==1) { add(new_ptr((Tree2toNDiagram(4), qk, qk, qk, qb, 1, gamma, 2, gamma, 3, g, -10))); add(new_ptr((Tree2toNDiagram(4), qk, qk, qk, qb, 3, gamma, 2, gamma, 1, g, -12))); } // Z + q + gamma if(threeBodyProcess_==0 || threeBodyProcess_==2) { add(new_ptr((Tree2toNDiagram(4),qk,qk,qk,g,1,gamma,2,gamma,3,qk, -20))); add(new_ptr((Tree2toNDiagram(4),qk,qk,qk,g,2,gamma,1,gamma,3,qk, -21))); add(new_ptr((Tree2toNDiagram(3),qk,qk,g,1,gamma,2,qk,5,gamma,5,qk,-22))); } // Z + qbar + gamma if(threeBodyProcess_==0 || threeBodyProcess_==3) { add(new_ptr((Tree2toNDiagram(4),g,qb,qb,qb,3,gamma,2,gamma,1,qb ,-30))); add(new_ptr((Tree2toNDiagram(4),g,qb,qb,qb,2,gamma,3,gamma,1,qb ,-31))); add(new_ptr((Tree2toNDiagram(3),g,qb,qb ,2,gamma,1,qb,5,gamma,5,qb,-32))); } } } } Energy2 MEPP2GammaGammaPowheg::scale() const { Energy2 scale; if(scaleChoice_==0) { Energy pt; if(meMomenta()[2].perp(meMomenta()[0].vect())>= meMomenta()[3].perp(meMomenta()[0].vect())){ pt = meMomenta()[2].perp(meMomenta()[0].vect()); } else { pt = meMomenta()[3].perp(meMomenta()[0].vect()); } scale = sqr(pt); } else if(scaleChoice_==1) { scale = sHat(); } return scalePreFactor_*scale; } int MEPP2GammaGammaPowheg::nDim() const { return HwMEBase::nDim() + ( contrib_>=1 ? 3 : 0 ); } bool MEPP2GammaGammaPowheg::generateKinematics(const double * r) { // radiative variables if(contrib_>=1) { zTilde_ = r[nDim()-1]; vTilde_ = r[nDim()-2]; phi_ = Constants::twopi*r[nDim()-3]; } // set the jacobian jacobian(1.0); // set up the momenta for ( int i = 2, N = meMomenta().size(); i < N; ++i ) meMomenta()[i] = Lorentz5Momentum(ZERO); // generate sHat Energy2 shat(sHat()); if(mePartonData().size()==5) { double eps = sqr(meMomenta()[2].mass())/shat; jacobian(jacobian()*(1.-eps)); shat *= eps+zTilde_*(1.-eps); } // momenta of the core process double ctmin = -1.0, ctmax = 1.0; Energy q = ZERO; try { q = SimplePhaseSpace:: getMagnitude(shat, meMomenta()[2].mass(), ZERO); } catch ( ImpossibleKinematics & e ) { return false; } Energy e = 0.5*sqrt(shat); Energy2 m22 = meMomenta()[2].mass2(); Energy2 e0e2 = 2.0*e*sqrt(sqr(q) + m22); Energy2 e1e2 = 2.0*e*sqrt(sqr(q) + m22); Energy2 e0e3 = 2.0*e*sqrt(sqr(q)); Energy2 e1e3 = 2.0*e*sqrt(sqr(q)); Energy2 pq = 2.0*e*q; if(mePartonData().size()==4) { Energy2 thmin = lastCuts().minTij(mePartonData()[0], mePartonData()[2]); if ( thmin > ZERO ) ctmax = min(ctmax, (e0e2 - m22 - thmin)/pq); thmin = lastCuts().minTij(mePartonData()[1], mePartonData()[2]); if ( thmin > ZERO ) ctmin = max(ctmin, (thmin + m22 - e1e2)/pq); thmin = lastCuts().minTij(mePartonData()[1], mePartonData()[3]); if ( thmin > ZERO ) ctmax = min(ctmax, (e1e3 - thmin)/pq); thmin = lastCuts().minTij(mePartonData()[0], mePartonData()[3]); if ( thmin > ZERO ) ctmin = max(ctmin, (thmin - e0e3)/pq); Energy ptmin = max(lastCuts().minKT(mePartonData()[2]), lastCuts().minKT(mePartonData()[3])); if ( ptmin > ZERO ) { double ctm = 1.0 - sqr(ptmin/q); if ( ctm <= 0.0 ) return false; ctmin = max(ctmin, -sqrt(ctm)); ctmax = min(ctmax, sqrt(ctm)); } double ymin2 = lastCuts().minYStar(mePartonData()[2]); double ymax2 = lastCuts().maxYStar(mePartonData()[2]); double ymin3 = lastCuts().minYStar(mePartonData()[3]); double ymax3 = lastCuts().maxYStar(mePartonData()[3]); double ytot = lastCuts().Y() + lastCuts().currentYHat(); if ( ymin2 + ytot > -0.9*Constants::MaxRapidity ) ctmin = max(ctmin, sqrt(sqr(q) + m22)*tanh(ymin2)/q); if ( ymax2 + ytot < 0.9*Constants::MaxRapidity ) ctmax = min(ctmax, sqrt(sqr(q) + m22)*tanh(ymax2)/q); if ( ymin3 + ytot > -0.9*Constants::MaxRapidity ) ctmax = min(ctmax, tanh(-ymin3)); if ( ymax3 + ytot < 0.9*Constants::MaxRapidity ) ctmin = max(ctmin, tanh(-ymax3)); if ( ctmin >= ctmax ) return false; } double cth = getCosTheta(ctmin, ctmax, r[0]); Energy pt = q*sqrt(1.0-sqr(cth)); phi(rnd(2.0*Constants::pi)); meMomenta()[2].setVect(Momentum3( pt*sin(phi()), pt*cos(phi()), q*cth)); meMomenta()[3].setVect(Momentum3(-pt*sin(phi()), -pt*cos(phi()), -q*cth)); meMomenta()[2].rescaleEnergy(); meMomenta()[3].rescaleEnergy(); // jacobian tHat(pq*cth + m22 - e0e2); uHat(m22 - shat - tHat()); jacobian(pq/shat*Constants::pi*jacobian()); // end for 2->2 processes if(mePartonData().size()==4) { vector<LorentzMomentum> out(2); out[0] = meMomenta()[2]; out[1] = meMomenta()[3]; tcPDVector tout(2); tout[0] = mePartonData()[2]; tout[1] = mePartonData()[3]; if ( !lastCuts().passCuts(tout, out, mePartonData()[0], mePartonData()[1]) ) return false; return true; } // special for 2-3 processes pair<double,double> x = make_pair(lastX1(),lastX2()); // partons pair<tcPDPtr,tcPDPtr> partons = make_pair(mePartonData()[0],mePartonData()[1]); // If necessary swap the particle data objects so that // first beam gives the incoming quark if(lastPartons().first ->dataPtr()!=partons.first) { swap(x.first,x.second); } // use vTilde to select the dipole for emission // gamma gamma g processes if(mePartonData()[4]->id()==ParticleID::g) { if(vTilde_<=0.5) { dipole_ = IIQCD1; vTilde_ = 4.*vTilde_; } else { dipole_ = IIQCD2; vTilde_ = 4.*(vTilde_-0.25); } jacobian(2.*jacobian()); } // gamma gamma q processes else if(mePartonData()[4]->id()>0&&mePartonData()[4]->id()<6) { if(vTilde_<=1./3.) { dipole_ = IIQCD2; vTilde_ = 3.*vTilde_; } else if(vTilde_<=2./3.) { dipole_ = IFQED1; vTilde_ = 3.*vTilde_-1.; } else { dipole_ = FIQED1; vTilde_ = 3.*vTilde_-2.; } jacobian(3.*jacobian()); } // gamma gamma qbar processes else if(mePartonData()[4]->id()<0&&mePartonData()[4]->id()>-6) { if(vTilde_<=1./3.) { dipole_ = IIQCD1; vTilde_ = 3.*vTilde_; } else if(vTilde_<=2./3.) { dipole_ = IFQED2; vTilde_ = 3.*vTilde_-1.; } else { dipole_ = FIQED2; vTilde_ = 3.*vTilde_-2.; } jacobian(3.*jacobian()); } else { assert(false); } // initial-initial dipoles if(dipole_<=4) { double z = shat/sHat(); double vt = vTilde_*(1.-z); double vJac = 1.-z; Energy pT = sqrt(shat*vt*(1.-vt-z)/z); if(pT<MeV) return false; double rapidity; Energy rs=sqrt(lastS()); Lorentz5Momentum pcmf; // emission from first beam if(dipole_<=2) { rapidity = -log(x.second*sqrt(lastS())/pT*vt); pcmf = Lorentz5Momentum(ZERO,ZERO, 0.5*rs*(x.first*z-x.second), 0.5*rs*(x.first*z+x.second)); } // emission from second beam else { rapidity = log(x.first *sqrt(lastS())/pT*vt); pcmf = Lorentz5Momentum(ZERO,ZERO, 0.5*rs*(x.first-x.second*z), 0.5*rs*(x.first+x.second*z)); } pcmf.rescaleMass(); Boost blab(pcmf.boostVector()); // emission from the quark radiation vector<Lorentz5Momentum> pnew(5); pnew [0] = Lorentz5Momentum(ZERO,ZERO,0.5*rs*x.first, 0.5*rs*x.first,ZERO); pnew [1] = Lorentz5Momentum(ZERO,ZERO,-0.5*rs*x.second, 0.5*rs*x.second,ZERO) ; pnew [2] = meMomenta()[2]; pnew [3] = meMomenta()[3]; pnew [4] = Lorentz5Momentum(pT*cos(phi_),pT*sin(phi_), pT*sinh(rapidity), pT*cosh(rapidity), ZERO); pnew[4].rescaleEnergy(); Lorentz5Momentum K = pnew [0]+pnew [1]-pnew [4]; Lorentz5Momentum Kt = pcmf; Lorentz5Momentum Ksum = K+Kt; Energy2 K2 = K.m2(); Energy2 Ksum2 = Ksum.m2(); for(unsigned int ix=2;ix<4;++ix) { pnew [ix].boost(blab); pnew [ix] = pnew [ix] - 2.*Ksum*(Ksum*pnew [ix])/Ksum2 +2*K*(Kt*pnew [ix])/K2; pnew[ix].rescaleEnergy(); } pcmf = Lorentz5Momentum(ZERO,ZERO, 0.5*rs*(x.first-x.second), 0.5*rs*(x.first+x.second)); pcmf.rescaleMass(); blab = pcmf.boostVector(); for(unsigned int ix=0;ix<pnew.size();++ix) pnew[ix].boost(-blab); // phase-space prefactors jacobian(jacobian()*vJac); if(dipole_%2!=0) swap(pnew[3],pnew[4]); for(unsigned int ix=2;ix<meMomenta().size();++ix) meMomenta()[ix] = pnew[ix]; } else if(dipole_<=8) { double x = shat/sHat(); double z = vTilde_; double x1 = -1./x; double x3 = 1.-z/x; double x2 = 2.+x1-x3; double xT = sqrt(4.*(1-x)*(1-z)*z/x); // rotate the momenta into the Breit-frame Lorentz5Momentum pin,pcmf; if(dipole_<=6) { pin = x*meMomenta()[0]; pcmf = pin+meMomenta()[1]; } else { pin = x*meMomenta()[1]; pcmf = pin+meMomenta()[0]; } Boost bv = pcmf.boostVector(); meMomenta()[2].boost(bv); meMomenta()[3].boost(bv); Lorentz5Momentum q = meMomenta()[3]-pin; Axis axis(q.vect().unit()); LorentzRotation rot; double sinth(sqrt(sqr(axis.x())+sqr(axis.y()))); rot = LorentzRotation(); if(axis.perp2()>1e-20) { rot.setRotate(-acos(axis.z()),Axis(-axis.y()/sinth,axis.x()/sinth,0.)); rot.rotateX(Constants::pi); } if(abs(1.-q.e()/q.vect().mag())>1e-6) rot.boostZ(q.e()/q.vect().mag()); pin *= rot; if(pin.perp2()/GeV2>1e-20) { Boost trans = -1./pin.e()*pin.vect(); trans.setZ(0.); rot.boost(trans); } rot.invert(); Energy Q = sqrt(-q.m2()); meMomenta()[4] = rot*Lorentz5Momentum( 0.5*Q*xT*cos(phi_), 0.5*Q*xT*sin(phi_), -0.5*Q*x2,0.5*Q*sqrt(sqr(x2)+sqr(xT))); meMomenta()[3] = rot*Lorentz5Momentum(-0.5*Q*xT*cos(phi_),-0.5*Q*xT*sin(phi_), -0.5*Q*x3,0.5*Q*sqrt(sqr(x3)+sqr(xT))); double ratio; if(dipole_<=6) { ratio = 2.*((meMomenta()[3]+meMomenta()[4])*meMomenta()[0])/sHat(); } else { ratio = 2.*((meMomenta()[3]+meMomenta()[4])*meMomenta()[1])/sHat(); } jacobian(jacobian()*ratio); } else { assert(false); } vector<LorentzMomentum> out(3); tcPDVector tout(3); for(unsigned int ix=0;ix<3;++ix) { out[ix] = meMomenta() [2+ix]; tout[ix] = mePartonData()[2+ix]; } return lastCuts().passCuts(tout, out, mePartonData()[0], mePartonData()[1]); } double MEPP2GammaGammaPowheg::me2() const { // Born configurations if(mePartonData().size()==4) { // gamma gamma core process if(mePartonData()[3]->id()==ParticleID::gamma) { return 2.*Constants::twopi*alphaEM_* loGammaGammaME(mePartonData(),meMomenta(),true); } // V jet core process else if(mePartonData()[3]->id()==ParticleID::g) { return 2.*Constants::twopi*alphaS_* loGammagME(mePartonData(),meMomenta(),true); } else if(mePartonData()[3]->id()>0) { return 2.*Constants::twopi*alphaS_* loGammaqME(mePartonData(),meMomenta(),true); } else if(mePartonData()[3]->id()<0) { return 2.*Constants::twopi*alphaS_* loGammaqbarME(mePartonData(),meMomenta(),true); } else { assert(false); return 0.; } } // hard emission configurations else { if(mePartonData()[4]->id()==ParticleID::g) return sHat()*realGammaGammagME (mePartonData(),meMomenta(),dipole_,Hard,true); else if(mePartonData()[4]->id()>0&&mePartonData()[4]->id()<6) return sHat()*realGammaGammaqME (mePartonData(),meMomenta(),dipole_,Hard,true); else if(mePartonData()[4]->id()<0&&mePartonData()[4]->id()>-6) return sHat()*realGammaGammaqbarME(mePartonData(),meMomenta(),dipole_,Hard,true); else { assert(false); return 0.; } } } CrossSection MEPP2GammaGammaPowheg::dSigHatDR() const { // couplings if(!fixedAlphaS_) alphaS_ = SM().alphaS(scale()); alphaEM_ = SM().alphaEM(); // cross section CrossSection preFactor = jacobian()/(16.0*sqr(Constants::pi)*sHat())*sqr(hbarc); loME_ = me2(); if( contrib_== 0 || mePartonData().size()==5 || (mePartonData().size()==4&& mePartonData()[3]->coloured())) return loME_*preFactor; else return NLOWeight()*preFactor; } Selector<MEBase::DiagramIndex> MEPP2GammaGammaPowheg::diagrams(const DiagramVector & diags) const { if(mePartonData().size()==4) { if(mePartonData()[3]->id()==ParticleID::gamma) { Selector<DiagramIndex> sel; for ( DiagramIndex i = 0; i < diags.size(); ++i ){ sel.insert(meInfo()[abs(diags[i]->id())], i); } return sel; } else { Selector<DiagramIndex> sel; for ( DiagramIndex i = 0; i < diags.size(); ++i ){ sel.insert(meInfo()[abs(diags[i]->id())%2], i); } return sel; } } else { Selector<DiagramIndex> sel; for ( DiagramIndex i = 0; i < diags.size(); ++i ) { if(abs(diags[i]->id()) == 10 && dipole_ == IIQCD2 ) sel.insert(1., i); else if(abs(diags[i]->id()) == 12 && dipole_ == IIQCD1 ) sel.insert(1., i); else if(abs(diags[i]->id()) == 20 && dipole_ == IIQCD2 ) sel.insert(1., i); else if(abs(diags[i]->id()) == 21 && dipole_ == IFQED1 ) sel.insert(1., i); else if(abs(diags[i]->id()) == 22 && dipole_ == FIQED1 ) sel.insert(1., i); else sel.insert(0., i); } return sel; } } Selector<const ColourLines *> MEPP2GammaGammaPowheg::colourGeometries(tcDiagPtr diag) const { // colour lines for V gamma static ColourLines cs("1 -2"); static ColourLines ct("1 2 -3"); // colour lines for q qbar -> V g static const ColourLines cqqbar[2]={ColourLines("1 -2 5,-3 -5"), ColourLines("1 5,-5 2 -3")}; // colour lines for q g -> V q static const ColourLines cqg [2]={ColourLines("1 2 -3,3 5"), ColourLines("1 -2,2 3 5")}; // colour lines for g qbar -> V qbar static const ColourLines cgqbar[2]={ColourLines("-3 -2 1,-1 -5"), ColourLines("-2 1,-1 -3 -5")}; // colour lines for q qbar -> V gamma g static const ColourLines cqqbarg[4]={ColourLines("1 2 3 7,-4 -7"), ColourLines("1 2 7,-4 3 -7"), ColourLines("1 7,-4 3 2 -7"), ColourLines("1 2 7,-4 3 -7")}; // colour lines for q g -> V gamma q static const ColourLines cqgq [3]={ColourLines("1 2 3 -4,4 7"), ColourLines("1 2 3 -4,4 7"), ColourLines("1 2 -3,3 5 7")}; // colour lines for gbar -> V gamma qbar static const ColourLines cqbargqbar[3]={ColourLines("1 -2 -3 -4,-1 -7"), ColourLines("1 -2 -3 -4,-1 -7"), ColourLines("1 -2 -3,-1 -5 -7")}; Selector<const ColourLines *> sel; switch(abs(diag->id())) { case 1 :case 2 : sel.insert(1.0, &ct); break; case 3 : sel.insert(1.0, &cs); break; case 4 : sel.insert(1.0, &cqqbar[0]); break; case 5: sel.insert(1.0, &cqqbar[1]); break; case 6: sel.insert(1.0, &cqg[0]); break; case 7: sel.insert(1.0, &cqg[1]); break; case 8: sel.insert(1.0, &cgqbar[0]); break; case 9: sel.insert(1.0, &cgqbar[1]); break; case 10: case 11: case 12: case 13: sel.insert(1.0, &cqqbarg[abs(diag->id())-10]); break; case 20: case 21: case 22: sel.insert(1.0, &cqgq[abs(diag->id())-20]); break; case 30: case 31: case 32: sel.insert(1.0, &cqbargqbar[abs(diag->id())-30]); break; default: assert(false); } return sel; } void MEPP2GammaGammaPowheg::persistentOutput(PersistentOStream & os) const { os << FFPvertex_ << FFGvertex_ << contrib_ << power_ << gluon_ << prefactor_ << process_ << threeBodyProcess_<< maxflavour_ << alphaS_ << fixedAlphaS_ << supressionFunction_ << supressionScale_ << ounit(lambda_,GeV) << alphaQCD_ << alphaQED_ << ounit(minpT_,GeV) << preQCDqqbarq_ << preQCDqqbarqbar_ << preQCDqg_ << preQCDgqbar_ << preQEDqqbarq_ << preQEDqqbarqbar_ << preQEDqgq_ << preQEDgqbarqbar_ << scaleChoice_ << scalePreFactor_; } void MEPP2GammaGammaPowheg::persistentInput(PersistentIStream & is, int) { is >> FFPvertex_ >> FFGvertex_ >> contrib_ >> power_ >> gluon_ >> prefactor_ >> process_ >> threeBodyProcess_ >> maxflavour_ >> alphaS_ >> fixedAlphaS_ >> supressionFunction_ >> supressionScale_ >> iunit(lambda_,GeV) >> alphaQCD_ >> alphaQED_ >> iunit(minpT_,GeV) >> preQCDqqbarq_ >> preQCDqqbarqbar_ >> preQCDqg_ >> preQCDgqbar_ >> preQEDqqbarq_ >> preQEDqqbarqbar_ >> preQEDqgq_ >> preQEDgqbarqbar_ >> scaleChoice_ >> scalePreFactor_; } void MEPP2GammaGammaPowheg::Init() { static ClassDocumentation<MEPP2GammaGammaPowheg> documentation ("TheMEPP2GammaGammaPowheg class implements gamma gamma production at NLO"); static Switch<MEPP2GammaGammaPowheg,unsigned int> interfaceProcess ("Process", "Which processes to include", &MEPP2GammaGammaPowheg::process_, 0, false, false); static SwitchOption interfaceProcessAll (interfaceProcess, "All", "Include all the processes", 0); static SwitchOption interfaceProcessGammaGamma (interfaceProcess, "GammaGamma", "Only include gamma gamma", 1); static SwitchOption interfaceProcessVJet (interfaceProcess, "VJet", "Only include gamma + jet", 2); static SwitchOption interfaceProcessHard (interfaceProcess, "Hard", "Only include hard radiation contributions", 3); static Switch<MEPP2GammaGammaPowheg,unsigned int> interfaceThreeBodyProcess ("ThreeBodyProcess", "The possible three body processes to include", &MEPP2GammaGammaPowheg::threeBodyProcess_, 0, false, false); static SwitchOption interfaceThreeBodyProcessAll (interfaceThreeBodyProcess, "All", "Include all processes", 0); static SwitchOption interfaceThreeBodyProcessqqbar (interfaceThreeBodyProcess, "qqbar", "Only include q qbar -> gamma gamma g processes", 1); static SwitchOption interfaceThreeBodyProcessqg (interfaceThreeBodyProcess, "qg", "Only include q g -> gamma gamma q processes", 2); static SwitchOption interfaceThreeBodyProcessgqbar (interfaceThreeBodyProcess, "gqbar", "Only include g qbar -> gamma gamma qbar processes", 3); static Switch<MEPP2GammaGammaPowheg,unsigned int> interfaceContribution ("Contribution", "Which contributions to the cross section to include", &MEPP2GammaGammaPowheg::contrib_, 1, false, false); static SwitchOption interfaceContributionLeadingOrder (interfaceContribution, "LeadingOrder", "Just generate the leading order cross section", 0); static SwitchOption interfaceContributionPositiveNLO (interfaceContribution, "PositiveNLO", "Generate the positive contribution to the full NLO cross section", 1); static SwitchOption interfaceContributionNegativeNLO (interfaceContribution, "NegativeNLO", "Generate the negative contribution to the full NLO cross section", 2); static Parameter<MEPP2GammaGammaPowheg,int> interfaceMaximumFlavour ("MaximumFlavour", "The maximum flavour allowed for the incoming quarks", &MEPP2GammaGammaPowheg::maxflavour_, 5, 1, 5, false, false, Interface::limited); static Parameter<MEPP2GammaGammaPowheg,double> interfaceAlphaS ("AlphaS", "The value of alphaS to use if using a fixed alphaS", &MEPP2GammaGammaPowheg::alphaS_, 0.118, 0.0, 0.2, false, false, Interface::limited); static Switch<MEPP2GammaGammaPowheg,bool> interfaceFixedAlphaS ("FixedAlphaS", "Use a fixed value of alphaS", &MEPP2GammaGammaPowheg::fixedAlphaS_, false, false, false); static SwitchOption interfaceFixedAlphaSYes (interfaceFixedAlphaS, "Yes", "Use a fixed alphaS", true); static SwitchOption interfaceFixedAlphaSNo (interfaceFixedAlphaS, "No", "Use a running alphaS", false); static Switch<MEPP2GammaGammaPowheg,unsigned int> interfaceSupressionFunction ("SupressionFunction", "Choice of the supression function", &MEPP2GammaGammaPowheg::supressionFunction_, 0, false, false); static SwitchOption interfaceSupressionFunctionNone (interfaceSupressionFunction, "None", "Default POWHEG approach", 0); static SwitchOption interfaceSupressionFunctionThetaFunction (interfaceSupressionFunction, "ThetaFunction", "Use theta functions at scale Lambda", 1); static SwitchOption interfaceSupressionFunctionSmooth (interfaceSupressionFunction, "Smooth", "Supress high pT by pt^2/(pt^2+lambda^2)", 2); static Parameter<MEPP2GammaGammaPowheg,Energy> interfaceSupressionScale ("SupressionScale", "The square of the scale for the supression function", &MEPP2GammaGammaPowheg::lambda_, GeV, 20.0*GeV, 0.0*GeV, 0*GeV, false, false, Interface::lowerlim); static Switch<MEPP2GammaGammaPowheg,unsigned int> interfaceSupressionScaleChoice ("SupressionScaleChoice", "Choice of the supression scale", &MEPP2GammaGammaPowheg::supressionScale_, 0, false, false); static SwitchOption interfaceSupressionScaleChoiceFixed (interfaceSupressionScaleChoice, "Fixed", "Use a fixed scale", 0); static SwitchOption interfaceSupressionScaleChoiceVariable (interfaceSupressionScaleChoice, "Variable", "Use the pT of the hard process as the scale", 1); static Reference<MEPP2GammaGammaPowheg,ShowerAlpha> interfaceShowerAlphaQCD ("ShowerAlphaQCD", "Reference to the object calculating the QCD coupling for the shower", &MEPP2GammaGammaPowheg::alphaQCD_, false, false, true, false, false); static Reference<MEPP2GammaGammaPowheg,ShowerAlpha> interfaceShowerAlphaQED ("ShowerAlphaQED", "Reference to the object calculating the QED coupling for the shower", &MEPP2GammaGammaPowheg::alphaQED_, false, false, true, false, false); static Parameter<MEPP2GammaGammaPowheg,double> interfacepreQCDqqbarq ("preQCDqqbarq", "The constant for the Sudakov overestimate for the " "q qbar -> V Gamma +g with emission from the q", &MEPP2GammaGammaPowheg::preQCDqqbarq_, 23.0, 0.0, 1000.0, false, false, Interface::limited); static Parameter<MEPP2GammaGammaPowheg,double> interfacepreQCDqqbarqbar ("preQCDqqbarqbar", "The constant for the Sudakov overestimate for the " "q qbar -> V Gamma +g with emission from the qbar", &MEPP2GammaGammaPowheg::preQCDqqbarqbar_, 23.0, 0.0, 1000.0, false, false, Interface::limited); static Switch<MEPP2GammaGammaPowheg,unsigned int> interfaceScaleChoice ("ScaleChoice", "The scale choice to use", &MEPP2GammaGammaPowheg::scaleChoice_, 0, false, false); static SwitchOption interfaceScaleChoicepT (interfaceScaleChoice, "pT", "Use the pT of the photons", 0); static SwitchOption interfaceScaleChoiceMGammaGamma (interfaceScaleChoice, "MGammaGamma", "Use the mass of the photon pair", 1); static Parameter<MEPP2GammaGammaPowheg,double> interfaceScalePreFactor ("ScalePreFactor", "Prefactor to change factorization/renormalisation scale", &MEPP2GammaGammaPowheg::scalePreFactor_, 1.0, 0.1, 10.0, false, false, Interface::limited); // prefactor_.push_back(preQCDqg_); // prefactor_.push_back(preQCDgqbar_); // prefactor_.push_back(preQEDqqbarq_); // prefactor_.push_back(preQEDqqbarqbar_); // prefactor_.push_back(preQEDqgq_); // prefactor_.push_back(preQEDgqbarqbar_); } double MEPP2GammaGammaPowheg::NLOWeight() const { // if leading-order return if(contrib_==0) return loME_; // prefactors CFfact_ = 4./3.*alphaS_/Constants::twopi; TRfact_ = 1./2.*alphaS_/Constants::twopi; // scale Energy2 mu2 = scale(); // virtual pieces double virt = CFfact_*subtractedVirtual(); // extract the partons and stuff for the real emission // and collinear counter terms // hadrons pair<tcBeamPtr,tcBeamPtr> hadrons= make_pair(dynamic_ptr_cast<tcBeamPtr>(lastParticles().first->dataPtr() ), dynamic_ptr_cast<tcBeamPtr>(lastParticles().second->dataPtr())); // momentum fractions pair<double,double> x = make_pair(lastX1(),lastX2()); // partons pair<tcPDPtr,tcPDPtr> partons = make_pair(mePartonData()[0],mePartonData()[1]); // If necessary swap the particle data objects so that // first beam gives the incoming quark if(lastPartons().first ->dataPtr()!=partons.first) { swap(x.first,x.second); swap(hadrons.first,hadrons.second); } // convert the values of z tilde to z pair<double,double> z; pair<double,double> zJac; double rhomax(pow(1.-x.first,1.-power_)); double rho = zTilde_*rhomax; z.first = 1.-pow(rho,1./(1.-power_)); zJac.first = rhomax*pow(1.-z.first,power_)/(1.-power_); rhomax = pow(1.-x.second,1.-power_); rho = zTilde_*rhomax; z.second = 1.-pow(rho,1./(1.-power_)); zJac.second = rhomax*pow(1.-z.second,power_)/(1.-power_); // calculate the PDFs pair<double,double> oldqPDF = make_pair(hadrons.first ->pdf()->xfx(hadrons.first ,partons.first ,scale(), x.first )/x.first , hadrons.second->pdf()->xfx(hadrons.second,partons.second,scale(), x.second)/x.second); // real/coll q/qbar pair<double,double> newqPDF = make_pair(hadrons.first ->pdf()->xfx(hadrons.first ,partons.first ,scale(), x.first /z.first )*z.first /x.first , hadrons.second->pdf()->xfx(hadrons.second,partons.second,scale(), x.second/z.second)*z.second/x.second); // real/coll gluon pair<double,double> newgPDF = make_pair(hadrons.first ->pdf()->xfx(hadrons.first ,gluon_,scale(), x.first /z.first )*z.first /x.first , hadrons.second->pdf()->xfx(hadrons.second,gluon_,scale(), x.second/z.second)*z.second/x.second); // coll terms // g -> q double collGQ = collinearGluon(mu2,zJac.first,z.first, oldqPDF.first,newgPDF.first); // g -> qbar double collGQbar = collinearGluon(mu2,zJac.second,z.second, oldqPDF.second,newgPDF.second); // q -> q double collQQ = collinearQuark(x.first ,mu2,zJac.first ,z.first , oldqPDF.first ,newqPDF.first ); // qbar -> qbar double collQbarQbar = collinearQuark(x.second,mu2,zJac.second,z.second, oldqPDF.second,newqPDF.second); // collinear remnants double coll = collQQ+collQbarQbar+collGQ+collGQbar; // real emission contribution double real1 = subtractedReal(x,z. first,zJac. first,oldqPDF. first, newqPDF. first,newgPDF. first, true); double real2 = subtractedReal(x,z.second,zJac.second,oldqPDF.second, newqPDF.second,newgPDF.second,false); // the total weight double wgt = loME_ + loME_*virt + loME_*coll + real1 + real2; return contrib_ == 1 ? max(0.,wgt) : max(0.,-wgt); } double MEPP2GammaGammaPowheg::loGammaGammaME(const cPDVector & particles, const vector<Lorentz5Momentum> & momenta, bool first) const { double output(0.); // analytic formula for speed if(!first) { Energy2 th = (momenta[0]-momenta[2]).m2(); Energy2 uh = (momenta[0]-momenta[3]).m2(); output = 4./3.*Constants::pi*SM().alphaEM(ZERO)*(th/uh+uh/th)* pow(double(particles[0]->iCharge())/3.,4); } // HE code result else { // wavefunctions for the incoming fermions SpinorWaveFunction em_in( momenta[0],particles[0],incoming); SpinorBarWaveFunction ep_in( momenta[1],particles[1],incoming); // wavefunctions for the outgoing bosons VectorWaveFunction v1_out(momenta[2],particles[2],outgoing); VectorWaveFunction v2_out(momenta[3],particles[3],outgoing); vector<SpinorWaveFunction> f1; vector<SpinorBarWaveFunction> a1; vector<VectorWaveFunction> v1,v2; // calculate the wavefunctions for(unsigned int ix=0;ix<2;++ix) { em_in.reset(ix); f1.push_back(em_in); ep_in.reset(ix); a1.push_back(ep_in); v1_out.reset(2*ix); v1.push_back(v1_out); v2_out.reset(2*ix); v2.push_back(v2_out); } vector<double> me(4,0.0); me_.reset(ProductionMatrixElement(PDT::Spin1Half,PDT::Spin1Half, PDT::Spin1,PDT::Spin1)); vector<Complex> diag(2,0.0); SpinorWaveFunction inter; for(unsigned int ihel1=0;ihel1<2;++ihel1) { for(unsigned int ihel2=0;ihel2<2;++ihel2) { for(unsigned int ohel1=0;ohel1<2;++ohel1) { for(unsigned int ohel2=0;ohel2<2;++ohel2) { inter = FFPvertex_->evaluate(ZERO,5,f1[ihel1].particle()->CC(), f1[ihel1],v1[ohel1]); diag[0] = FFPvertex_->evaluate(ZERO,inter,a1[ihel2],v2[ohel2]); inter = FFPvertex_->evaluate(ZERO,5,f1[ihel1].particle()->CC(), f1[ihel1] ,v2[ohel2]); diag[1] = FFPvertex_->evaluate(ZERO,inter,a1[ihel2],v1[ohel1]); // individual diagrams for (size_t ii=0; ii<2; ++ii) me[ii] += std::norm(diag[ii]); // full matrix element diag[0] += diag[1]; output += std::norm(diag[0]); // storage of the matrix element for spin correlations me_(ihel1,ihel2,2*ohel1,2*ohel2) = diag[0]; } } } } // store diagram info, etc. DVector save(3); for (size_t i = 0; i < 3; ++i) save[i] = 0.25 * me[i]; meInfo(save); // spin and colour factors output *= 0.125/3./norm(FFPvertex_->norm()); } return output; } double MEPP2GammaGammaPowheg::loGammaqME(const cPDVector & particles, const vector<Lorentz5Momentum> & momenta, bool first) const { double output(0.); // analytic formula for speed if(!first) { Energy2 sh = (momenta[0]+momenta[1]).m2(); Energy2 th = (momenta[0]-momenta[2]).m2(); Energy2 uh = (momenta[0]-momenta[3]).m2(); output = -1./3./sh/th*(sh*sh+th*th+2.*uh*(sh+th+uh))* 4.*Constants::pi*SM().alphaEM(ZERO)* sqr(particles[0]->iCharge()/3.); } // HE result else { vector<SpinorWaveFunction> fin; vector<VectorWaveFunction> gin; vector<SpinorBarWaveFunction> fout; vector<VectorWaveFunction> vout; SpinorWaveFunction qin (momenta[0],particles[0],incoming); VectorWaveFunction glin(momenta[1],particles[1],incoming); VectorWaveFunction wout(momenta[2],particles[2],outgoing); SpinorBarWaveFunction qout(momenta[3],particles[3],outgoing); // polarization states for the particles for(unsigned int ix=0;ix<2;++ix) { qin.reset(ix) ; fin.push_back(qin); qout.reset(ix); fout.push_back(qout); glin.reset(2*ix); gin.push_back(glin); wout.reset(2*ix); vout.push_back(wout); } me_.reset(ProductionMatrixElement(PDT::Spin1Half,PDT::Spin1, PDT::Spin1,PDT::Spin1Half)); // compute the matrix elements double me[3]={0.,0.,0.}; Complex diag[2]; SpinorWaveFunction inters; SpinorBarWaveFunction interb; for(unsigned int ihel1=0;ihel1<2;++ihel1) { for(unsigned int ihel2=0;ihel2<2;++ihel2) { for(unsigned int ohel1=0;ohel1<2;++ohel1) { // intermediates for the diagrams interb= FFGvertex_->evaluate(scale(),5,particles[3]->CC(), fout[ohel1],gin[ihel2]); inters= FFGvertex_->evaluate(scale(),5,particles[0], fin[ihel1],gin[ihel2]); for(unsigned int vhel=0;vhel<2;++vhel) { diag[0] = FFPvertex_->evaluate(ZERO,fin[ihel1],interb,vout[vhel]); diag[1] = FFPvertex_->evaluate(ZERO,inters,fout[ohel1],vout[vhel]); // diagram contributions me[1] += norm(diag[0]); me[2] += norm(diag[1]); // total diag[0] += diag[1]; me[0] += norm(diag[0]); me_(ihel1,2*ihel2,2*vhel,ohel1) = diag[0]; } } } } // results // initial state spin and colour average double colspin = 1./24./4.; // and C_F N_c from matrix element colspin *= 4.; DVector save; for(unsigned int ix=0;ix<3;++ix) { me[ix] *= colspin; if(ix>0) save.push_back(me[ix]); } meInfo(save); output = me[0]/norm(FFGvertex_->norm()); } return output; } double MEPP2GammaGammaPowheg::loGammaqbarME(const cPDVector & particles, const vector<Lorentz5Momentum> & momenta, bool first) const { double output(0.); // analytic formula for speed if(!first) { Energy2 sh = (momenta[0]+momenta[1]).m2(); Energy2 uh = (momenta[0]-momenta[2]).m2(); Energy2 th = (momenta[0]-momenta[3]).m2(); output = -1./3./sh/th*(sh*sh+th*th+2.*uh*(sh+th+uh))* 4.*Constants::pi*SM().alphaEM()* sqr(particles[1]->iCharge()/3.); } // HE result else { vector<SpinorBarWaveFunction> ain; vector<VectorWaveFunction> gin; vector<SpinorWaveFunction> aout; vector<VectorWaveFunction> vout; VectorWaveFunction glin (momenta[0],particles[0],incoming); SpinorBarWaveFunction qbin (momenta[1],particles[1],incoming); VectorWaveFunction wout (momenta[2],particles[2],outgoing); SpinorWaveFunction qbout(momenta[3],particles[3],outgoing); // polarization states for the particles for(unsigned int ix=0;ix<2;++ix) { qbin .reset(ix ); ain .push_back(qbin ); qbout.reset(ix ); aout.push_back(qbout); glin.reset(2*ix); gin.push_back(glin); wout.reset(2*ix); vout.push_back(wout); } // if calculation spin corrections construct the me me_.reset(ProductionMatrixElement(PDT::Spin1,PDT::Spin1Half, PDT::Spin1,PDT::Spin1Half)); // compute the matrix elements double me[3]={0.,0.,0.}; Complex diag[2]; SpinorWaveFunction inters; SpinorBarWaveFunction interb; for(unsigned int ihel1=0;ihel1<2;++ihel1) { for(unsigned int ihel2=0;ihel2<2;++ihel2) { for(unsigned int ohel1=0;ohel1<2;++ohel1) { // intermediates for the diagrams inters= FFGvertex_->evaluate(scale(),5,particles[3]->CC(), aout[ohel1],gin[ihel1]); interb= FFGvertex_->evaluate(scale(),5,particles[1], ain[ihel2],gin[ihel1]); for(unsigned int vhel=0;vhel<2;++vhel) { diag[0]= FFPvertex_->evaluate(ZERO,inters,ain[ihel2],vout[vhel]); diag[1]= FFPvertex_->evaluate(ZERO,aout[ohel1],interb,vout[vhel]); // diagram contributions me[1] += norm(diag[0]); me[2] += norm(diag[1]); // total diag[0] += diag[1]; me[0] += norm(diag[0]); me_(2*ihel1,ihel2,2*vhel,ohel1) = diag[0]; } } } } // results // initial state spin and colour average double colspin = 1./24./4.; // and C_F N_c from matrix element colspin *= 4.; DVector save; for(unsigned int ix=0;ix<3;++ix) { me[ix] *= colspin; if(ix>0) save.push_back(me[ix]); } meInfo(save); output = me[0]/norm(FFGvertex_->norm()); } return output; } double MEPP2GammaGammaPowheg::loGammagME(const cPDVector & particles, const vector<Lorentz5Momentum> & momenta, bool first) const { double output(0.); // analytic formula for speed if(!first) { Energy2 uh = (momenta[0]-momenta[2]).m2(); Energy2 th = (momenta[0]-momenta[3]).m2(); output = 8./9.*double((th*th+uh*uh)/uh/th)* 4.*Constants::pi*SM().alphaEM(ZERO)* sqr(particles[0]->iCharge()/3.); } else { vector<SpinorWaveFunction> fin; vector<SpinorBarWaveFunction> ain; vector<VectorWaveFunction> gout; vector<VectorWaveFunction> vout; SpinorWaveFunction qin (momenta[0],particles[0],incoming); SpinorBarWaveFunction qbin(momenta[1],particles[1],incoming); VectorWaveFunction wout(momenta[2],particles[2],outgoing); VectorWaveFunction glout(momenta[3],particles[3],outgoing); // polarization states for the particles for(unsigned int ix=0;ix<2;++ix) { qin.reset(ix) ; fin.push_back(qin); qbin.reset(ix) ; ain.push_back(qbin); glout.reset(2*ix); gout.push_back(glout); wout.reset(2*ix); vout.push_back(wout); } // if calculation spin corrections construct the me if(first) me_.reset(ProductionMatrixElement(PDT::Spin1Half,PDT::Spin1Half, PDT::Spin1,PDT::Spin1)); // compute the matrix elements double me[3]={0.,0.,0.}; Complex diag[2]; SpinorWaveFunction inters; SpinorBarWaveFunction interb; for(unsigned int ihel1=0;ihel1<2;++ihel1) { for(unsigned int ihel2=0;ihel2<2;++ihel2) { for(unsigned int ohel1=0;ohel1<2;++ohel1) { // intermediates for the diagrams inters= FFGvertex_->evaluate(scale(),5,particles[0], fin[ihel1],gout[ohel1]); interb= FFGvertex_->evaluate(scale(),5,particles[1], ain[ihel2],gout[ohel1]); for(unsigned int vhel=0;vhel<2;++vhel) { diag[0]= FFPvertex_->evaluate(ZERO,fin[ihel1],interb,vout[vhel]); diag[1]= FFPvertex_->evaluate(ZERO,inters,ain[ihel2],vout[vhel]); // diagram contributions me[1] += norm(diag[0]); me[2] += norm(diag[1]); // total diag[0] += diag[1]; me[0] += norm(diag[0]); if(first) me_(ihel1,ihel2,vhel,2*ohel1) = diag[0]; } } } } // results // initial state spin and colour average double colspin = 1./9./4.; // and C_F N_c from matrix element colspin *= 4.; DVector save; for(unsigned int ix=0;ix<3;++ix) { me[ix] *= colspin; if(ix>0) save.push_back(me[ix]); } meInfo(save); output = me[0]/norm(FFGvertex_->norm()); } return output; } InvEnergy2 MEPP2GammaGammaPowheg:: realGammaGammagME(const cPDVector & particles, const vector<Lorentz5Momentum> & momenta, DipoleType dipole, RadiationType rad, bool ) const { // matrix element double sum = realME(particles,momenta); // loop over the QCD and QCD dipoles InvEnergy2 dipoles[2]; pair<double,double> supress[2]; // compute the two dipole terms unsigned int iemit = 4, ihard = 3; double x = (momenta[0]*momenta[1]-momenta[iemit]*momenta[1]- momenta[iemit]*momenta[0])/(momenta[0]*momenta[1]); Lorentz5Momentum Kt = momenta[0]+momenta[1]-momenta[iemit]; vector<Lorentz5Momentum> pa(4),pb(4); // momenta for q -> q g/gamma emission pa[0] = x*momenta[0]; pa[1] = momenta[1]; Lorentz5Momentum K = pa[0]+pa[1]; Lorentz5Momentum Ksum = K+Kt; Energy2 K2 = K.m2(); Energy2 Ksum2 = Ksum.m2(); pa[2] = momenta[2]-2.*Ksum*(Ksum*momenta[2])/Ksum2+2*K*(Kt*momenta[2])/K2; pa[2].setMass(momenta[2].mass()); pa[3] = momenta[ihard] -2.*Ksum*(Ksum*momenta[ihard])/Ksum2+2*K*(Kt*momenta[ihard])/K2; pa[3].setMass(ZERO); cPDVector part(particles.begin(),--particles.end()); part[3] = particles[ihard]; // first leading-order matrix element double lo1 = loGammaGammaME(part,pa); // first dipole dipoles[0] = 1./(momenta[0]*momenta[iemit])/x*(2./(1.-x)-(1.+x))*lo1; supress[0] = supressionFunction(momenta[iemit].perp(),pa[3].perp()); // momenta for qbar -> qbar g/gamma emission pb[0] = momenta[0]; pb[1] = x*momenta[1]; K = pb[0]+pb[1]; Ksum = K+Kt; K2 = K.m2(); Ksum2 = Ksum.m2(); pb[2] = momenta[2]-2.*Ksum*(Ksum*momenta[2])/Ksum2+2*K*(Kt*momenta[2])/K2; pb[2].setMass(momenta[2].mass()); pb[3] = momenta[ihard] -2.*Ksum*(Ksum*momenta[ihard])/Ksum2+2*K*(Kt*momenta[ihard])/K2; pb[3].setMass(ZERO); // second LO matrix element double lo2 = loGammaGammaME(part,pb); // second dipole dipoles[1] = 1./(momenta[1]*momenta[iemit])/x*(2./(1.-x)-(1.+x))*lo2; supress[1] = supressionFunction(momenta[iemit].perp(),pb[3].perp()); for(unsigned int ix=0;ix<2;++ix) dipoles[ix] *= 4./3.; // denominator for the matrix element InvEnergy2 denom = abs(dipoles[0]) + abs(dipoles[1]); // contribution if( denom==ZERO || dipoles[(dipole-1)/2]==ZERO ) return ZERO; sum *= abs(dipoles[(dipole-1)/2])/denom; // final coupling factors InvEnergy2 output; if(rad==Subtraction) { output = alphaS_*alphaEM_* (sum*UnitRemoval::InvE2*supress[(dipole-1)/2].first - dipoles[(dipole-1)/2]); } else { output = alphaS_*alphaEM_*sum*UnitRemoval::InvE2; if(rad==Hard) output *=supress[(dipole-1)/2].second; else if(rad==Shower) output *=supress[(dipole-1)/2].first ; } return output; } InvEnergy2 MEPP2GammaGammaPowheg::realGammaGammaqME(const cPDVector & particles, const vector<Lorentz5Momentum> & momenta, DipoleType dipole, RadiationType rad, bool ) const { double sum = realME(particles,momenta); // initial-state QCD dipole double x = (momenta[0]*momenta[1]-momenta[4]*momenta[1]- momenta[4]*momenta[0])/(momenta[0]*momenta[1]); Lorentz5Momentum Kt = momenta[0]+momenta[1]-momenta[4]; vector<Lorentz5Momentum> pa(4); pa[0] = momenta[0]; pa[1] = x*momenta[1]; Lorentz5Momentum K = pa[0]+pa[1]; Lorentz5Momentum Ksum = K+Kt; Energy2 K2 = K.m2(); Energy2 Ksum2 = Ksum.m2(); pa[2] = momenta[2]-2.*Ksum*(Ksum*momenta[2])/Ksum2+2*K*(Kt*momenta[2])/K2; pa[2].setMass(momenta[2].mass()); pa[3] = momenta[3] -2.*Ksum*(Ksum*momenta[3])/Ksum2+2*K*(Kt*momenta[3])/K2; pa[3].setMass(ZERO); cPDVector part(particles.begin(),--particles.end()); part[1] = particles[4]->CC(); double lo1 = loGammaGammaME(part,pa); InvEnergy2 D1 = 0.5/(momenta[1]*momenta[4])/x*(1.-2.*x*(1.-x))*lo1; // initial-final QED dipole vector<Lorentz5Momentum> pb(4); x = 1.-(momenta[3]*momenta[4])/(momenta[4]*momenta[0]+momenta[0]*momenta[3]); pb[3] = momenta[4]+momenta[3]-(1.-x)*momenta[0]; pb[0] = x*momenta[0]; pb[1] = momenta[1]; pb[2] = momenta[2]; double z = momenta[0]*momenta[3]/(momenta[0]*momenta[3]+momenta[0]*momenta[4]); part[1] = particles[1]; part[3] = particles[4]; double lo2 = loGammaqME(part,pb); Energy pT = sqrt(-(pb[0]-pb[3]).m2()*(1.-x)*(1.-z)*z/x); InvEnergy2 DF = 1./(momenta[4]*momenta[3])/x*(1./(1.-x+z)-2.+z)*lo2; InvEnergy2 DI = 1./(momenta[0]*momenta[3])/x*(1./(1.-x+z)-1.-x)*lo2; DI *= sqr(double(particles[0]->iCharge())/3.); DF *= sqr(double(particles[0]->iCharge())/3.); InvEnergy2 denom = abs(D1)+abs(DI)+abs(DF); pair<double,double> supress; InvEnergy2 term; if ( dipole == IFQED1 ) { term = DI; supress = supressionFunction(pT,pb[3].perp()); } else if( dipole == FIQED1 ) { term = DF; supress = supressionFunction(pT,pb[3].perp()); } else { term = D1; supress = supressionFunction(momenta[4].perp(),pa[3].perp()); } if( denom==ZERO || term == ZERO ) return ZERO; sum *= abs(term)/denom; // final coupling factors InvEnergy2 output; if(rad==Subtraction) { output = alphaS_*alphaEM_* (sum*UnitRemoval::InvE2*supress.first - term); } else { output = alphaS_*alphaEM_*sum*UnitRemoval::InvE2; if(rad==Hard) output *= supress.second; else if(rad==Shower) output *= supress.first ; } // final coupling factors return output; } InvEnergy2 MEPP2GammaGammaPowheg:: realGammaGammaqbarME(const cPDVector & particles, const vector<Lorentz5Momentum> & momenta, DipoleType dipole, RadiationType rad, bool) const { double sum = realME(particles,momenta); // initial-state QCD dipole double x = (momenta[0]*momenta[1]-momenta[4]*momenta[1]-momenta[4]*momenta[0])/ (momenta[0]*momenta[1]); Lorentz5Momentum Kt = momenta[0]+momenta[1]-momenta[4]; vector<Lorentz5Momentum> pa(4); pa[0] = x*momenta[0]; pa[1] = momenta[1]; Lorentz5Momentum K = pa[0]+pa[1]; Lorentz5Momentum Ksum = K+Kt; Energy2 K2 = K.m2(); Energy2 Ksum2 = Ksum.m2(); pa[2] = momenta[2]-2.*Ksum*(Ksum*momenta[2])/Ksum2+2*K*(Kt*momenta[2])/K2; pa[2].setMass(momenta[2].mass()); pa[3] = momenta[3] -2.*Ksum*(Ksum*momenta[3])/Ksum2+2*K*(Kt*momenta[3])/K2; pa[3].setMass(ZERO); cPDVector part(particles.begin(),--particles.end()); part[0] = particles[4]->CC(); double lo1 = loGammaGammaME(part,pa); InvEnergy2 D1 = 0.5/(momenta[0]*momenta[4])/x*(1.-2.*x*(1.-x))*lo1; // initial-final QED dipole vector<Lorentz5Momentum> pb(4); x = 1.-(momenta[3]*momenta[4])/(momenta[4]*momenta[1]+momenta[1]*momenta[3]); pb[3] = momenta[4]+momenta[3]-(1.-x)*momenta[1]; pb[0] = momenta[0]; pb[1] = x*momenta[1]; pb[2] = momenta[2]; double z = momenta[1]*momenta[3]/(momenta[1]*momenta[3]+momenta[1]*momenta[4]); part[0] = particles[0]; part[3] = particles[4]; double lo2 = loGammaqbarME(part,pb); Energy pT = sqrt(-(pb[1]-pb[3]).m2()*(1.-x)*(1.-z)*z/x); InvEnergy2 DF = 1./(momenta[4]*momenta[3])/x*(2./(1.-x+z)-2.+z)*lo2; InvEnergy2 DI = 1./(momenta[0]*momenta[3])/x*(2./(1.-x+z)-1.-x)*lo2; InvEnergy2 term; DI *= sqr(double(particles[1]->iCharge())/3.); DF *= sqr(double(particles[1]->iCharge())/3.); InvEnergy2 denom = abs(D1)+abs(DI)+abs(DF); pair<double,double> supress; if ( dipole == IFQED2 ) { term = DI; supress = supressionFunction(pT,pb[3].perp()); } else if( dipole == FIQED2 ) { term = DF; supress = supressionFunction(pT,pb[3].perp()); } else { term = D1; supress = supressionFunction(momenta[4].perp(),pa[3].perp()); } if( denom==ZERO || dipole==ZERO ) return ZERO; sum *= abs(term)/denom; // final coupling factors InvEnergy2 output; if(rad==Subtraction) { output = alphaS_*alphaEM_* (sum*UnitRemoval::InvE2*supress.first - term); } else { output = alphaS_*alphaEM_*sum*UnitRemoval::InvE2; if(rad==Hard) output *= supress.second; else if(rad==Shower) output *= supress.first ; } // final coupling factors return output; } double MEPP2GammaGammaPowheg:: realME(const cPDVector & particles, const vector<Lorentz5Momentum> & momenta) const { vector<SpinorWaveFunction> qin; vector<SpinorBarWaveFunction> qbarin; vector<VectorWaveFunction> wout,pout,gout; SpinorWaveFunction q_in; SpinorBarWaveFunction qbar_in; VectorWaveFunction g_out; VectorWaveFunction v_out (momenta[2],particles[2],outgoing); VectorWaveFunction p_out (momenta[3],particles[3],outgoing); // q qbar -> gamma gamma g if(particles[4]->id()==ParticleID::g) { q_in = SpinorWaveFunction (momenta[0],particles[0],incoming); qbar_in = SpinorBarWaveFunction (momenta[1],particles[1],incoming); g_out = VectorWaveFunction (momenta[4],particles[4],outgoing); } // q g -> gamma gamma q else if(particles[4]->id()>0) { q_in = SpinorWaveFunction (momenta[0],particles[0],incoming); qbar_in = SpinorBarWaveFunction (momenta[4],particles[4],outgoing); g_out = VectorWaveFunction (momenta[1],particles[1],incoming); } else if(particles[4]->id()<0) { q_in = SpinorWaveFunction (momenta[4],particles[4],outgoing); qbar_in = SpinorBarWaveFunction (momenta[1],particles[1],incoming); g_out = VectorWaveFunction (momenta[0],particles[0],incoming); } else assert(false); for(unsigned int ix=0;ix<2;++ix) { q_in.reset(ix); qin.push_back(q_in); qbar_in.reset(ix); qbarin.push_back(qbar_in); g_out.reset(2*ix); gout.push_back(g_out); p_out.reset(2*ix); pout.push_back(p_out); v_out.reset(2*ix); wout.push_back(v_out); } vector<Complex> diag(6 , 0.); Energy2 mu2 = scale(); double sum(0.); for(unsigned int ihel1=0;ihel1<2;++ihel1) { for(unsigned int ihel2=0;ihel2<2;++ihel2) { for(unsigned int whel=0;whel<2;++whel) { for(unsigned int phel=0;phel<2;++phel) { for(unsigned int ghel=0;ghel<2;++ghel) { // first diagram SpinorWaveFunction inters1 = FFPvertex_->evaluate(ZERO,5,qin[ihel1].particle()->CC(),qin[ihel1],pout[phel]); SpinorBarWaveFunction inters2 = FFPvertex_->evaluate(ZERO,5,qin[ihel1].particle(), qbarin[ihel2],wout[whel]); diag[0] = FFGvertex_->evaluate(mu2,inters1,inters2,gout[ghel]); // second diagram SpinorWaveFunction inters3 = FFGvertex_->evaluate(mu2,5,qin[ihel1].particle()->CC(),qin[ihel1],gout[ghel]); SpinorBarWaveFunction inters4 = FFPvertex_->evaluate(ZERO,5,qbarin[ihel2].particle()->CC(), qbarin[ihel2],pout[phel]); diag[1] = FFPvertex_->evaluate(ZERO,inters3,inters4,wout[whel]); // fourth diagram diag[2] = FFPvertex_->evaluate(ZERO,inters3,inters2,pout[phel]); // fifth diagram SpinorBarWaveFunction inters5 = FFGvertex_->evaluate(mu2,5,qbarin[ihel2].particle()->CC(), qbarin[ihel2],gout[ghel]); diag[3] = FFPvertex_->evaluate(ZERO,inters1,inters5,wout[whel]); // sixth diagram SpinorWaveFunction inters6 = FFPvertex_->evaluate(ZERO,5,qbarin[ihel2].particle(), qin[ihel1],wout[whel]); diag[4] = FFGvertex_->evaluate(mu2,inters6,inters4,gout[ghel]); // eighth diagram diag[5] = FFPvertex_->evaluate(ZERO,inters6,inters5,pout[phel]); // sum Complex dsum = std::accumulate(diag.begin(),diag.end(),Complex(0.)); sum += norm(dsum); } } } } } // divide out the em and strong couplings sum /= norm(FFGvertex_->norm()*FFPvertex_->norm()); // final spin and colour factors spin = 1/4 colour = 4/9 if(particles[4]->id()==ParticleID::g) sum /= 9.; // final spin and colour factors spin = 1/4 colour = 4/(3*8) else sum /= 24.; // finally identical particle factor return 0.5*sum; } double MEPP2GammaGammaPowheg::subtractedVirtual() const { double v = 1+tHat()/sHat(); double born = (1-v)/v+v/(1-v); double finite_term = born* (2./3.*sqr(Constants::pi)-3.+sqr(log(v))+sqr(log(1-v))+3.*log(1-v))+ 2.+2.*log(v)+2.*log(1-v)+3.*(1-v)/v*(log(v)-log(1-v))+ (2.+v/(1-v))*sqr(log(v))+(2.+(1-v)/v)*sqr(log(1-v)); double virt = ((6.-(2./3.)*sqr(Constants::pi))* born-2.+finite_term); return virt/born; } double MEPP2GammaGammaPowheg::subtractedReal(pair<double,double> x, double z, double zJac, double oldqPDF, double newqPDF, double newgPDF,bool order) const { double vt = vTilde_*(1.-z); double vJac = 1.-z; Energy pT = sqrt(sHat()*vt*(1.-vt-z)/z); // rapidities double rapidity; if(order) { rapidity = -log(x.second*sqrt(lastS())/pT*vt); } else { rapidity = log(x.first *sqrt(lastS())/pT*vt); } // CMS system Energy rs=sqrt(lastS()); Lorentz5Momentum pcmf = Lorentz5Momentum(ZERO,ZERO,0.5*rs*(x.first-x.second), 0.5*rs*(x.first+x.second)); pcmf.rescaleMass(); Boost blab(pcmf.boostVector()); // emission from the quark radiation vector<Lorentz5Momentum> pnew(5); if(order) { pnew [0] = Lorentz5Momentum(ZERO,ZERO,0.5*rs*x.first/z, 0.5*rs*x.first/z,ZERO); pnew [1] = Lorentz5Momentum(ZERO,ZERO,-0.5*rs*x.second, 0.5*rs*x.second,ZERO) ; } else { pnew[0] = Lorentz5Momentum(ZERO,ZERO,0.5*rs*x.first, 0.5*rs*x.first,ZERO); pnew[1] = Lorentz5Momentum(ZERO,ZERO,-0.5*rs*x.second/z, 0.5*rs*x.second/z,ZERO) ; } pnew [2] = meMomenta()[2]; pnew [3] = meMomenta()[3]; pnew [4] = Lorentz5Momentum(pT*cos(phi_),pT*sin(phi_), pT*sinh(rapidity), pT*cosh(rapidity), ZERO); Lorentz5Momentum K = pnew [0]+pnew [1]-pnew [4]; Lorentz5Momentum Kt = pcmf; Lorentz5Momentum Ksum = K+Kt; Energy2 K2 = K.m2(); Energy2 Ksum2 = Ksum.m2(); for(unsigned int ix=2;ix<4;++ix) { pnew [ix].boost(blab); pnew [ix] = pnew [ix] - 2.*Ksum*(Ksum*pnew [ix])/Ksum2 +2*K*(Kt*pnew [ix])/K2; } // phase-space prefactors double phase = zJac*vJac/z; // real emission q qbar vector<double> output(4,0.); double realQQ(0.),realGQ(0.); if(!(zTilde_<1e-7 || vt<1e-7 || 1.-z-vt < 1e-7 )) { cPDVector particles(mePartonData()); particles.push_back(gluon_); // calculate the full 2->3 matrix element realQQ = sHat()*phase*newqPDF/oldqPDF* realGammaGammagME(particles,pnew,order ? IIQCD1 : IIQCD2,Subtraction,false); if(order) { particles[0] = gluon_; particles[4] = mePartonData()[0]->CC(); realGQ = sHat()*phase*newgPDF/oldqPDF* realGammaGammaqbarME(particles,pnew,IIQCD2,Subtraction,false); } else { particles[1] = gluon_; particles[4] = mePartonData()[1]->CC(); realGQ = sHat()*phase*newgPDF/oldqPDF* realGammaGammaqME (particles,pnew,IIQCD1,Subtraction,false); } } // return the answer return realQQ+realGQ; } double MEPP2GammaGammaPowheg::collinearQuark(double x, Energy2 mu2, double jac, double z, double oldPDF, double newPDF) const { if(1.-z < 1.e-8) return 0.; return CFfact_*( // this bit is multiplied by LO PDF sqr(Constants::pi)/3.-5.+2.*sqr(log(1.-x )) +(1.5+2.*log(1.-x ))*log(sHat()/mu2) // NLO PDF bit +jac /z * newPDF /oldPDF * (1.-z -(1.+z )*log(sqr(1.-z )/z ) -(1.+z )*log(sHat()/mu2)-2.*log(z )/(1.-z )) // + function bit +jac /z *(newPDF /oldPDF -z )* 2./(1.-z )*log(sHat()*sqr(1.-z )/mu2)); } double MEPP2GammaGammaPowheg::collinearGluon(Energy2 mu2, double jac, double z, double oldPDF, double newPDF) const { if(1.-z < 1.e-8) return 0.; return TRfact_*jac/z*newPDF/oldPDF* ((sqr(z)+sqr(1.-z))*log(sqr(1.-z)*sHat()/z/mu2) +2.*z*(1.-z)); } void MEPP2GammaGammaPowheg::doinit() { HwMEBase::doinit(); vector<unsigned int> mopt(2,1); massOption(mopt); // get the vertices we need // get a pointer to the standard model object in the run static const tcHwSMPtr hwsm = dynamic_ptr_cast<tcHwSMPtr>(standardModel()); if (!hwsm) throw InitException() << "hwsm pointer is null in" << " MEPP2GammaGamma::doinit()" << Exception::abortnow; // get pointers to all required Vertex objects FFPvertex_ = hwsm->vertexFFP(); FFGvertex_ = hwsm->vertexFFG(); gluon_ = getParticleData(ParticleID::g); // sampling factors prefactor_.push_back(preQCDqqbarq_); prefactor_.push_back(preQCDqqbarqbar_); prefactor_.push_back(preQCDqg_); prefactor_.push_back(preQCDgqbar_); prefactor_.push_back(preQEDqqbarq_); prefactor_.push_back(preQEDqqbarqbar_); prefactor_.push_back(preQEDqgq_); prefactor_.push_back(preQEDgqbarqbar_); } RealEmissionProcessPtr MEPP2GammaGammaPowheg:: generateHardest(RealEmissionProcessPtr born, ShowerInteraction inter) { beams_.clear(); partons_.clear(); bool QCDAllowed = inter !=ShowerInteraction::QED; bool QEDAllowed = inter !=ShowerInteraction::QCD; // find the incoming particles // and get the particles to be showered ParticleVector incoming,particlesToShower; pair<double,double> x; for(unsigned int ix=0;ix<born->bornIncoming().size();++ix) { incoming.push_back( born->bornIncoming()[ix] ); beams_.push_back(dynamic_ptr_cast<tcBeamPtr>(born->hadrons()[ix]->dataPtr())); partons_.push_back( born->bornIncoming()[ix]->dataPtr() ); particlesToShower.push_back( born->bornIncoming()[ix] ); if(ix==0) x.first = incoming.back()->momentum().rho()/born->hadrons()[ix]->momentum().rho(); else x.second = incoming.back()->momentum().rho()/born->hadrons()[ix]->momentum().rho(); } // find the parton which should be first if( ( particlesToShower[1]->id() > 0 && particlesToShower[0]->id() < 0 ) || ( particlesToShower[0]->id() == ParticleID::g && particlesToShower[1]->id() < 6 && particlesToShower[1]->id() > 0 ) ) { swap(particlesToShower[0],particlesToShower[1]); swap(partons_[0],partons_[1]); swap(beams_ [0],beams_ [1]); swap(x.first ,x.second ); } // check that quark is along +ve z direction quarkplus_ = particlesToShower[0]->momentum().z() > ZERO; // outgoing partons for(unsigned int ix=0;ix<born->bornOutgoing().size();++ix) { particlesToShower.push_back( born->bornOutgoing()[ix] ); } if(particlesToShower.size()!=4) return RealEmissionProcessPtr(); if(particlesToShower[2]->id()!=ParticleID::gamma) swap(particlesToShower[2],particlesToShower[3]); if(particlesToShower[3]->id()==ParticleID::gamma) { if(QCDAllowed) return hardQCDEmission(born,particlesToShower,x); } else { if(QEDAllowed) return hardQEDEmission(born,particlesToShower,x); } return born; } RealEmissionProcessPtr MEPP2GammaGammaPowheg:: hardQCDEmission(RealEmissionProcessPtr born, ParticleVector particlesToShower, pair<double,double> x) { Energy rootS = sqrt(lastS()); // limits on the rapidity of the jet double minyj = -8.0,maxyj = 8.0; // generate the hard emission vector<Energy> pT; Energy pTmax(-GeV); cPDVector selectedParticles; vector<Lorentz5Momentum> selectedMomenta; int iemit(-1); for(unsigned int ix=0;ix<4;++ix) { pT.push_back(0.5*generator()->maximumCMEnergy()); double a = alphaQCD_->overestimateValue()/Constants::twopi* prefactor_[ix]*(maxyj-minyj); cPDVector particles; for(unsigned int iy=0;iy<particlesToShower.size();++iy) particles.push_back(particlesToShower[iy]->dataPtr()); if(ix<2) particles.push_back(gluon_); else if(ix==2) { particles.push_back(particles[0]->CC()); particles[0] = gluon_; } else { particles.push_back(particles[1]->CC()); particles[1] = gluon_; } vector<Lorentz5Momentum> momenta(5); do { pT[ix] *= pow(UseRandom::rnd(),1./a); double y = UseRandom::rnd()*(maxyj-minyj)+ minyj; double vt,z; if(ix%2==0) { vt = pT[ix]*exp(-y)/rootS/x.second; z = (1.-pT[ix]*exp(-y)/rootS/x.second)/(1.+pT[ix]*exp( y)/rootS/x.first ); if(z>1.||z<x.first) continue; } else { vt = pT[ix]*exp( y)/rootS/x.first ; z = (1.-pT[ix]*exp( y)/rootS/x.first )/(1.+pT[ix]*exp(-y)/rootS/x.second ); if(z>1.||z<x.second) continue; } if(vt>1.-z || vt<0.) continue; if(ix%2==0) { momenta[0] = particlesToShower[0]->momentum()/z; momenta[1] = particlesToShower[1]->momentum(); } else { momenta[0] = particlesToShower[0]->momentum(); momenta[1] = particlesToShower[1]->momentum()/z; } double phi = Constants::twopi*UseRandom::rnd(); momenta[2] = particlesToShower[2]->momentum(); momenta[3] = particlesToShower[3]->momentum(); if(!quarkplus_) y *= -1.; momenta[4] = Lorentz5Momentum(pT[ix]*cos(phi),pT[ix]*sin(phi), pT[ix]*sinh(y),pT[ix]*cosh(y), ZERO); Lorentz5Momentum K = momenta[0] + momenta[1] - momenta[4]; Lorentz5Momentum Kt = momenta[2]+momenta[3]; Lorentz5Momentum Ksum = K+Kt; Energy2 K2 = K.m2(), Ksum2 = Ksum.m2(); for(unsigned int iy=2;iy<4;++iy) { momenta [iy] = momenta [iy] - 2.*Ksum*(Ksum*momenta [iy])/Ksum2 +2*K*(Kt*momenta [iy])/K2; } // matrix element piece double wgt = alphaQCD_->ratio(sqr(pT[ix]))*z/(1.-vt)/prefactor_[ix]/loME_; if(ix==0) wgt *= sqr(pT[ix])*realGammaGammagME(particles,momenta,IIQCD1,Shower,false); else if(ix==1) wgt *= sqr(pT[ix])*realGammaGammagME(particles,momenta,IIQCD2,Shower,false); else if(ix==2) wgt *= sqr(pT[ix])*realGammaGammaqbarME(particles,momenta,IIQCD1,Shower,false); else if(ix==3) wgt *= sqr(pT[ix])*realGammaGammaqME(particles,momenta,IIQCD2,Shower,false); wgt *= 4.*Constants::pi/alphaS_; // pdf piece double pdf[2]; if(ix%2==0) { pdf[0] = beams_[0]->pdf()->xfx(beams_[0],partons_ [0], scale(), x.first ) /x.first; pdf[1] = beams_[0]->pdf()->xfx(beams_[0],particles[0], scale()+sqr(pT[ix]),x.first /z)*z/x.first; } else { pdf[0] = beams_[1]->pdf()->xfx(beams_[1],partons_ [1], scale() ,x.second ) /x.second; pdf[1] = beams_[1]->pdf()->xfx(beams_[1],particles[1], scale()+sqr(pT[ix]),x.second/z)*z/x.second; } if(pdf[0]<=0.||pdf[1]<=0.) continue; wgt *= pdf[1]/pdf[0]; if(wgt>1.) generator()->log() << "Weight greater than one in " << "MEPP2GammaGammaPowheg::hardQCDEmission() " << "for channel " << ix << " Weight = " << wgt << "\n"; if(UseRandom::rnd()<wgt) break; } while(pT[ix]>minpT_); if(pT[ix]>minpT_ && pT[ix]>pTmax) { pTmax = pT[ix]; selectedParticles = particles; selectedMomenta = momenta; iemit=ix; } } // if no emission if(pTmax<ZERO) { born->pT()[ShowerInteraction::QCD] = minpT_; return born; } // construct the HardTree object needed to perform the showers // create the partons ParticleVector newparticles; newparticles.push_back(selectedParticles[0]->produceParticle(selectedMomenta[0])); newparticles.push_back(selectedParticles[1]->produceParticle(selectedMomenta[1])); for(unsigned int ix=2;ix<particlesToShower.size();++ix) { newparticles.push_back(particlesToShower[ix]->dataPtr()-> produceParticle(selectedMomenta[ix])); } newparticles.push_back(selectedParticles[4]->produceParticle(selectedMomenta[4])); // identify the type of process // gluon emission if(newparticles.back()->id()==ParticleID::g) { newparticles[4]->incomingColour(newparticles[0]); newparticles[4]->incomingColour(newparticles[1],true); } // quark else if(newparticles.back()->id()>0) { iemit=1; newparticles[4]->incomingColour(newparticles[1]); newparticles[1]-> colourConnect(newparticles[0]); } // antiquark else { iemit=0; newparticles[4]->incomingColour(newparticles[0],true); newparticles[1]-> colourConnect(newparticles[0]); } // add incoming int ispect = iemit==0 ? 1 : 0; if(particlesToShower[0]==born->bornIncoming()[0]) { born->incoming().push_back(newparticles[0]); born->incoming().push_back(newparticles[1]); } else { born->incoming().push_back(newparticles[1]); born->incoming().push_back(newparticles[0]); swap(iemit,ispect); } // add the outgoing for(unsigned int ix=2;ix<newparticles.size();++ix) born->outgoing().push_back(newparticles[ix]); // emitter spectator etc born->emitter (iemit ); born->spectator(ispect); born->emitted(4); // x values pair<double,double> xnew; for(unsigned int ix=0;ix<2;++ix) { double x = born->incoming()[ix]->momentum().rho()/born->hadrons()[ix]->momentum().rho(); if(ix==0) xnew.first = x; else xnew.second = x; } born->x(xnew); // max pT born->pT()[ShowerInteraction::QCD] = pTmax; born->interaction(ShowerInteraction::QCD); // return the process return born; } RealEmissionProcessPtr MEPP2GammaGammaPowheg:: hardQEDEmission(RealEmissionProcessPtr born, ParticleVector particlesToShower, pair<double,double> x) { // return if not emission from quark if(particlesToShower[0]->id()!=ParticleID::g && particlesToShower[1]->id()!=ParticleID::g ) return RealEmissionProcessPtr(); // generate the hard emission vector<Energy> pT; Energy pTmax(-GeV); cPDVector selectedParticles; vector<Lorentz5Momentum> selectedMomenta; int iemit(-1); pair<double,double> mewgt(make_pair(0.,0.)); for(unsigned int ix=0;ix<particlesToShower.size();++ix) { selectedParticles.push_back(particlesToShower[ix]->dataPtr()); selectedMomenta.push_back(particlesToShower[ix]->momentum()); } selectedParticles.push_back(getParticleData(ParticleID::gamma)); swap(selectedParticles[3],selectedParticles[4]); selectedMomenta.push_back(Lorentz5Momentum()); swap(selectedMomenta[3],selectedMomenta[4]); Lorentz5Momentum pin,pout; double xB; unsigned int iloc; if(particlesToShower[0]->dataPtr()->charged()) { pin = particlesToShower[0]->momentum(); xB = x.first; iloc = 6; } else { pin = particlesToShower[1]->momentum(); xB = x.second; iloc = 7; } pout = particlesToShower[3]->momentum(); Lorentz5Momentum q = pout-pin; Axis axis(q.vect().unit()); LorentzRotation rot; double sinth(sqrt(sqr(axis.x())+sqr(axis.y()))); rot = LorentzRotation(); if(axis.perp2()>1e-20) { rot.setRotate(-acos(axis.z()),Axis(-axis.y()/sinth,axis.x()/sinth,0.)); rot.rotateX(Constants::pi); } if(abs(1.-q.e()/q.vect().mag())>1e-6) rot.boostZ(q.e()/q.vect().mag()); Lorentz5Momentum ptemp = rot*pin; if(ptemp.perp2()/GeV2>1e-20) { Boost trans = -1./ptemp.e()*ptemp.vect(); trans.setZ(0.); rot.boost(trans); } rot.invert(); Energy Q = sqrt(-q.m2()); double xT = sqrt((1.-xB)/xB); double xTMin = 2.*minpT_/Q; double wgt(0.); double a = alphaQED_->overestimateValue()*prefactor_[iloc]/Constants::twopi; Lorentz5Momentum p1,p2,p3; do { wgt = 0.; // intergration variables dxT/xT^3 xT *= 1./sqrt(1.-2.*log(UseRandom::rnd())/a*sqr(xT)); // dz double zp = UseRandom::rnd(); double xp = 1./(1.+0.25*sqr(xT)/zp/(1.-zp)); if(xT<xTMin) break; // check allowed if(xp<xB||xp>1.) continue; // phase-space piece of the weight wgt = 4.*sqr(1.-xp)*(1.-zp)*zp/prefactor_[iloc]/loME_; // coupling Energy2 pT2 = 0.25*sqr(Q*xT); wgt *= alphaQED_->ratio(pT2); // matrix element wgt *= 4.*Constants::pi/alphaEM_; // PDF double pdf[2]; if(iloc==6) { pdf[0] = beams_[0]->pdf()-> xfx(beams_[0],partons_[0],scale() ,x.first ); pdf[1] = beams_[0]->pdf()-> xfx(beams_[0],partons_[0],scale()+pT2,x.first /xp); } else { pdf[0] = beams_[1]->pdf()-> xfx(beams_[1],partons_[1],scale() ,x.second ); pdf[1] = beams_[1]->pdf()-> xfx(beams_[1],partons_[1],scale()+pT2,x.second/xp); } if(pdf[0]<=0.||pdf[1]<=0.) { wgt = 0.; continue; } wgt *= pdf[1]/pdf[0]; // matrix element piece double phi = Constants::twopi*UseRandom::rnd(); double x2 = 1.-(1.-zp)/xp; double x3 = 2.-1./xp-x2; p1=Lorentz5Momentum(ZERO,ZERO,0.5*Q/xp,0.5*Q/xp,ZERO); p2=Lorentz5Momentum( 0.5*Q*xT*cos(phi), 0.5*Q*xT*sin(phi), -0.5*Q*x2,0.5*Q*sqrt(sqr(xT)+sqr(x2))); p3=Lorentz5Momentum(-0.5*Q*xT*cos(phi),-0.5*Q*xT*sin(phi), -0.5*Q*x3,0.5*Q*sqrt(sqr(xT)+sqr(x3))); selectedMomenta[iloc-6] = rot*p1; selectedMomenta[3] = rot*p3; selectedMomenta[4] = rot*p2; if(iloc==6) { mewgt.first = sqr(Q)*realGammaGammaqME(selectedParticles,selectedMomenta,IFQED1,Shower,false); mewgt.second = sqr(Q)*realGammaGammaqME(selectedParticles,selectedMomenta,FIQED1,Shower,false); wgt *= mewgt.first+mewgt.second; } else { mewgt.first = sqr(Q)*realGammaGammaqbarME(selectedParticles,selectedMomenta,IFQED2,Shower,false); mewgt.second = sqr(Q)*realGammaGammaqbarME(selectedParticles,selectedMomenta,FIQED2,Shower,false); wgt *= mewgt.first+mewgt.second; } if(wgt>1.) generator()->log() << "Weight greater than one in " << "MEPP2GammaGammaPowheg::hardQEDEmission() " << "for IF channel " << " Weight = " << wgt << "\n"; } while(xT>xTMin&&UseRandom::rnd()>wgt); // if no emission if(xT<xTMin) { born->pT()[ShowerInteraction::QED] = minpT_; return born; } pTmax = 0.5*xT*Q; iemit = mewgt.first>mewgt.second ? 2 : 3; // construct the object needed to perform the showers // create the partons ParticleVector newparticles; newparticles.push_back(selectedParticles[0]->produceParticle(selectedMomenta[0])); newparticles.push_back(selectedParticles[1]->produceParticle(selectedMomenta[1])); for(unsigned int ix=2;ix<particlesToShower.size();++ix) { newparticles.push_back(particlesToShower[ix]-> dataPtr()->produceParticle(selectedMomenta[ix==2 ? 2 : 4 ])); } newparticles.push_back(selectedParticles[3]->produceParticle(selectedMomenta[3])); // make the colour connections bool col = newparticles[3]->id()<0; if(particlesToShower[0]->dataPtr()->charged()) { newparticles[3]->incomingColour(newparticles[1],col); newparticles[1]->colourConnect (newparticles[0],col); } else { newparticles[3]->incomingColour(newparticles[0],col); newparticles[0]->colourConnect (newparticles[1],col); } bool FSR = iemit==3; // add incoming particles if(particlesToShower[0]==born->bornIncoming()[0]) { born->incoming().push_back(newparticles[0]); born->incoming().push_back(newparticles[1]); } else { born->incoming().push_back(newparticles[1]); born->incoming().push_back(newparticles[0]); } // IS radiatng particle unsigned int iemitter = born->incoming()[0]->dataPtr()->charged() ? 0 : 1; // add outgoing particles if(particlesToShower[2]==born->bornOutgoing()[0]) { born->outgoing().push_back(newparticles[2]); born->outgoing().push_back(newparticles[3]); } else { born->outgoing().push_back(newparticles[3]); born->outgoing().push_back(newparticles[2]); } born->outgoing().push_back(newparticles[4]); // outgoing radiating particle unsigned int ispectator = born->outgoing()[0]->dataPtr()->charged() ? 2 : 3; // get emitter and spectator right if(FSR) swap(iemitter,ispectator); born->emitter (iemitter ); born->spectator(ispectator); born->emitted(4); // x values pair<double,double> xnew; for(unsigned int ix=0;ix<2;++ix) { double x = born->incoming()[ix]->momentum().rho()/born->hadrons()[ix]->momentum().rho(); if(ix==0) xnew.first = x; else xnew.second = x; } born->x(xnew); // max pT born->pT()[ShowerInteraction::QED] = pTmax; // return the process born->interaction(ShowerInteraction::QED); return born; }
hep-mirrors/herwig
MatrixElement/Powheg/MEPP2GammaGammaPowheg.cc
C++
gpl-3.0
72,054
#pragma once #ifndef LIBBMS_BMS_HPP_INCLUDED #define LIBBMS_BMS_HPP_INCLUDED #include "BmsBeatmap.hpp" #include "BmsChannelId.hpp" #include "BmsDataUnit.hpp" #include "BmsDataUnitId.hpp" #include "BmsDecimalDataUnit.hpp" #include "BmsException.hpp" #include "BmsIntegerListDataUnit.hpp" #include "BmsReferenceId.hpp" #include "BmsReferenceListDataUnit.hpp" #include "BmsSectionId.hpp" #endif // !LIBBMS_BMS_HPP_INCLUDED
MsrLab-org/libbms
Sources/Bms.hpp
C++
gpl-3.0
422
#-*- coding:utf-8 -*- # # nngt_graph.py # # This file is part of the NNGT project to generate and analyze # neuronal networks and their activity. # Copyright (C) 2015-2019 Tanguy Fardet # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Default (limited) graph if none of the graph libraries are available """ from collections import OrderedDict from copy import deepcopy import logging import numpy as np from scipy.sparse import coo_matrix, lil_matrix import nngt from nngt.lib import InvalidArgument, nonstring_container, is_integer from nngt.lib.connect_tools import (_cleanup_edges, _set_dist_new_edges, _set_default_edge_attributes) from nngt.lib.graph_helpers import _get_edge_attr, _get_dtype, _post_del_update from nngt.lib.converters import _np_dtype, _to_np_array from nngt.lib.logger import _log_message from .graph_interface import GraphInterface, BaseProperty logger = logging.getLogger(__name__) # ---------- # # Properties # # ---------- # class _NProperty(BaseProperty): ''' Class for generic interactions with nodes properties (graph-tool) ''' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.prop = OrderedDict() def __getitem__(self, name): dtype = _np_dtype(super().__getitem__(name)) return _to_np_array(self.prop[name], dtype=dtype) def __setitem__(self, name, value): if name in self: size = self.parent().node_nb() if len(value) == size: self.prop[name] = list(value) else: raise ValueError("A list or a np.array with one entry per " "node in the graph is required") else: raise InvalidArgument("Attribute does not exist yet, use " "set_attribute to create it.") def new_attribute(self, name, value_type, values=None, val=None): dtype = object if val is None: if value_type == "int": val = int(0) dtype = int elif value_type == "double": val = np.NaN dtype = float elif value_type == "string": val = "" else: val = None value_type = "object" if values is None: values = _to_np_array( [deepcopy(val) for _ in range(self.parent().node_nb())], value_type) if len(values) != self.parent().node_nb(): raise ValueError("A list or a np.array with one entry per " "node in the graph is required") # store name and value type in the dict super().__setitem__(name, value_type) # store the real values in the attribute self.prop[name] = list(values) self._num_values_set[name] = len(values) def set_attribute(self, name, values, nodes=None): ''' Set the node attribute. Parameters ---------- name : str Name of the node attribute. values : array, size N Values that should be set. nodes : array-like, optional (default: all nodes) Nodes for which the value of the property should be set. If `nodes` is not None, it must be an array of size N. ''' num_nodes = self.parent().node_nb() num_n = len(nodes) if nodes is not None else num_nodes if num_n == num_nodes: self[name] = list(values) self._num_values_set[name] = num_nodes else: if num_n != len(values): raise ValueError("`nodes` and `values` must have the same " "size; got respectively " + str(num_n) + \ " and " + str(len(values)) + " entries.") if self._num_values_set[name] == num_nodes - num_n: self.prop[name].extend(values) else: for n, val in zip(nodes, values): self.prop[name][n] = val self._num_values_set[name] = num_nodes def remove(self, nodes): ''' Remove entries for a set of nodes ''' for key in self: for n in reversed(sorted(nodes)): self.prop[key].pop(n) self._num_values_set[key] -= len(nodes) class _EProperty(BaseProperty): ''' Class for generic interactions with nodes properties (graph-tool) ''' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.prop = OrderedDict() def __getitem__(self, name): ''' Return the attributes of an edge or a list of edges. ''' eprop = {} graph = self.parent() if isinstance(name, slice): for k in self.keys(): dtype = _np_dtype(super().__getitem__(k)) eprop[k] = _to_np_array(self.prop[k], dtype)[name] return eprop elif nonstring_container(name): if nonstring_container(name[0]): eids = [graph.edge_id(e) for e in name] for k in self.keys(): dtype = _np_dtype(super().__getitem__(k)) eprop[k] = _to_np_array(self.prop[k], dtype=dtype)[eids] else: eid = graph.edge_id(name) for k in self.keys(): eprop[k] = self.prop[k][eid] return eprop dtype = _np_dtype(super().__getitem__(name)) return _to_np_array(self.prop[name], dtype=dtype) def __setitem__(self, name, value): if name in self: size = self.parent().edge_nb() if len(value) == size: self.prop[name] = list(value) else: raise ValueError("A list or a np.array with one entry per " "edge in the graph is required") else: raise InvalidArgument("Attribute does not exist yet, use " "set_attribute to create it.") self._num_values_set[name] = len(value) def set_attribute(self, name, values, edges=None, last_edges=False): ''' Set the edge property. Parameters ---------- name : str Name of the edge property. values : array Values that should be set. edges : array-like, optional (default: None) Edges for which the value of the property should be set. If `edges` is not None, it must be an array of shape `(len(values), 2)`. ''' num_edges = self.parent().edge_nb() num_e = len(edges) if edges is not None else num_edges if num_e != len(values): raise ValueError("`edges` and `values` must have the same " "size; got respectively " + str(num_e) + \ " and " + str(len(values)) + " entries.") if edges is None: self[name] = list(values) else: if last_edges: self.prop[name].extend(values) else: eid = self.parent().edge_id prop = self.prop[name] # using list comprehension for fast loop [_set_prop(prop, eid(e), val) for e, val in zip(edges, values)] if num_e: self._num_values_set[name] = num_edges def new_attribute(self, name, value_type, values=None, val=None): num_edges = self.parent().edge_nb() if values is None and val is None: self._num_values_set[name] = num_edges if val is None: if value_type == "int": val = int(0) elif value_type == "double": val = np.NaN elif value_type == "string": val = "" else: val = None if values is None: values = _to_np_array( [deepcopy(val) for _ in range(num_edges)], value_type) if len(values) != num_edges: self._num_values_set[name] = 0 raise ValueError("A list or a np.array with one entry per " "edge in the graph is required") # store name and value type in the dict super().__setitem__(name, value_type) # store the real values in the attribute self.prop[name] = list(values) self._num_values_set[name] = len(values) def edges_deleted(self, eids): ''' Remove the attributes of a set of edge ids ''' for key, val in self.prop.items(): self.prop[key] = [v for i, v in enumerate(val) if i not in eids] self._num_values_set[key] -= len(eids) # ----------------- # # NNGT backup graph # # ----------------- # class _NNGTGraphObject: ''' Minimal implementation of the GraphObject, which does not rely on any graph-library. ''' def __init__(self, nodes=0, weighted=True, directed=True): ''' Initialized independent graph ''' self._nodes = set(i for i in range(nodes)) self._out_deg = [0]*nodes self._in_deg = [0]*nodes if directed: # for directed networks, edges and unique are the same self._edges = self._unique = OrderedDict() assert self._edges is self._unique else: # for undirected networks self._edges = OrderedDict() self._unique = OrderedDict() self._directed = directed self._weighted = weighted def copy(self): ''' Returns a deep copy of the graph object ''' copy = _NNGTGraphObject(len(self._nodes), weighted=self._weighted, directed=self._directed) copy._nodes = self._nodes.copy() if self._directed: copy._unique = copy._edges = self._edges.copy() assert copy._unique is copy._edges else: copy._edges = self._edges.copy() copy._unique = self._unique.copy() copy._out_deg = self._out_deg.copy() copy._in_deg = self._in_deg.copy() return copy def is_directed(self): return self._directed @property def nodes(self): return list(self._nodes) class _NNGTGraph(GraphInterface): ''' NNGT wrapper class for _NNGTGraphObject ''' #------------------------------------------------------------------# # Constructor and instance properties def __init__(self, nodes=0, weighted=True, directed=True, copy_graph=None, **kwargs): ''' Initialized independent graph ''' self._nattr = _NProperty(self) self._eattr = _EProperty(self) self._max_eid = 0 # test if copying graph if copy_graph is not None: self._from_library_graph(copy_graph, copy=True) self._max_eid = copy_graph._max_eid else: self._graph = _NNGTGraphObject( nodes=nodes, weighted=weighted, directed=directed) #------------------------------------------------------------------# # Graph manipulation def edge_id(self, edge): ''' Return the ID a given edge or a list of edges in the graph. Raises an error if the edge is not in the graph or if one of the vertices in the edge is nonexistent. Parameters ---------- edge : 2-tuple or array of edges Edge descriptor (source, target). Returns ------- index : int or array of ints Index of the given `edge`. ''' g = self._graph if is_integer(edge[0]): return g._edges[tuple(edge)] elif nonstring_container(edge[0]): idx = [g._edges[tuple(e)] for e in edge] return idx else: raise AttributeError("`edge` must be either a 2-tuple of ints or " "an array of 2-tuples of ints.") def has_edge(self, edge): ''' Whether `edge` is present in the graph. .. versionadded:: 2.0 ''' e = tuple(edge) return e in self._graph._edges @property def edges_array(self): ''' Edges of the graph, sorted by order of creation, as an array of 2-tuple. ''' return np.asarray(list(self._graph._unique), dtype=int) def _get_edges(self, source_node=None, target_node=None): g = self._graph edges = None if source_node is not None: source_node = \ [source_node] if is_integer(source_node) else source_node if g.is_directed(): edges = [e for e in g._unique if e[0] in source_node] else: edges = set() for e in g._unique: if e[0] in source_node or e[1] in source_node: if e[::-1] not in edges: edges.add(e) edges = list(edges) return edges target_node = \ [target_node] if is_integer(target_node) else target_node if g.is_directed(): edges = [e for e in g._unique if e[1] in target_node] else: edges = set() for e in g._unique: if e[0] in target_node or e[1] in target_node: if e[::-1] not in edges: edges.add(e) edges = list(edges) return edges def is_connected(self): raise NotImplementedError("Not available with 'nngt' backend, please " "install a graph library (networkx, igraph, " "or graph-tool).") def new_node(self, n=1, neuron_type=1, attributes=None, value_types=None, positions=None, groups=None): ''' Adding a node to the graph, with optional properties. Parameters ---------- n : int, optional (default: 1) Number of nodes to add. neuron_type : int, optional (default: 1) Type of neuron (1 for excitatory, -1 for inhibitory) attributes : dict, optional (default: None) Dictionary containing the attributes of the nodes. value_types : dict, optional (default: None) Dict of the `attributes` types, necessary only if the `attributes` do not exist yet. positions : array of shape (n, 2), optional (default: None) Positions of the neurons. Valid only for :class:`~nngt.SpatialGraph` or :class:`~nngt.SpatialNetwork`. groups : str, int, or list, optional (default: None) :class:`~nngt.core.NeuralGroup` to which the neurons belong. Valid only for :class:`~nngt.Network` or :class:`~nngt.SpatialNetwork`. Returns ------- The node or a tuple of the nodes created. ''' nodes = [] g = self._graph if n == 1: nodes.append(len(g._nodes)) g._in_deg.append(0) g._out_deg.append(0) else: num_nodes = len(g._nodes) nodes.extend( [i for i in range(num_nodes, num_nodes + n)]) g._in_deg.extend([0 for _ in range(n)]) g._out_deg.extend([0 for _ in range(n)]) g._nodes.update(nodes) attributes = {} if attributes is None else deepcopy(attributes) if attributes: for k, v in attributes.items(): if k not in self._nattr: self._nattr.new_attribute(k, value_types[k], val=v) else: v = v if nonstring_container(v) else [v] self._nattr.set_attribute(k, v, nodes=nodes) # set default values for all attributes that were not set for k in self.node_attributes: if k not in attributes: dtype = self.get_attribute_type(k) if dtype == "double": values = [np.NaN for _ in nodes] self._nattr.set_attribute(k, values, nodes=nodes) elif dtype == "int": values = [0 for _ in nodes] self._nattr.set_attribute(k, values, nodes=nodes) elif dtype == "string": values = ["" for _ in nodes] self._nattr.set_attribute(k, values, nodes=nodes) else: values = [None for _ in nodes] self._nattr.set_attribute(k, values, nodes=nodes) if self.is_spatial(): old_pos = self._pos self._pos = np.full((self.node_nb(), 2), np.NaN, dtype=float) num_existing = len(old_pos) if old_pos is not None else 0 if num_existing != 0: self._pos[:num_existing, :] = old_pos if positions is not None: assert self.is_spatial(), \ "`positions` argument requires a SpatialGraph/SpatialNetwork." self._pos[nodes] = positions if groups is not None: assert self.is_network(), \ "`positions` argument requires a Network/SpatialNetwork." if nonstring_container(groups): assert len(groups) == n, "One group per neuron required." for g, node in zip(groups, nodes): self.population.add_to_group(g, node) else: self.population.add_to_group(groups, nodes) if n == 1: return nodes[0] return nodes def delete_nodes(self, nodes): ''' Remove nodes (and associated edges) from the graph. ''' g = self._graph old_nodes = range(self.node_nb()) # update node set and degrees if nonstring_container(nodes): nodes = set(nodes) g._nodes = g._nodes.difference(nodes) else: g._nodes.remove(nodes) g._out_deg.pop(nodes) g._in_deg.pop(nodes) nodes = {nodes} # remove node attributes self._nattr.remove(nodes) # map from old nodes to new node ids idx = 0 remapping = {} for n in old_nodes: if n not in nodes: remapping[n] = idx idx += 1 # remove edges and remap edges remove_eids = set() new_edges = OrderedDict() new_eid = 0 for e, eid in g._unique.items(): if e[0] in nodes or e[1] in nodes: remove_eids.add(eid) else: new_edges[(remapping[e[0]], remapping[e[1]])] = new_eid new_eid += 1 g._unique = new_edges if not g._directed: g._edges = new_edges.copy() g._edges.update({e[::-1]: i for e, i in new_edges.items()}) else: g._edges = g._unique # tell edge attributes self._eattr.edges_deleted(remove_eids) g._nodes = set(range(len(g._nodes))) # check spatial and structure properties _post_del_update(self, nodes, remapping=remapping) def new_edge(self, source, target, attributes=None, ignore=False, self_loop=False): ''' Adding a connection to the graph, with optional properties. .. versionchanged :: 2.0 Added `self_loop` argument to enable adding self-loops. Parameters ---------- source : :class:`int/node` Source node. target : :class:`int/node` Target node. attributes : :class:`dict`, optional (default: ``{}``) Dictionary containing optional edge properties. If the graph is weighted, defaults to ``{"weight": 1.}``, the unit weight for the connection (synaptic strength in NEST). ignore : bool, optional (default: False) If set to True, ignore attempts to add an existing edge and accept self-loops; otherwise an error is raised. self_loop : bool, optional (default: False) Whether to allow self-loops or not. Returns ------- The new connection or None if nothing was added. ''' g = self._graph attributes = {} if attributes is None else deepcopy(attributes) # set default values for attributes that were not passed _set_default_edge_attributes(self, attributes, num_edges=1) # check that the edge does not already exist edge = (source, target) if source not in g._nodes: raise InvalidArgument("There is no node {}.".format(source)) if target not in g._nodes: raise InvalidArgument("There is no node {}.".format(target)) if source == target: if not ignore and not self_loop: raise InvalidArgument("Trying to add a self-loop.") elif ignore: _log_message(logger, "WARNING", "Self-loop on {} ignored.".format(source)) return None if (g._directed and edge not in g._unique) or edge not in g._edges: edge_id = self._max_eid # ~ edge_id = len(g._unique) g._unique[edge] = edge_id g._out_deg[source] += 1 g._in_deg[target] += 1 self._max_eid += 1 # check distance _set_dist_new_edges(attributes, self, [edge]) # attributes self._attr_new_edges([(source, target)], attributes=attributes) if not g._directed: # edges and unique are different objects, so update _edges g._edges[edge] = edge_id # add reciprocal e_recip = (target, source) g._edges[e_recip] = edge_id g._out_deg[target] += 1 g._in_deg[source] += 1 else: if not ignore: raise InvalidArgument("Trying to add existing edge.") _log_message(logger, "WARNING", "Existing edge {} ignored.".format((source, target))) return edge def new_edges(self, edge_list, attributes=None, check_duplicates=False, check_self_loops=True, check_existing=True, ignore_invalid=False): ''' Add a list of edges to the graph. .. versionchanged:: 2.0 Can perform all possible checks before adding new edges via the ``check_duplicates`` ``check_self_loops``, and ``check_existing`` arguments. Parameters ---------- edge_list : list of 2-tuples or np.array of shape (edge_nb, 2) List of the edges that should be added as tuples (source, target) attributes : :class:`dict`, optional (default: ``{}``) Dictionary containing optional edge properties. If the graph is weighted, defaults to ``{"weight": ones}``, where ``ones`` is an array the same length as the `edge_list` containing a unit weight for each connection (synaptic strength in NEST). check_duplicates : bool, optional (default: False) Check for duplicate edges within `edge_list`. check_self_loops : bool, optional (default: True) Check for self-loops. check_existing : bool, optional (default: True) Check whether some of the edges in `edge_list` already exist in the graph or exist multiple times in `edge_list` (also performs `check_duplicates`). ignore_invalid : bool, optional (default: False) Ignore invalid edges: they are not added to the graph and are silently dropped. Unless this is set to true, an error is raised whenever one of the three checks fails. .. warning:: Setting `check_existing` to False will lead to undefined behavior if existing edges are provided! Only use it (for speedup) if you are sure that you are indeed only adding new edges. Returns ------- Returns new edges only. ''' attributes = {} if attributes is None else deepcopy(attributes) num_edges = len(edge_list) g = self._graph # set default values for attributes that were not passed _set_default_edge_attributes(self, attributes, num_edges) # check that all nodes exist if np.max(edge_list) >= self.node_nb(): raise InvalidArgument("Some nodes do no exist.") # check edges new_attr = None if check_duplicates or check_self_loops or check_existing: edge_list, new_attr = _cleanup_edges( self, edge_list, attributes, check_duplicates, check_self_loops, check_existing, ignore_invalid) else: new_attr = attributes # create the edges initial_eid = self._max_eid ws = None num_added = len(edge_list) if "weight" in new_attr: if nonstring_container(new_attr["weight"]): ws = new_attr["weight"] else: ws = (new_attr["weight"] for _ in range(num_added)) else: ws = _get_edge_attr(self, edge_list, "weight", last_edges=True) for i, (e, w) in enumerate(zip(edge_list, ws)): eid = self._max_eid g._unique[tuple(e)] = eid self._max_eid += 1 g._out_deg[e[0]] += 1 g._in_deg[e[1]] += 1 if not g._directed: # edges and unique are different objects, so update _edges g._edges[tuple(e)] = eid # reciprocal edge g._edges[tuple(e[::-1])] = eid g._out_deg[e[1]] += 1 g._in_deg[e[0]] += 1 # check distance _set_dist_new_edges(new_attr, self, edge_list) # call parent function to set the attributes self._attr_new_edges(edge_list, attributes=new_attr) return edge_list def delete_edges(self, edges): ''' Remove a list of edges ''' g = self._graph old_enum = len(g._unique) if not nonstring_container(edges[0]): edges = [edges] if not isinstance(edges[0], tuple): edges = [tuple(e) for e in edges] # get edge ids e_to_eid = g._unique eids = {e_to_eid[e] for e in edges} # remove directed = g._directed for e in edges: if e in g._unique: del g._unique[e] if not directed: if e in g._edges: del g._edges[e] del g._edges[e[::-1]] # reset eids for i, e in enumerate(g._unique): g._unique[e] = i if not directed: e._edges[e] = i e._edges[e[::-1]] = i self._eattr.edges_deleted(eids) def clear_all_edges(self): g = self._graph if g._directed: g._edges = g._unique = OrderedDict() assert g._edges is g._unique else: g._edges = OrderedDict() g._unique = OrderedDict() g._out_deg = [0 for _ in range(self.node_nb())] g._out_deg = [0 for _ in range(self.node_nb())] self._eattr.clear() #------------------------------------------------------------------# # Getters def node_nb(self): ''' Returns the number of nodes. .. warning:: When using MPI, returns only the local number of nodes. ''' return len(self._graph._nodes) def edge_nb(self): ''' Returns the number of edges. .. warning:: When using MPI, returns only the local number of edges. ''' return len(self._graph._unique) def is_directed(self): return g._directed def get_degrees(self, mode="total", nodes=None, weights=None): ''' Returns the degree of the nodes. .. warning :: When using MPI, returns only the degree related to local edges. ''' g = self._graph num_nodes = None weights = 'weight' if weights is True else weights if nodes is None: num_nodes = self.node_nb() nodes = slice(num_nodes) elif nonstring_container(nodes): nodes = list(nodes) num_nodes = len(nodes) else: nodes = [nodes] num_nodes = 1 # weighted if nonstring_container(weights) or weights in self._eattr: degrees = np.zeros(num_nodes) adj_mat = self.adjacency_matrix(types=False, weights=weights) if mode in ("in", "total") or not self.is_directed(): degrees += adj_mat.sum(axis=0).A1[nodes] if mode in ("out", "total") and self.is_directed(): degrees += adj_mat.sum(axis=1).A1[nodes] return degrees elif weights not in {None, False}: raise ValueError("Invalid `weights` {}".format(weights)) # unweighted degrees = np.zeros(num_nodes, dtype=int) if not g._directed or mode in ("in", "total"): if isinstance(nodes, slice): degrees += g._in_deg[nodes] else: degrees += [g._in_deg[i] for i in nodes] if g._directed and mode in ("out", "total"): if isinstance(nodes, slice): degrees += g._out_deg[nodes] else: degrees += [g._out_deg[i] for i in nodes] if num_nodes == 1: return degrees[0] return degrees def neighbours(self, node, mode="all"): ''' Return the neighbours of `node`. Parameters ---------- node : int Index of the node of interest. mode : string, optional (default: "all") Type of neighbours that will be returned: "all" returns all the neighbours regardless of directionality, "in" returns the in-neighbours (also called predecessors) and "out" retruns the out-neighbours (or successors). Returns ------- neighbours : set The neighbours of `node`. ''' edges = self.edges_array if mode == "all" or not self._graph._directed: neighbours = set(edges[edges[:, 1] == node, 0]) return neighbours.union(edges[edges[:, 0] == node, 1]) if mode == "in": return set(edges[edges[:, 1] == node, 0]) if mode == "out": return set(edges[edges[:, 0] == node, 1]) raise ValueError(('Invalid `mode` argument {}; possible values' 'are "all", "out" or "in".').format(mode)) def _from_library_graph(self, graph, copy=True): ''' Initialize `self._graph` from existing library object. ''' self._graph = graph._graph.copy() if copy else graph._graph for key, val in graph._nattr.items(): dtype = graph._nattr.value_type(key) self._nattr.new_attribute(key, dtype, values=val) for key, val in graph._eattr.items(): dtype = graph._eattr.value_type(key) self._eattr.new_attribute(key, dtype, values=val) # tool function to set edge properties def _set_prop(array, eid, val): array[eid] = val
Silmathoron/NNGT
nngt/core/nngt_graph.py
Python
gpl-3.0
32,443