code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
using System; using System.IO; using System.Net; using System.Security.Cryptography; using DeanCCCore.Core._2ch.Jane; using DeanCCCore.Core.Utility; namespace DeanCCCore.Core { [Serializable] public class ZipFileHeader : ImageHeader { public ZipFileHeader() { } public ZipFileHeader(int sourceResIndex , string url) { SourceResIndex = sourceResIndex; OriginalUrl = url; } public override bool IsZip { get { return true; } } } }
omega227/DeanCC
DeanCC5/DeanCCCore/Core/ZipFileHeader.cs
C#
gpl-3.0
598
///////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2011- Statoil ASA // Copyright (C) 2013- Ceetron Solutions AS // Copyright (C) 2011-2012 Ceetron AS // // ResInsight 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. // // ResInsight 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 at <http://www.gnu.org/licenses/gpl.html> // for more details. // ///////////////////////////////////////////////////////////////////////////////// #include "RivGridPartMgr.h" #include "RiaApplication.h" #include "RiaPreferences.h" #include "RigCaseCellResultsData.h" #include "RigCaseData.h" #include "RigResultAccessorFactory.h" #include "RimEclipseCase.h" #include "RimCellEdgeResultSlot.h" #include "RimReservoirCellResultsStorage.h" #include "RimReservoirView.h" #include "RimResultSlot.h" #include "RimTernaryLegendConfig.h" #include "RimWellCollection.h" #include "RivCellEdgeEffectGenerator.h" #include "RivResultToTextureMapper.h" #include "RivScalarMapperUtils.h" #include "RivSourceInfo.h" #include "RivTernaryScalarMapperEffectGenerator.h" #include "RivTernaryTextureCoordsCreator.h" #include "RivTextureCoordsCreator.h" #include "cafEffectGenerator.h" #include "cafPdmFieldCvfColor.h" #include "cafPdmFieldCvfMat4d.h" #include "cafProgressInfo.h" #include "cvfDrawableGeo.h" #include "cvfMath.h" #include "cvfModelBasicList.h" #include "cvfPart.h" #include "cvfRenderStateBlending.h" #include "cvfRenderStatePolygonOffset.h" #include "cvfRenderState_FF.h" #include "cvfShaderProgram.h" #include "cvfShaderProgramGenerator.h" #include "cvfShaderSourceProvider.h" #include "cvfShaderSourceRepository.h" #include "cvfStructGrid.h" #include "cvfUniform.h" //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- RivGridPartMgr::RivGridPartMgr(const RigGridBase* grid, size_t gridIdx) : m_surfaceGenerator(grid), m_gridIdx(gridIdx), m_grid(grid), m_surfaceFaceFilter(grid), m_opacityLevel(1.0f), m_defaultColor(cvf::Color3::WHITE) { CVF_ASSERT(grid); m_cellVisibility = new cvf::UByteArray; m_surfaceFacesTextureCoords = new cvf::Vec2fArray; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RivGridPartMgr::setTransform(cvf::Transform* scaleTransform) { m_scaleTransform = scaleTransform; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RivGridPartMgr::setCellVisibility(cvf::UByteArray* cellVisibilities) { CVF_ASSERT(m_scaleTransform.notNull()); CVF_ASSERT(cellVisibilities); m_cellVisibility = cellVisibilities; m_surfaceGenerator.setCellVisibility(cellVisibilities); m_surfaceGenerator.addFaceVisibilityFilter(&m_surfaceFaceFilter); generatePartGeometry(m_surfaceGenerator); } void RivGridPartMgr::generatePartGeometry(cvf::StructGridGeometryGenerator& geoBuilder) { bool useBufferObjects = true; // Surface geometry { cvf::ref<cvf::DrawableGeo> geo = geoBuilder.generateSurface(); if (geo.notNull()) { geo->computeNormals(); if (useBufferObjects) { geo->setRenderMode(cvf::DrawableGeo::BUFFER_OBJECT); } cvf::ref<cvf::Part> part = new cvf::Part; part->setName("Grid " + cvf::String(static_cast<int>(m_gridIdx))); part->setId(m_gridIdx); // !! For now, use grid index as part ID (needed for pick info) part->setDrawable(geo.p()); part->setTransform(m_scaleTransform.p()); // Set mapping from triangle face index to cell index cvf::ref<RivSourceInfo> si = new RivSourceInfo; si->m_cellFaceFromTriangleMapper = geoBuilder.triangleToCellFaceMapper(); part->setSourceInfo(si.p()); part->updateBoundingBox(); // Set default effect caf::SurfaceEffectGenerator geometryEffgen(cvf::Color4f(cvf::Color3f::WHITE), caf::PO_1); cvf::ref<cvf::Effect> geometryOnlyEffect = geometryEffgen.generateEffect(); part->setEffect(geometryOnlyEffect.p()); part->setEnableMask(surfaceBit); m_surfaceFaces = part; } } // Mesh geometry { cvf::ref<cvf::DrawableGeo> geoMesh = geoBuilder.createMeshDrawable(); if (geoMesh.notNull()) { if (useBufferObjects) { geoMesh->setRenderMode(cvf::DrawableGeo::BUFFER_OBJECT); } cvf::ref<cvf::Part> part = new cvf::Part; part->setName("Grid mesh " + cvf::String(static_cast<int>(m_gridIdx))); part->setDrawable(geoMesh.p()); part->setTransform(m_scaleTransform.p()); part->updateBoundingBox(); RiaPreferences* prefs = RiaApplication::instance()->preferences(); cvf::ref<cvf::Effect> eff; caf::MeshEffectGenerator effGen(prefs->defaultGridLineColors()); eff = effGen.generateEffect(); // Set priority to make sure fault lines are rendered first part->setPriority(10); part->setEnableMask(meshSurfaceBit); part->setEffect(eff.p()); m_surfaceGridLines = part; } } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RivGridPartMgr::appendPartsToModel(cvf::ModelBasicList* model) { CVF_ASSERT(model != NULL); if(m_surfaceFaces.notNull() ) model->addPart(m_surfaceFaces.p() ); if(m_surfaceGridLines.notNull()) model->addPart(m_surfaceGridLines.p()); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RivGridPartMgr::updateCellColor(cvf::Color4f color) { if (m_surfaceFaces.isNull()) return; // Set default effect caf::SurfaceEffectGenerator geometryEffgen(color, caf::PO_1); cvf::ref<cvf::Effect> geometryOnlyEffect = geometryEffgen.generateEffect(); if (m_surfaceFaces.notNull()) m_surfaceFaces->setEffect(geometryOnlyEffect.p()); if (color.a() < 1.0f) { // Set priority to make sure this transparent geometry are rendered last if (m_surfaceFaces.notNull()) m_surfaceFaces->setPriority(100); } m_opacityLevel = color.a(); m_defaultColor = color.toColor3f(); // Update mesh colors as well, in case of change RiaPreferences* prefs = RiaApplication::instance()->preferences(); cvf::ref<cvf::Effect> eff; if (m_surfaceFaces.notNull()) { caf::MeshEffectGenerator effGen(prefs->defaultGridLineColors()); eff = effGen.generateEffect(); m_surfaceGridLines->setEffect(eff.p()); } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RivGridPartMgr::updateCellResultColor(size_t timeStepIndex, RimResultSlot* cellResultSlot) { CVF_ASSERT(cellResultSlot); RigCaseData* eclipseCase = cellResultSlot->reservoirView()->eclipseCase()->reservoirData(); cvf::ref<cvf::Color3ubArray> surfaceFacesColorArray; // Outer surface if (m_surfaceFaces.notNull()) { if (cellResultSlot->isTernarySaturationSelected()) { RivTernaryTextureCoordsCreator texturer(cellResultSlot, cellResultSlot->ternaryLegendConfig(), timeStepIndex, m_grid->gridIndex(), m_surfaceGenerator.quadToCellFaceMapper()); texturer.createTextureCoords(m_surfaceFacesTextureCoords.p()); const RivTernaryScalarMapper* mapper = cellResultSlot->ternaryLegendConfig()->scalarMapper(); RivScalarMapperUtils::applyTernaryTextureResultsToPart(m_surfaceFaces.p(), m_surfaceFacesTextureCoords.p(), mapper, m_opacityLevel, caf::FC_NONE); } else { RivTextureCoordsCreator texturer(cellResultSlot, timeStepIndex, m_grid->gridIndex(), m_surfaceGenerator.quadToCellFaceMapper()); if (!texturer.isValid()) { return; } texturer.createTextureCoords(m_surfaceFacesTextureCoords.p()); const cvf::ScalarMapper* mapper = cellResultSlot->legendConfig()->scalarMapper(); RivScalarMapperUtils::applyTextureResultsToPart(m_surfaceFaces.p(), m_surfaceFacesTextureCoords.p(), mapper, m_opacityLevel, caf::FC_NONE); } } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RivGridPartMgr::updateCellEdgeResultColor(size_t timeStepIndex, RimResultSlot* cellResultSlot, RimCellEdgeResultSlot* cellEdgeResultSlot) { if (m_surfaceFaces.notNull()) { cvf::DrawableGeo* dg = dynamic_cast<cvf::DrawableGeo*>(m_surfaceFaces->drawable()); if (dg) { cvf::ref<cvf::Effect> eff = RivScalarMapperUtils::createCellEdgeEffect(dg, m_surfaceGenerator.quadToCellFaceMapper(), m_grid->gridIndex(), timeStepIndex, cellResultSlot, cellEdgeResultSlot, m_opacityLevel, m_defaultColor, caf::FC_NONE); m_surfaceFaces->setEffect(eff.p()); } } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- RivGridPartMgr::~RivGridPartMgr() { #if 0 if (m_faultFaces.notNull()) m_faultFaces->deleteOrReleaseOpenGLResources(); if (m_faultGridLines.notNull()) m_faultGridLines->deleteOrReleaseOpenGLResources(); if (m_surfaceGridLines.notNull()) m_surfaceGridLines->deleteOrReleaseOpenGLResources(); if (m_surfaceFaces.notNull()) m_surfaceFaces->deleteOrReleaseOpenGLResources(); #endif }
iLoop2/ResInsight
ApplicationCode/ModelVisualization/RivGridPartMgr.cpp
C++
gpl-3.0
10,747
ALTER TABLE Tag ADD (version INT DEFAULT '0' NOT NULL);
mozilla/caseconductor-ui
platform/db_scripts/db_tcm_update_db_script_8.sql
SQL
gpl-3.0
57
# Manage yum repos ## in any.yaml ``` repos::default: gpgcheck: 0 enabled: 1 mirrorlist_expire: 7200 failovermethod: priority repos::list: name1: descr: name-1 mirrorlist: 'http://url/?release=$releasever&arch=$basearch&repo=os&infra=$infra' priority: 50 name2: descr: name-2 mirrorlist: 'http://url/?release=$releasever&arch=$basearch&repo=updates&infra=$infra' priority: 51 ``` if `:merge_behavior: deeper` all found hashes will be merged in accordance with the priority.
FATruden/puppet
modules/repos/README.md
Markdown
gpl-3.0
518
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.2.4 or newer * * NOTICE OF LICENSE * * Licensed under the Academic Free License version 3.0 * * This source file is subject to the Academic Free License (AFL 3.0) that is * bundled with this package in the files license_afl.txt / license_afl.rst. * It is also available through the world wide web at this URL: * http://opensource.org/licenses/AFL-3.0 * If you did not receive a copy of the license and are unable to obtain it * through the world wide web, please send an email to * [email protected] so we can send you a copy immediately. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/) * @license http://opensource.org/licenses/AFL-3.0 Academic Free License (AFL 3.0) * @link http://codeigniter.com * @since Version 1.0 * @filesource */ ?><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Database Error</title> <style type="text/css"> ::selection{ background-color: #E13300; color: white; } ::moz-selection{ background-color: #E13300; color: white; } ::webkit-selection{ background-color: #E13300; color: white; } body { background-color: #fff; margin: 40px; font: 13px/20px normal Helvetica, Arial, sans-serif; color: #4F5155; } a { color: #003399; background-color: transparent; font-weight: normal; } h1 { color: #444; background-color: transparent; border-bottom: 1px solid #D0D0D0; font-size: 19px; font-weight: normal; margin: 0 0 14px 0; padding: 14px 15px 10px 15px; } code { font-family: Consolas, Monaco, Courier New, Courier, monospace; font-size: 12px; background-color: #f9f9f9; border: 1px solid #D0D0D0; color: #002166; display: block; margin: 14px 0 14px 0; padding: 12px 10px 12px 10px; } #container { margin: 10px; border: 1px solid #D0D0D0; -webkit-box-shadow: 0 0 8px #D0D0D0; } p { margin: 12px 15px 12px 15px; } </style> </head> <body> <div id="container"> <h1><?php echo $heading; ?></h1> <?php echo $message; ?> </div> </body> </html>
MitchellMcKenna/LifePress
application/errors/error_db.php
PHP
gpl-3.0
2,192
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>GLFW: Globals</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="extra.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <div class="glfwheader"> <a href="http://www.glfw.org/" id="glfwhome">GLFW</a> <ul class="glfwnavbar"> <li><a href="http://www.glfw.org/documentation.html">Documentation</a></li> <li><a href="http://www.glfw.org/download.html">Download</a></li> <li><a href="http://www.glfw.org/media.html">Media</a></li> <li><a href="http://www.glfw.org/community.html">Community</a></li> </ul> </div> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li class="current"><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li><a href="globals.html"><span>All</span></a></li> <li><a href="globals_func.html"><span>Functions</span></a></li> <li><a href="globals_type.html"><span>Typedefs</span></a></li> <li class="current"><a href="globals_defs.html"><span>Macros</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="globals_defs.html#index_a"><span>a</span></a></li> <li><a href="globals_defs_b.html#index_b"><span>b</span></a></li> <li><a href="globals_defs_c.html#index_c"><span>c</span></a></li> <li><a href="globals_defs_d.html#index_d"><span>d</span></a></li> <li><a href="globals_defs_e.html#index_e"><span>e</span></a></li> <li><a href="globals_defs_f.html#index_f"><span>f</span></a></li> <li><a href="globals_defs_g.html#index_g"><span>g</span></a></li> <li><a href="globals_defs_h.html#index_h"><span>h</span></a></li> <li><a href="globals_defs_i.html#index_i"><span>i</span></a></li> <li><a href="globals_defs_j.html#index_j"><span>j</span></a></li> <li><a href="globals_defs_k.html#index_k"><span>k</span></a></li> <li><a href="globals_defs_l.html#index_l"><span>l</span></a></li> <li class="current"><a href="globals_defs_m.html#index_m"><span>m</span></a></li> <li><a href="globals_defs_n.html#index_n"><span>n</span></a></li> <li><a href="globals_defs_o.html#index_o"><span>o</span></a></li> <li><a href="globals_defs_p.html#index_p"><span>p</span></a></li> <li><a href="globals_defs_r.html#index_r"><span>r</span></a></li> <li><a href="globals_defs_s.html#index_s"><span>s</span></a></li> <li><a href="globals_defs_t.html#index_t"><span>t</span></a></li> <li><a href="globals_defs_v.html#index_v"><span>v</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> &#160; <h3><a class="anchor" id="index_m"></a>- m -</h3><ul> <li>GLFW_MAXIMIZED : <a class="el" href="glfw3_8h.html#ad8ccb396253ad0b72c6d4c917eb38a03">glfw3.h</a> </li> <li>GLFW_MOD_ALT : <a class="el" href="group__mods.html#gad2acd5633463c29e07008687ea73c0f4">glfw3.h</a> </li> <li>GLFW_MOD_CONTROL : <a class="el" href="group__mods.html#ga6ed94871c3208eefd85713fa929d45aa">glfw3.h</a> </li> <li>GLFW_MOD_SHIFT : <a class="el" href="group__mods.html#ga14994d3196c290aaa347248e51740274">glfw3.h</a> </li> <li>GLFW_MOD_SUPER : <a class="el" href="group__mods.html#ga6b64ba10ea0227cf6f42efd0a220aba1">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_1 : <a class="el" href="group__buttons.html#ga181a6e875251fd8671654eff00f9112e">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_2 : <a class="el" href="group__buttons.html#ga604b39b92c88ce9bd332e97fc3f4156c">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_3 : <a class="el" href="group__buttons.html#ga0130d505563d0236a6f85545f19e1721">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_4 : <a class="el" href="group__buttons.html#ga53f4097bb01d5521c7d9513418c91ca9">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_5 : <a class="el" href="group__buttons.html#gaf08c4ddecb051d3d9667db1d5e417c9c">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_6 : <a class="el" href="group__buttons.html#gae8513e06aab8aa393b595f22c6d8257a">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_7 : <a class="el" href="group__buttons.html#ga8b02a1ab55dde45b3a3883d54ffd7dc7">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_8 : <a class="el" href="group__buttons.html#ga35d5c4263e0dc0d0a4731ca6c562f32c">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_LAST : <a class="el" href="group__buttons.html#gab1fd86a4518a9141ec7bcde2e15a2fdf">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_LEFT : <a class="el" href="group__buttons.html#gaf37100431dcd5082d48f95ee8bc8cd56">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_MIDDLE : <a class="el" href="group__buttons.html#ga34a4d2a701434f763fd93a2ff842b95a">glfw3.h</a> </li> <li>GLFW_MOUSE_BUTTON_RIGHT : <a class="el" href="group__buttons.html#ga3e2f2cf3c4942df73cc094247d275e74">glfw3.h</a> </li> </ul> </div><!-- contents --> <address class="footer"> <p> Last update on Wed Feb 1 2017 for GLFW 3.2.1 </p> </address> </body> </html>
MichaelCoughlinAN/Odds-N-Ends
C++/OpenGL_Example_1/build/glfw-3.2.1/docs/html/globals_defs_m.html
HTML
gpl-3.0
7,738
/* RPG Paper Maker Copyright (C) 2017-2021 Wano RPG Paper Maker engine is under proprietary license. This source code is also copyrighted. Use Commercial edition for commercial use of your games. See RPG Paper Maker EULA here: http://rpg-paper-maker.com/index.php/eula. */ #include "paneldamageskind.h" #include "ui_paneldamageskind.h" #include "damageskind.h" #include "common.h" #include "rpm.h" // ------------------------------------------------------- // // CONSTRUCTOR / DESTRUCTOR / GET / SET // // ------------------------------------------------------- PanelDamagesKind::PanelDamagesKind(QWidget *parent) : QWidget(parent), ui(new Ui::PanelDamagesKind) { ui->setupUi(this); } PanelDamagesKind::~PanelDamagesKind() { delete ui; } // ------------------------------------------------------- // // INTERMEDIARY FUNCTIONS // // ------------------------------------------------------- void PanelDamagesKind::initialize(PrimitiveValue *statisticID, PrimitiveValue *currencyID, SuperListItem *variableID, SuperListItem *kind) { m_statisticID = statisticID; m_currencyID = currencyID; m_variableID = variableID; m_kind = kind; int index = m_kind->id(); ui->comboBoxChoice->clear(); ui->comboBoxChoice->addItems(RPM::ENUM_TO_STRING_DAMAGES_KIND); ui->comboBoxChoice->setCurrentIndex(index); ui->panelPrimitiveValueStatistic->initializeDataBaseCommandId(m_statisticID ->modelDataBase()); ui->panelPrimitiveValueStatistic->initializeModel(m_statisticID); ui->panelPrimitiveValueStatistic->updateModel(); ui->panelPrimitiveValueCurrency->initializeDataBaseCommandId(m_currencyID ->modelDataBase()); ui->panelPrimitiveValueCurrency->initializeModel(m_currencyID); ui->panelPrimitiveValueCurrency->updateModel(); ui->widgetVariable->initializeSuper(m_variableID); showElement(); } // ------------------------------------------------------- void PanelDamagesKind::hideAll() { ui->panelPrimitiveValueStatistic->hide(); ui->panelPrimitiveValueCurrency->hide(); ui->widgetVariable->hide(); } // ------------------------------------------------------- void PanelDamagesKind::showElement() { hideAll(); switch (static_cast<DamagesKind>(m_kind->id())) { case DamagesKind::Stat: ui->panelPrimitiveValueStatistic->show(); break; case DamagesKind::Currency: ui->panelPrimitiveValueCurrency->show(); break; case DamagesKind::Variable: ui->widgetVariable->show(); break; } } // ------------------------------------------------------- // // SLOTS // // ------------------------------------------------------- void PanelDamagesKind::on_comboBoxChoice_currentIndexChanged(int index) { m_kind->setId(index); showElement(); }
Wano-k/RPG-Paper-Maker
Editor/CustomWidgets/paneldamageskind.cpp
C++
gpl-3.0
2,843
#! /bin/sh dirs="$*" if test _"$dirs" = _ then dirs="." fi for dir in $dirs do if test -d $dir then aclocal="" autoconf=" && autoconf" autoheader="" automake="" if test -f $dir/Makefile.am then aclocal=" && aclocal -I build-aux" automake=" && automake --copy --add-missing" if egrep 'A[CM]_PROG_LIBTOOL' $dir/configure.ac >/dev/null then libtoolize=" && libtoolize --copy --automake" fi fi if egrep 'A[CM]_CONFIG_HEADER' $dir/configure.ac >/dev/null then autoheader=" && autoheader" fi commands="cd $dir${libtoolize}${aclocal}${autoheader}${autoconf}${automake}" echo "$commands" eval "($commands)" result=$? if test $result -ne 0 then exit $result fi fi done exit $result
virtuald/webdma
autogen.sh
Shell
gpl-3.0
724
### # Copyright 2016 - 2022 Green River Data Analysis, LLC # # License detail: https://github.com/greenriver/hmis-warehouse/blob/production/LICENSE.md ### require 'memoist' module ClaimsReporting::Health module PatientExtension extend ActiveSupport::Concern included do extend Memoist has_many :medical_claims, class_name: 'ClaimsReporting::MedicalClaim', foreign_key: :member_id, primary_key: :medicaid_id def medical_claims_for_qualifying_activity(qa, denied: false) # rubocop:disable Naming/MethodParameterName activity_date_range = Range.new(*qualifying_activities.map(&:date_of_activity).minmax) ( medical_claims_by_service_start_date(date_range: activity_date_range)[qa.date_of_activity] || [] ).select do |c| procedure_matches = qa.procedure_with_modifiers == c.procedure_with_modifiers procedure_matches &&= c.claim_status == 'D' if denied procedure_matches end end def best_medical_claim_for_qualifying_activity(qa, denied: false) # rubocop:disable Naming/MethodParameterName matching_claims = medical_claims_for_qualifying_activity(qa, denied: denied) return matching_claims.first if matching_claims.size <= 1 # slow path -- more that one matching claim for the same day # we can try to assign them in matching order by id matching_qa = qualifying_activities.select do |qa2| ( qa2.claim_submitted_on.present? && qa2.date_of_activity == qa.date_of_activity && qa2.procedure_with_modifiers == qa.procedure_with_modifiers ) end return nil unless matching_qa.size == matching_claims.size return nil if matching_qa.index(qa).nil? matching_claims[matching_qa.index(qa)] end def medical_claims_by_service_start_date(date_range:) medical_claims.where( service_start_date: date_range, ).group_by(&:service_start_date) end memoize :medical_claims_by_service_start_date end end end
greenriver/hmis-warehouse
drivers/claims_reporting/extensions/health/patient_extension.rb
Ruby
gpl-3.0
2,089
<?php /**************************************************************************/ /* PHP-NUKE: Advanced Content Management System */ /* ============================================ */ /* */ /* This is the language module with all the system messages */ /* */ /* If you made a translation go to the my website and send to me */ /* the translated file. Please keep the original text order by modules, */ /* and just one message per line, also double check your translation! */ /* */ /* You need to change the second quoted phrase, not the capital one! */ /* */ /* If you need to use double quotes (") remember to add a backslash (\), */ /* so your entry will look like: This is \"double quoted\" text. */ /* And, if you use HTML code, please double check it. */ /**************************************************************************/ define("_URL","URL"); define("_FUNCTIONS","Functions"); define("_YES","Yes"); define("_NO","No"); define("_CATEGORY","Category"); define("_SAVECHANGES","Save Changes"); define("_OK","Ok!"); define("_HITS","Hits"); define("_THEREARE","There are"); define("_CHECK","Check"); define("_AUTHORNAME","Author's Name"); define("_AUTHOREMAIL","Author's Email"); define("_DOWNLOADNAME","Program Name"); define("_INBYTES","in bytes"); define("_FILESIZE","Filesize"); define("_VERSION","Version"); define("_DESCRIPTION","Description"); define("_AUTHOR","Author"); define("_HOMEPAGE","HomePage"); define("_NAME","Name"); define("_FILEURL","File Link"); define("_DOWNLOADID","Download ID"); define("_PAGETITLE","Page Title"); define("_PAGEURL","Page URL"); define("_ADDURL","Add this URL"); define("_DOWNLOAD","Downloads"); define("_TITLE","Title"); define("_STATUS","Status"); define("_ADD","Add"); define("_MODIFY","Modify"); define("_DOWNLOADSINDB","Downloads in our Database"); define("_DOWNLOADSWAITINGVAL","Downloads Waiting for Validation"); define("_CLEANDOWNLOADSDB","Clean Downloads Votes"); define("_BROKENDOWNLOADSREP","Broken Downloads Reports"); define("_DOWNLOADMODREQUEST","Download Modification Requests"); define("_ADDNEWDOWNLOAD","Add a New Download"); define("_MODDOWNLOAD","Modify a Download"); define("_WEBDOWNLOADSADMIN","Web Downloads Administration"); define("_DNOREPORTEDBROKEN","No reported broken downloads."); define("_DUSERREPBROKEN","User Reported Broken Downloads"); define("_DIGNOREINFO","Ignore (Deletes all <strong><i>requests</i></strong> for a given download)"); define("_DDELETEINFO","Delete (Deletes <strong><i>broken download</i></strong> and <strong><i>requests</i></strong> for a given download)"); define("_DOWNLOADOWNER","Download Owner"); define("_DUSERMODREQUEST","User Download Modification Requests"); define("_DOWNLOADVALIDATION","Download Validation"); define("_CHECKALLDOWNLOADS","Check ALL Downloads"); define("_VALIDATEDOWNLOADS","Validate Downloads"); define("_NEWDOWNLOADADDED","New Download added to the Database"); define("_SUBMITTER","Submitter"); define("_VISIT","Visit"); define("_ADDMAINCATEGORY","Add a MAIN Category"); define("_ADDSUBCATEGORY","Add a SUB-Category"); define("_IN","in"); define("_DESCRIPTION255","Description: (255 characters max)"); define("_MODCATEGORY","Modify a Category"); define("_ADDEDITORIAL","Add Editorial"); define("_EDITORIALTITLE","Editorial Title"); define("_EDITORIALTEXT","Editorial Text"); define("_DATEWRITTEN","Date Written"); define("_IGNORE","Ignore"); define("_ORIGINAL","Original"); define("_PROPOSED","Proposed"); define("_NOMODREQUESTS","There are not any modification requests right now"); define("_SUBCATEGORY","Sub-Category"); define("_OWNER","Owner"); define("_ACCEPT","Accept"); define("_ERRORTHECATEGORY","ERROR: The Category"); define("_ALREADYEXIST","already exist!"); define("_ERRORTHESUBCATEGORY","ERROR: The Sub-Category"); define("_EDITORIALADDED","Editorial added to the Database"); define("_EDITORIALMODIFIED","Editorial Modified"); define("_EDITORIALREMOVED","Editorial removed from the Database"); define("_CHECKCATEGORIES","Check Categories"); define("_INCLUDESUBCATEGORIES","(include Sub-Categories)"); define("_FAILED","Failed!"); define("_BEPATIENT","(please be patient)"); define("_VALIDATINGCAT","Validating Category (and all subcategories)"); define("_VALIDATINGSUBCAT","Validating Sub-Category"); define("_ERRORURLEXIST","ERROR: This URL is already listed in the Database!"); define("_ERRORNOTITLE","ERROR: You need to type a TITLE for your URL!"); define("_ERRORNOURL","ERROR: You need to type a URL for your URL!"); define("_ERRORNODESCRIPTION","ERROR: You need to type a DESCRIPTION for your URL!"); define("_EZTRANSFER","Transfer"); define("_EZTHEREIS","There is"); define("_EZSUBCAT","sub-categories"); define("_EZATTACHEDTOCAT","under this category"); define("_EZTRANSFERDOWNLOADS","Transfer all downloads from category"); define("_DELEZDOWNLOADSCATWARNING","WARNING : Are you sure you want to delete this category? You will delete all sub-categories and attached downloads as well!"); define("_DOWNLOADTITLE","Download Title"); ?>
TGates71/PNPv1-Languages
PNPv101-lang-english/modules/Downloads/admin/language/lang-english.php
PHP
gpl-3.0
5,394
package com.hackatoncivico.rankingpolitico; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.util.LogWriter; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.hackatoncivico.rankingpolitico.models.Candidato; import com.hackatoncivico.rankingpolitico.models.Criterio; import com.hackatoncivico.rankingpolitico.models.CriterioCandidato; import com.hackatoncivico.rankingpolitico.models.RegistroCandidato; import com.hackatoncivico.rankingpolitico.models.RegistroCandidatos; import com.hackatoncivico.rankingpolitico.utils.ApiAccess; import com.hackatoncivico.rankingpolitico.utils.Utils; import com.squareup.picasso.Picasso; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; /** * Created by franz on 7/11/2015. */ public class ProfileActivity extends AppCompatActivity { private static final String TAG = "ProfileActivity"; public static final String ID_CANDIDATO = "ID_CANDIDATO"; private String idCandidato; private Candidato candidato; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); // Add Toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar); toolbar.setTitle(getString(R.string.title_profile_activity)); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); idCandidato = sharedPref.getString(Utils.SELECTED_CANDIDATE, ""); GetCandidato data = new GetCandidato(); data.execute(); } @Override public void onResume() { super.onResume(); if (candidato != null) { handleCandidato(candidato); } } private void handleCandidato(final Candidato candidato){ this.candidato = candidato; Button btn_logros = (Button) findViewById(R.id.btn_logros); btn_logros.setOnClickListener(Utils.setNextScreenListener(this, LogrosActivity.class, LogrosActivity.ID_CANDIDATO, String.valueOf(candidato.id))); Button btn_criterios = (Button) findViewById(R.id.btn_criterios); btn_criterios.setOnClickListener(Utils.setNextScreenListener(this, CriteriosActivity.class, CriteriosActivity.ID_CANDIDATO, String.valueOf(candidato.id))); runOnUiThread(new Runnable() { @Override public void run() { //progressBar.setVisibility(View.GONE); ImageView avatar = (ImageView) findViewById(R.id.profile_avatar); Picasso.with(getBaseContext()) .load(ApiAccess.DOMINIO_URL + candidato.foto) .placeholder(R.drawable.avatar) .into(avatar); TextView full_name = (TextView) findViewById(R.id.profile_full_name); full_name.setText(candidato.nombres + " " + candidato.apellidos); TextView logros = (TextView) findViewById(R.id.profile_logros_count); logros.setText(String.valueOf(candidato.logros.size())); int criterios_count = 0; for (int i = 0; i < candidato.criterios.size(); i++) { CriterioCandidato criterioCandidato = candidato.criterios.get(i); Criterio criterio = criterioCandidato.criterio; try{ criterios_count = criterios_count + Integer.parseInt(criterio.puntuacion); } catch (NumberFormatException nfe){ nfe.printStackTrace(); } } TextView criterios = (TextView) findViewById(R.id.profile_criterios_count); criterios.setText(String.valueOf(criterios_count)); } }); } private class GetCandidato extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params) { try { //Create an HTTP client HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(ApiAccess.CANDIDATOS_URL + '/' + idCandidato); //Perform the request and check the status code HttpResponse response = client.execute(get); StatusLine statusLine = response.getStatusLine(); if(statusLine.getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); try { //Read the server response and attempt to parse it as JSON Reader reader = new InputStreamReader(content); GsonBuilder gsonBuilder = new GsonBuilder(); //gsonBuilder.setDateFormat("M/d/yy hh:mm a"); Gson gson = gsonBuilder.create(); //List<Candidato> posts = new ArrayList<Candidato>(); //posts = Arrays.asList(gson.fromJson(reader, Candidato[].class)); RegistroCandidato registroCandidato = gson.fromJson(reader, RegistroCandidato.class); content.close(); handleCandidato(registroCandidato.registros); } catch (Exception ex) { Log.e(TAG, "Failed to parse JSON due to: " + ex); //failedLoadingPosts(); } } else { Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode()); //failedLoadingPosts(); } } catch(Exception ex) { Log.e(TAG, "Failed to send HTTP POST request due to: " + ex); //failedLoadingPosts(); } return null; } } }
franzueto/rankingpoliticogt-android
app/src/main/java/com/hackatoncivico/rankingpolitico/ProfileActivity.java
Java
gpl-3.0
6,690
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #ifndef STORAGE_LEVELDB_INCLUDE_DB_H_ #define STORAGE_LEVELDB_INCLUDE_DB_H_ #include <stdint.h> #include <stdio.h> #include "iterator.h" #include "options.h" namespace leveldb { // Update Makefile if you change these static const int kMajorVersion = 1; static const int kMinorVersion = 19; struct Options; struct ReadOptions; struct WriteOptions; class WriteBatch; // Abstract handle to particular state of a DB. // A Snapshot is an immutable object and can therefore be safely // accessed from multiple threads without any external synchronization. class Snapshot { protected: virtual ~Snapshot(); }; // A range of keys struct Range { Slice start; // Included in the range Slice limit; // Not included in the range Range() { } Range(const Slice& s, const Slice& l) : start(s), limit(l) { } }; // A DB is a persistent ordered map from keys to values. // A DB is safe for concurrent access from multiple threads without // any external synchronization. class DB { public: // Open the database with the specified "name". // Stores a pointer to a heap-allocated database in *dbptr and returns // OK on success. // Stores NULL in *dbptr and returns a non-OK status on error. // Caller should delete *dbptr when it is no longer needed. static Status Open(const Options& options, const std::string& name, DB** dbptr); DB() { } virtual ~DB(); // Set the database entry for "key" to "value". Returns OK on success, // and a non-OK status on error. // Note: consider setting options.sync = true. virtual Status Put(const WriteOptions& options, const Slice& key, const Slice& value) = 0; // Remove the database entry (if any) for "key". Returns OK on // success, and a non-OK status on error. It is not an error if "key" // did not exist in the database. // Note: consider setting options.sync = true. virtual Status Delete(const WriteOptions& options, const Slice& key) = 0; // Apply the specified updates to the database. // Returns OK on success, non-OK on failure. // Note: consider setting options.sync = true. virtual Status Write(const WriteOptions& options, WriteBatch* updates) = 0; // If the database contains an entry for "key" store the // corresponding value in *value and return OK. // // If there is no entry for "key" leave *value unchanged and return // a status for which Status::IsNotFound() returns true. // // May return some other Status on an error. virtual Status Get(const ReadOptions& options, const Slice& key, std::string* value) = 0; // Return a heap-allocated iterator over the contents of the database. // The result of NewIterator() is initially invalid (caller must // call one of the Seek methods on the iterator before using it). // // Caller should delete the iterator when it is no longer needed. // The returned iterator should be deleted before this db is deleted. virtual Iterator* NewIterator(const ReadOptions& options) = 0; // Return a handle to the current DB state. Iterators created with // this handle will all observe a stable snapshot of the current DB // state. The caller must call ReleaseSnapshot(result) when the // snapshot is no longer needed. virtual const Snapshot* GetSnapshot() = 0; // Release a previously acquired snapshot. The caller must not // use "snapshot" after this call. virtual void ReleaseSnapshot(const Snapshot* snapshot) = 0; // DB implementations can export properties about their state // via this method. If "property" is a valid property understood by this // DB implementation, fills "*value" with its current value and returns // true. Otherwise returns false. // // // Valid property names include: // // "leveldb.num-files-at-level<N>" - return the number of files at level <N>, // where <N> is an ASCII representation of a level number (e.g. "0"). // "leveldb.stats" - returns a multi-line string that describes statistics // about the internal operation of the DB. // "leveldb.sstables" - returns a multi-line string that describes all // of the sstables that make up the db contents. // "leveldb.approximate-memory-usage" - returns the approximate number of // bytes of memory in use by the DB. virtual bool GetProperty(const Slice& property, std::string* value) = 0; // For each i in [0,n-1], store in "sizes[i]", the approximate // file system space used by keys in "[range[i].start .. range[i].limit)". // // Note that the returned sizes measure file system space usage, so // if the user data compresses by a factor of ten, the returned // sizes will be one-tenth the size of the corresponding user data size. // // The results may not include the sizes of recently written data. virtual void GetApproximateSizes(const Range* range, int n, uint64_t* sizes) = 0; // Compact the underlying storage for the key range [*begin,*end]. // In particular, deleted and overwritten versions are discarded, // and the data is rearranged to reduce the cost of operations // needed to access the data. This operation should typically only // be invoked by users who understand the underlying implementation. // // begin==NULL is treated as a key before all keys in the database. // end==NULL is treated as a key after all keys in the database. // Therefore the following call will compact the entire database: // db->CompactRange(NULL, NULL); virtual void CompactRange(const Slice* begin, const Slice* end) = 0; private: // No copying allowed DB(const DB&); void operator=(const DB&); }; // Destroy the contents of the specified database. // Be very careful using this method. Status DestroyDB(const std::string& name, const Options& options); // If a DB cannot be opened, you may attempt to call this method to // resurrect as much of the contents of the database as possible. // Some data may be lost, so be careful when calling this function // on a database that contains important information. Status RepairDB(const std::string& dbname, const Options& options); } // namespace leveldb #endif // STORAGE_LEVELDB_INCLUDE_DB_H_
martinvol/tallerII
ApplicationServer/src/leveldb/include/leveldb/db.h
C
gpl-3.0
6,509
/* * OpenSplice DDS * * This software and documentation are Copyright 2006 to 2013 PrismTech * Limited and its licensees. All rights reserved. See file: * * $OSPL_HOME/LICENSE * * for full copyright notice and license terms. * */ #include <assert.h> #include "c_typebase.h" #include "idl_scope.h" #include "idl_genCxxHelper.h" #include "os_heap.h" #include "os_stdlib.h" #define IDL_MAXSCOPE (20) /* This modules handles the name scopes of objects by providing a scope stack. Each time a name scope is defined, the name is pushed on the stack. Each time the name scope is left, the name is popped from the stack. Name scopes are defined by the IDL definition "module <name>", "struct <name>" and "union <name>". */ /* idl_scopeElement specifies a scope stack element where "scopeName" specifies the name of the scope and "scopeType" specifies the kind of scope, either "idl_tFile" which is currently not used, "idl_tModule" for a module definition, "idl_tStruct" for a structure definition and "idl_tUnion" for a union definition. */ C_STRUCT(idl_scopeElement) { c_char *scopeName; idl_scopeType scopeType; }; /* idl_scope specifies the scope stack where "stack" is an array of "idl_scopeElement", "baseName" specifies the basename of the file that contains the scope stack and "scopePointer" specifies the actual top of the stack (-1 specifies an empty stack). */ C_STRUCT(idl_scope) { idl_scopeElement stack[IDL_MAXSCOPE]; c_char *baseName; c_long scopePointer; }; /* Create a new scope element with the specified name and type */ idl_scopeElement idl_scopeElementNew ( const char *scopeName, idl_scopeType scopeType) { idl_scopeElement element; assert (scopeName); assert (strlen(scopeName)); element = os_malloc ((size_t)C_SIZEOF(idl_scopeElement)); element->scopeName = os_strdup (scopeName); element->scopeType = scopeType; return element; } /* Free a scope element */ void idl_scopeElementFree ( idl_scopeElement element) { assert (element); os_free (element->scopeName); os_free (element); } /* Create a copy of an existing scope element */ idl_scopeElement idl_scopeElementDup ( idl_scopeElement element) { idl_scopeElement new_element; assert (element); new_element = os_malloc ((size_t)C_SIZEOF(idl_scopeElement)); new_element->scopeName = os_strdup (element->scopeName); new_element->scopeType = element->scopeType; return new_element; } /* Return the scope name related to a specific scope element */ c_char * idl_scopeElementName ( idl_scopeElement element) { if (element) { return element->scopeName; } return ""; } /* Return the scope type related to a specific scope element */ idl_scopeType idl_scopeElementType ( idl_scopeElement element) { if (element == NULL) { /* Empty scope stack will deliver NULL scope element */ return idl_tModule; } return element->scopeType; } /* Create a new and empty scope stack, for a specified basename */ idl_scope idl_scopeNew ( const char *baseName) { idl_scope scope = os_malloc ((size_t)C_SIZEOF(idl_scope)); scope->baseName = os_strdup (baseName); scope->scopePointer = -1; return scope; } /* Create a new and empty scope stack, for a specified basename */ idl_scope idl_scopeDup ( idl_scope scope) { idl_scope newScope = idl_scopeNew(idl_scopeBasename(scope)); c_long si; for (si = 0; si < (scope->scopePointer+1); si++) { idl_scopePush (newScope, idl_scopeElementDup(scope->stack[si])); } return newScope; } /* Free a scope stack, also freeing all scope elements */ void idl_scopeFree ( idl_scope scope) { c_long si; assert (scope); for (si = 0; si < (scope->scopePointer+1); si++) { idl_scopeElementFree(scope->stack[si]); } os_free (scope->baseName); os_free (scope); return; } /* Push a scope element on the scope stack */ void idl_scopePush ( idl_scope scope, idl_scopeElement element ) { assert (scope); assert (scope->scopePointer < IDL_MAXSCOPE); assert (element); scope->scopePointer++; scope->stack[scope->scopePointer] = element; } /* Return the size of a scope stack (the amount of scope elements) */ c_long idl_scopeStackSize ( idl_scope scope) { return (scope->scopePointer+1); } /* Remove the top element from a scope stack */ void idl_scopePop ( idl_scope scope) { assert (scope); assert (scope->scopePointer >= 0); scope->scopePointer--; } /* Remove the top element from a scope stack, and free its resources */ void idl_scopePopFree ( idl_scope scope) { assert (scope); assert (scope->scopePointer >= 0); idl_scopeElementFree(scope->stack[scope->scopePointer]); scope->scopePointer--; } /* Return the top element from a scope stack */ idl_scopeElement idl_scopeCur ( idl_scope scope) { assert (scope); assert (scope->scopePointer >= -1); if (scope->scopePointer == -1) { return NULL; } return scope->stack[scope->scopePointer]; } /* Return the element from a scope stack, by index where "index" >= 0 and "index" <= "scopePointer" */ idl_scopeElement idl_scopeIndexed ( idl_scope scope, c_long index) { assert (index >= 0); assert (index <= scope->scopePointer); return scope->stack[index]; } /* Determine if two scope stacks are equal */ c_bool idl_scopeEqual ( idl_scope scope1, idl_scope scope2) { c_long i; /* If the "scopePointer"s are unequal, the stack do not equal */ if (scope1->scopePointer != scope2->scopePointer) { return FALSE; } /* Per stack element compare the names, if any does not equal the stacks are unequal */ for (i = 0; i < (scope1->scopePointer + 1); i++) { if (strcmp(idl_scopeElementName(scope1->stack[i]), idl_scopeElementName(scope2->stack[i])) != 0) { return FALSE; } } return TRUE; } /* Determine if a scope stack is contained by a second stack */ c_bool idl_scopeSub ( idl_scope scope, /* moduleScope */ idl_scope scopeSub) /* keyScope */ { c_long i; /* If the "scopePointer" of the stack is higher than the "scopePointer" of the second stack, the second stack can not contain the first stack */ if (scope->scopePointer > scopeSub->scopePointer) { return FALSE; } /* For all scope elements of the stack with the scope elements of the second stack. If one of them does not equal, the second stack can not contain the first. The scope element types are not compared, this should not a real problem. */ for (i = 0; i < (scope->scopePointer + 1); i++) { if (strcmp(idl_scopeElementName(scope->stack[i]), idl_scopeElementName(scopeSub->stack[i])) != 0) { return FALSE; } } return TRUE; } /* Build a textual representation of a scope stack with a specified seperator and optionally add a user specified identifier */ c_char * idl_scopeStack ( idl_scope scope, const char *scopeSepp, const char *name) { c_long si; c_char *scopeStack; c_char *elName; if (scope && (scope->scopePointer >= 0)) { /* If the stack is not empty */ si = 0; /* copy the first scope element name */ scopeStack = os_strdup (idl_scopeElementName(scope->stack[si])); si++; /* for all scope elements */ while (si <= scope->scopePointer) { elName = idl_scopeElementName(scope->stack[si]); /* allocate space for current scope stack + separator + next scope name */ scopeStack = os_realloc (scopeStack, (size_t)( (int)strlen(scopeStack)+ (int)strlen(scopeSepp)+ (int)strlen(elName)+1)); /* concatinate the separator */ os_strcat (scopeStack, scopeSepp); /* concatinate scope name */ os_strcat (scopeStack, elName); si++; } if (name) { /* if a user identifier is specified, allocate space for current scope stack + separator + user identifier */ scopeStack = os_realloc (scopeStack, (size_t)( (int)strlen(scopeStack)+ (int)strlen(scopeSepp)+ (int)strlen(name)+1)); /* concatinate the separator */ os_strcat (scopeStack, scopeSepp); /* concatinate user identifier */ os_strcat (scopeStack, name); } } else { /* Empty scope stack */ if (name) { /* if a user identifier is specified, copy the user identifier */ scopeStack = os_strdup (name); } else { /* make the scope stack representation empty */ scopeStack = os_strdup(""); } } /* return the scope stack represenation */ return scopeStack; } /* Return the basename related to a scope */ c_char * idl_scopeBasename ( idl_scope scope) { return os_strdup(scope->baseName); }
SanderMertens/opensplice
src/tools/idlpp/code/idl_scope.c
C
gpl-3.0
9,149
#-- # Copyright 2015, 2016, 2017 Huub de Beer <[email protected]> # # This file is part of Paru # # Paru 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. # # Paru 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 Paru. If not, see <http://www.gnu.org/licenses/>. #++ require_relative "./inline.rb" module Paru module PandocFilter # A Subscript inline node class Subscript < Inline end end end
htdebeer/paru
lib/paru/filter/subscript.rb
Ruby
gpl-3.0
874
Exif-Scout ========== The Exif-Scout is a C++ & Qt based GUI for offline searching through the exif-data of images with the power of regular expresions. ![Exif-Scout-GUI](http://timluedtke.de/ablage/Exif-Scout.png) You can select various exiv-data as search parameters and the Exif-Scout searches through your offline media. Exif-Scout is a program I have written as a university-class-project some years ago. I wanted to save it before it gets lost. --project by Tim Luedtke (mail «at» timluedtke dot de) --thanks to S. Steinmann, S. Brueckner, S. Walz, R. Kratou WARNING ======= This project is not yet in a working condition because the makefiles need to be adjusted. As a result of bad makefile generation (by eclipse) the makefiles have the needed directorys hardcoded (e.g. /usr/share/qt4/mkspecs/linux-g++). Therefore it is some work necessary before the project can be compiled for the first time after the years. Sorry for that - but thats over my makefile-knowledge for know... Some help here would be nice. The Exiv2-Library may be needed on you system (http://www.exiv2.org/download.html). FILES ===== Makefile - was once used for comiling in linux Makefile.Debug - was once used for comiling in Windows Makefile.Release - was once used for comiling in Windows exivdata.cpp - file used from the exiv2-library for reading out the exif-data from files LICENCE ======= This project is licensed under the GPLv3. All images used in this project are selfmade by the projects author and licensed under the same license. This project also uses parts of the Exiv2-Library (http://www.exiv2.org/).
hypergnash/Exif-Scout
README.md
Markdown
gpl-3.0
1,628
<?xml version="1.0" encoding="UTF-8"?> <html lang="en" class="no-js ie8"> <!--<![endif]--> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <title> Mein Bookmanager </title> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <link rel="shortcut icon" href="/bookmanager/static/images/favicon.ico" type="image/x-icon"/> <link rel="apple-touch-icon" href="/bookmanager/static/images/apple-touch-icon.png"/> <link rel="apple-touch-icon" sizes="114x114" href="/bookmanager/static/images/apple-touch-icon-retina.png"/> <link rel="stylesheet" href="/bookmanager/static/css/main.css" type="text/css"/> <link rel="stylesheet" href="/bookmanager/static/css/mobile.css" type="text/css"/> <meta name="layout" content="main"/> <style type="text/css" media="screen"> #status { background-color: #eee; border: .2em solid #fff; margin: 2em 2em 1em; padding: 1em; width: 12em; float: left; -moz-box-shadow: 0px 0px 1.25em #ccc; -webkit-box-shadow: 0px 0px 1.25em #ccc; box-shadow: 0px 0px 1.25em #ccc; -moz-border-radius: 0.6em; -webkit-border-radius: 0.6em; border-radius: 0.6em; } .ie6 #status { display: inline; /* float double margin fix http://www.positioniseverything.net/explorer/doubled-margin.html */ } #status ul { font-size: 0.9em; list-style-type: none; margin-bottom: 0.6em; padding: 0; } #status li { line-height: 1.3; } #status h1 { text-transform: uppercase; font-size: 1.1em; margin: 0 0 0.3em; } #page-body { margin: 2em 1em 1.25em 18em; } h2 { margin-top: 1em; margin-bottom: 0.3em; font-size: 1em; } p { line-height: 1.5; margin: 0.25em 0; } #controller-list ul { list-style-position: inside; } #controller-list li { line-height: 1.3; list-style-position: inside; margin: 0.25em 0; } @media screen and (max-width: 480px) { #status { display: none; } #page-body { margin: 0 1em 1em; } #page-body h1 { margin-top: 0; } } </style> </head> <body> <div id="grailsLogo" role="banner"> <a href="http://grails.org"> <img src="/bookmanager/static/images/grails_logo.png" alt="Grails"/> </a> </div> <div class="nav" style="background-color: #9CAD6F;"> <ul> <li> <a href="/bookmanager/" class="home"> Start </a> </li> <li> <a href="/bookmanager/buchsuche/suchmaske" class="list"> Bücher Suche </a> </li> <li> <a href="/bookmanager/buch/index" class="list"> Bücher verwalten </a> </li> <li> <a href="/bookmanager/verlag/index" class="list"> Verlage verwalten </a> </li> <li> <a href="/bookmanager/autor/index" class="list"> Autoren verwalten </a> </li> </ul> </div> <a href="#page-body" class="skip"> Skip to content… </a> <div id="status" role="complementary"> <h1> Status der Anwendung </h1> <ul> <li> App version: 0.1 </li> <li> Grails version: 2.3.5 </li> <li> Groovy version: 2.1.9 </li> <li> JVM version: 1.6.0_27 </li> <li> Reloading active: true </li> <li> Controllers: 8 </li> <li> Domains: 3 </li> <li> Services: 4 </li> <li> Tag Libraries: 13 </li> </ul> <h1> Installierte Plugins </h1> <ul> <li> logging - 2.3.5 </li> <li> i18n - 2.3.5 </li> <li> core - 2.3.5 </li> <li> restResponder - 2.3.5 </li> <li> dataBinding - 2.3.5 </li> <li> resources - 1.2.1 </li> <li> databaseMigration - 1.3.8 </li> <li> webxml - 1.4.1 </li> <li> jquery - 1.10.2.2 </li> <li> codeCoverage - 1.2.7 </li> <li> geb - 0.9.2 </li> <li> spock - 0.7 </li> <li> urlMappings - 2.3.5 </li> <li> servlets - 2.3.5 </li> <li> codecs - 2.3.5 </li> <li> dataSource - 2.3.5 </li> <li> controllers - 2.3.5 </li> <li> functionalTest - 2.0.RC1 </li> <li> mimeTypes - 2.3.5 </li> <li> filters - 2.3.5 </li> <li> domainClass - 2.3.5 </li> <li> controllersAsync - 2.3.5 </li> <li> converters - 2.3.5 </li> <li> hibernate - 3.6.10.7 </li> <li> groovyPages - 2.3.5 </li> <li> validation - 2.3.5 </li> <li> services - 2.3.5 </li> <li> scaffolding - 2.0.1 </li> <li> cache - 1.1.1 </li> <li> buildTestData - 2.1.2 </li> </ul> </div> <div id="page-body" role="main"> <h1> Mein Bookmanager </h1> <p> Congratulations, you have successfully started your first Grails application! At the moment this is the default page, feel free to modify it to either redirect to a controller or display whatever content you may choose. Below is a list of controllers that are currently deployed in this application, click on each to execute its default action: </p> <div id="controller-list" role="navigation"> <h2> Verfügbare Controller: </h2> <ul> <li class="controller"> <a href="/bookmanager/autor/index"> bookmanager.AutorController </a> </li> <li class="controller"> <a href="/bookmanager/buch/index"> bookmanager.BuchController </a> </li> <li class="controller"> <a href="/bookmanager/buchsuche/index"> bookmanager.BuchsucheController </a> </li> <li class="controller"> <a href="/bookmanager/home/index"> bookmanager.HomeController </a> </li> <li class="controller"> <a href="/bookmanager/verlag/index"> bookmanager.VerlagController </a> </li> <li class="controller"> <a href="/bookmanager/functionaltesting/index"> com.grailsrocks.functionaltest.controllers.FunctionalTestDataAccessController </a> </li> <li class="controller"> <a href="/bookmanager/selfTest/paramecho"> com.grailsrocks.functionaltest.controllers.test.SelfTestController </a> </li> <li class="controller"> <a href="/bookmanager/dbdoc"> grails.plugin.databasemigration.DbdocController </a> </li> </ul> </div> </div> <div class="footer" role="contentinfo"> © 2009 - 2014 - exensio GmbH - Version 0.1 </div> <div id="spinner" class="spinner" style="display:none;"> Loading… </div> <script src="/bookmanager/static/js/application.js" type="text/javascript"> </script> </body> </html>
gitRigge/bookmanager
test/target/geb-reports/bookmanager/BookManageSpec/001-001-Test German Home Page-end.html
HTML
gpl-3.0
8,177
# -*- coding: utf-8 -*- ################################################################################ # Copyright 2014, Distributed Meta-Analysis System ################################################################################ """Software structure for generating Monte-Carlo collections of results. NOTE: Highest resolution regions are implicitly assumed to be FIPS-coded counties, but the logic does not require them to be. FIPS language should be replaced with generic ID references. A key structure is the make_generator(fips, times, values) function. make_generator is passed to the functions that iterate through different weather forecasts, such as make_tar_ncdf. It is then called with each location and daily weather data. fips is a single county code, times is a list of yyyyddd formated date values, values is a list of weather values. The output of make_generator() is a generator, producing tuples (year, effect), for whichever years an effect can be computed. Output file structure: Each bundle of output impact results of a given type and for a given weather forecast are in a gzipped tar file containing a single directory <name>, containing a separate csv file (an effect file) for each region. The format of the csv file is: year,<label>[,<other labels>]* <year>,<impact>[,<prior calculated impact>]* Basic processing logic: Some functions, like find_ncdfs_allreal, discover collections of forecasted variables (within the WDS directory structure), and provide through enumerators. Variable collections are dictionaries {variable: REFERENCE}, where REFERENCE may be a filename, a netCDF, or a dictionary of {original: netCDF object, data: [days x counties], times: [yyyyddd]}. [VRD] Controllers (elsewhere) loop through these, and for each available forecast call a make_tar_* function passing in a make_generator function. The make_tar_* functions call make_generator with each individual region, retrieving a set of results, and then package those results into the output file format. Temporary directories (characterized by random letters) are used to hold the results as they're being generated (before being bundled into tars). """ __copyright__ = "Copyright 2014, Distributed Meta-Analysis System" __author__ = "James Rising" __credits__ = ["James Rising"] __maintainer__ = "James Rising" __email__ = "[email protected]" __status__ = "Production" __version__ = "$Revision$" # $Source$ import tarfile, os, csv, re, random, string import numpy as np try: # this is required for nc4's, but we can wait to fail from netCDF4 import Dataset except: pass FIPS_COMPLETE = '__complete__' # special FIPS code for the last county LATEX_STRING = '__latexstr__' # special FIPS code for making a LaTeX representation ### Effect Bundle Generation ## Temporary directory management def enter_local_tempdir(prefix=''): """Create and set the working directory as a new temporary directory. Returns the name of the temporary directory (to be passed to exit_local_tempdir). """ suffix = ''.join(random.choice(string.lowercase) for i in range(6)) os.mkdir(prefix + suffix) os.chdir(prefix + suffix) return prefix + suffix def exit_local_tempdir(tempdir, killit=True): """Return to the root output directory (and optionally delete the temporary directory). tempdir is the output of enter_local_tempdir. """ os.chdir("..") if killit: kill_local_tempdir(tempdir) def kill_local_tempdir(tempdir): """Remove all contents of a temporary directory. Call after exit_local_tempdir is called, only if killit=False. """ os.system("rm -r " + tempdir) ## General helper functions for creation def send_fips_complete(make_generator): """Call after the last county of a loop of counties, to clean up any memory. """ print "Complete the FIPS" try: iterator = make_generator(FIPS_COMPLETE, None, None).next() print "Success" except StopIteration, e: pass except Exception, e: print e pass def get_target_path(targetdir, name): """Helper function to use the targetdir directory if its provided. """ if targetdir is not None: return os.path.join(targetdir, name) else: return name def write_effect_file(path, fips, generator, collabel): """Write the effects for a single FIPS-coded county. path: relative path for file fips: the unique id of the region generator: a enumerator of tuples/lists with individual rows collabel: label for one (string) or more (list) columns after the year column """ # Create the CSV file with open(os.path.join(path, fips + '.csv'), 'wb') as csvfp: writer = csv.writer(csvfp, quoting=csv.QUOTE_MINIMAL) # Write the header row if not isinstance(collabel, list): writer.writerow(["year", collabel]) else: writer.writerow(["year"] + collabel) # Write all data rows for values in generator: writer.writerow(values) ## Top-level bundle creation functions def make_tar_dummy(name, acradir, make_generator, targetdir=None, collabel="fraction"): """Constructs a tar of files for each county, using NO DATA. Calls make_generator for each county, using a filename of counties. name: the name of the effect bundle. acradir: path to the DMAS acra directory. make_generator(fips, times, daily): returns an iterator of (year, effect). targetdir: path to a final destination for the bundle collabel: the label for the effect column """ tempdir = enter_local_tempdir() os.mkdir(name) # directory for county files # Generate a effect file for each county in regionsA with open(os.path.join(acradir, 'regions/regionsANSI.csv')) as countyfp: reader = csv.reader(countyfp) reader.next() # ignore header # Each row is a county for row in reader: fips = canonical_fips(row[0]) print fips # Call generator (with no data) generator = make_generator(fips, None, None) if generator is None: continue # Construct the effect file write_effect_file(name, fips, generator, collabel) send_fips_complete(make_generator) # Generate the bundle tar target = get_target_path(targetdir, name) os.system("tar -czf " + os.path.join("..", target) + ".tar.gz " + name) # Remove the working directory exit_local_tempdir(tempdir) def make_tar_duplicate(name, filepath, make_generator, targetdir=None, collabel="fraction"): """Constructs a tar of files for each county that is described in an existing bundle. Passes NO DATA to make_generator. name: the name of the effect bundle. filepath: path to an existing effect bundle make_generator(fips, times, daily): returns an iterator of (year, effect). targetdir: path to a final destination for the bundle collabel: the label for the effect column """ tempdir = enter_local_tempdir() os.mkdir(name) # Iterate through all FIPS-titled files in the effect bundle with tarfile.open(filepath) as tar: for item in tar.getnames()[1:]: fips = item.split('/')[1][0:-4] print fips # Call make_generator with no data generator = make_generator(fips, None, None) if generator is None: continue # Construct the effect file write_effect_file(name, fips, generator, collabel) send_fips_complete(make_generator) # Generate the bundle tar target = get_target_path(targetdir, name) os.system("tar -czf " + os.path.join("..", target) + ".tar.gz " + name) # Remove the working directory exit_local_tempdir(tempdir) def make_tar_ncdf(name, weather_ncdf, var, make_generator, targetdir=None, collabel="fraction"): """Constructs a tar of files for each county, describing yearly results. name: the name of the effect bundle. weather_ncdf: str for one, or {variable: filename} for calling generator with {variable: data}. var: str for one, or [str] for calling generator with {variable: data} make_generator(fips, times, daily): returns an iterator of (year, effect). targetdir: path to a final destination for the bundle, or a function to take the data collabel: the label for the effect column """ # If this is a function, we just start iterating if hasattr(targetdir, '__call__'): call_with_generator(name, weather_ncdf, var, make_generator, targetdir) return # Create the working directory tempdir = enter_local_tempdir() os.mkdir(name) # Helper function for calling write_effect_file with collabel def write_csv(name, fips, generator): write_effect_file(name, fips, generator, collabel) # Iterate through the data call_with_generator(name, weather_ncdf, var, make_generator, write_csv) # Create the effect bundle target = get_target_path(targetdir, name) os.system("tar -czf " + os.path.join("..", target) + ".tar.gz " + name) # Remove the working directory exit_local_tempdir(tempdir) def yield_given(name, yyyyddd, weather, make_generator): """Yields (as an iterator) rows of the result of applying make_generator to the given weather. name: the name of the effect bundle. yyyyddd: YYYYDDD formated date values. weather: a dictionary to call generator with {variable: data}. make_generator(fips, times, daily): returns an iterator of (year, effect). """ generator = make_generator(0, yyyyddd, weather) if generator is None: return # Call targetfunc with the result for values in generator: yield values # Signal the end of the counties send_fips_complete(make_generator) def call_with_generator(name, weather_ncdf, var, make_generator, targetfunc): """Helper function for calling make_generator with each variable set. In cases with multiple weather datasets, assumes all use the same clock (sequence of times) and geography (sequence of counties). name: the name of the effect bundle. weather_ncdf: str for one, or {variable: filename} for calling generator with {variable: data}. var: str for one, or [str] for calling generator with {variable: data} make_generator(fips, times, daily): returns an iterator of (year, effect). targetfunc: function(name, fips, generator) to handle results """ if isinstance(weather_ncdf, dict) and isinstance(var, list): # In this case, we generate a dictionary of variables weather = {} times = None # All input assumed to have same clock # Filter by the variables in var for variable in var: # Retrieve the netcdf object (rootgrp) and add to weather dict if isinstance(weather_ncdf[variable], str): # Open this up as a netCDF and read data into array rootgrp = Dataset(weather_ncdf[variable], 'r+', format='NETCDF4') weather[variable] = rootgrp.variables[variable][:,:] elif isinstance(weather_ncdf[variable], dict): # This is an {original, data, times} dictionary rootgrp = weather_ncdf[variable]['original'] weather[variable] = weather_ncdf[variable]['data'] if 'times' in weather_ncdf[variable]: times = weather_ncdf[variable]['times'] else: # This is already a netcdf object rootgrp = weather_ncdf[variable] weather[variable] = rootgrp.variables[variable][:,:] # Collect additional information from netcdf object counties = rootgrp.variables['fips'] lats = rootgrp.variables['lat'] lons = rootgrp.variables['lon'] if times is None: times = rootgrp.variables['time'] else: # We just want a single variable (not a dictionary of them) # Retrieve the netcdf object (rootgrp) and add to weather dict if isinstance(weather_ncdf, str): # Open this up as a netCDF and read into array rootgrp = Dataset(weather_ncdf, 'r+', format='NETCDF4') weather = rootgrp.variables[var][:,:] elif isinstance(weather_ncdf, dict): # This is an {original, data, times} dictionary rootgrp = weather_ncdf['original'] weather = weather_ncdf['data'] else: # This is already a netcdf object rootgrp = weather_ncdf weather = rootgrp.variables[var][:,:] # Collect additional information from netcdf object counties = rootgrp.variables['fips'] lats = rootgrp.variables['lat'] lons = rootgrp.variables['lon'] times = rootgrp.variables['time'] # Loop through counties, calling make_generator with each for ii in range(len(counties)): fips = canonical_fips(counties[ii]) print fips # Extract the weather just for this county if not isinstance(weather, dict): daily = weather[:,ii] else: daily = {} for variable in weather: daily[variable] = weather[variable][:,ii] # Call make_generator for this county generator = make_generator(fips, times, daily, lat=lats[ii], lon=lons[ii]) if generator is None: continue # Call targetfunc with the result targetfunc(name, fips, generator) # Signal the end of the counties send_fips_complete(make_generator) def make_tar_ncdf_profile(weather_ncdf, var, make_generator): """Like make_tar_ncdf, except that just goes through the motions, and only for 100 counties weather_ncdf: str for one, or {variable: filename} for calling generator with {variable: data}. var: str for one, or [str] for calling generator with {variable: data} """ # Open a single netCDF if only one filename passed in if isinstance(weather_ncdf, str): # Collect the necessary info rootgrp = Dataset(weather_ncdf, 'r+', format='NETCDF4') counties = rootgrp.variables['fips'] lats = rootgrp.variables['lat'] lons = rootgrp.variables['lon'] times = rootgrp.variables['time'] weather = rootgrp.variables[var][:,:] else: # Open all netCDF referenced in var weather = {} # Construct a dictionary of [yyyyddd x county] arrays for variable in var: rootgrp = Dataset(weather_ncdf[variable], 'r+', format='NETCDF4') counties = rootgrp.variables['fips'] lats = rootgrp.variables['lat'] lons = rootgrp.variables['lon'] times = rootgrp.variables['time'] weather[variable] = rootgrp.variables[variable][:,:] # Just do 100 counties for ii in range(100): # Always using 5 digit fips fips = canonical_fips(counties[ii]) print fips # Construct the input array for this county if not isinstance(weather, dict): daily = weather[:,ii] else: daily = {} for variable in weather: daily[variable] = weather[variable][:,ii] # Generate the generator generator = make_generator(fips, times, daily, lat=lats[ii], lon=lons[ii]) if generator is None: continue # Just print out the results print "year", "fraction" for (year, effect) in generator: print year, effect ### Effect calculation functions ## make_generator functions def load_tar_make_generator(targetdir, name, column=None): """Load existing data for additional calculations. targetdir: relative path to a directory of effect bundles. name: the effect name (so the effect bundle is at <targetdir>/<name>.tar.gz """ # Extract the existing tar into a loader tempdir tempdir = enter_local_tempdir('loader-') os.system("tar -xzf " + os.path.join("..", targetdir, name + ".tar.gz")) exit_local_tempdir(tempdir, killit=False) def generate(fips, yyyyddd, temps, *args, **kw): # When all of the counties are done, kill the local dir if fips == FIPS_COMPLETE: print "Remove", tempdir # We might be in another tempdir-- check if os.path.exists(tempdir): kill_local_tempdir(tempdir) else: kill_local_tempdir(os.path.join('..', tempdir)) return # Open up the effect for this bundle fipspath = os.path.join(tempdir, name, fips + ".csv") if not os.path.exists(fipspath): fipspath = os.path.join('..', fipspath) if not os.path.exists(fipspath): # If we can't find this, just return a single year with 0 effect print fipspath + " doesn't exist" yield (yyyyddd[0] / 1000, 0) raise StopIteration() with open(fipspath) as fp: reader = csv.reader(fp) reader.next() # ignore header # yield the same values that generated this effect file for row in reader: if column is None: yield [int(row[0])] + map(float, row[1:]) else: yield (int(row[0]), float(row[column])) return generate ### Aggregation from counties to larger regions def aggregate_tar(name, scale_dict=None, targetdir=None, collabel="fraction", get_region=None, report_all=False): """Aggregates results from counties to larger regions. name: the name of an impact, already constructed into an effect bundle scale_dict: a dictionary of weights, per county targetdir: directory holding both county bundle and to hold region bundle collabel: Label for result column(s) get_region: either None (uses first two digits of FIPS-- aggregates to state), True (combine all counties-- aggregate to national), or a function(fips) => code which aggregates each set of counties producing the same name report_all: if true, include a whole sequence of results; otherwise, just take first one """ # Get a region name and a get_region function region_name = 'region' # final bundle will use this as a suffix if get_region is None: # aggregate to state get_region = lambda fips: fips[0:2] region_name = 'state' elif get_region is True: # aggregate to nation get_region = lambda fips: 'national' region_name = 'national' else: # get a title, if get_region returns one for dummy-fips "_title_" try: title = get_region('_title_') if title is not None: region_name = title except: pass regions = {} # {region code: {year: (numer, denom)}} # This is the effect bundle to aggregate target = get_target_path(targetdir, name) # Generate a temporary directory to extract county results tempdir = enter_local_tempdir() # Extract all of the results os.system("tar -xzf " + os.path.join("..", target) + ".tar.gz") # Go through all counties for filename in os.listdir(name): # If this is a county file match = re.match(r'(\d{5})\.csv', filename) if match: code = match.groups(1)[0] # get the FIPS code # Check that it's in the scale_dict if scale_dict is not None and code not in scale_dict: continue # Check which region it is in region = get_region(code) if region is None: continue # Prepare the dictionary of results for this region, if necessary if region not in regions: regions[region] = {} # year => (numer, denom) # Get out the current dictioanry of years years = regions[region] # Go through every year in this effect file with open(os.path.join(name, filename)) as csvfp: reader = csv.reader(csvfp, delimiter=',') reader.next() if report_all: # Report entire sequence of results for row in reader: # Get the numerator and denominator for this weighted sum if row[0] not in years: numer, denom = (np.array([0] * (len(row)-1)), 0) else: numer, denom = years[row[0]] # Add on one more value to the weighted sum try: numer = numer + np.array(map(float, row[1:])) * (scale_dict[code] if scale_dict is not None else 1) denom = denom + (scale_dict[code] if scale_dict is not None else 1) except Exception, e: print e # Put the weighted sum calculation back in for this year years[row[0]] = (numer, denom) else: # Just report the first result for row in reader: # Get the numerator and denominator for this weighted sum if row[0] not in years: numer, denom = (0, 0) else: numer, denom = years[row[0]] # Add on one more value to the weighted sum numer = numer + float(row[1]) * (scale_dict[code] if scale_dict is not None else 1) denom = denom + (scale_dict[code] if scale_dict is not None else 1) # Put the weighted sum calculation back in for this year years[row[0]] = (numer, denom) # Remove all county results from extracted tar os.system("rm -r " + name) # Start producing directory of region results dirregion = name + '-' + region_name if not os.path.exists(dirregion): os.mkdir(dirregion) # For each region that got a result for region in regions: # Create a new CSV effect file with open(os.path.join(dirregion, region + '.csv'), 'wb') as csvfp: writer = csv.writer(csvfp, quoting=csv.QUOTE_MINIMAL) # Include a header row if not isinstance(collabel, list): writer.writerow(["year", collabel]) else: writer.writerow(["year"] + collabel) # Construct a sorted list of years from the keys of this region's dictionary years = map(str, sorted(map(int, regions[region].keys()))) # For each year, output the weighted average for year in years: if regions[region][year][1] == 0: # the denom is 0-- never got a value writer.writerow([year, 'NA']) else: # Write out the year's result if report_all: writer.writerow([year] + list(regions[region][year][0] / float(regions[region][year][1]))) else: writer.writerow([year, float(regions[region][year][0]) / regions[region][year][1]]) # Construct the effect bundle target = get_target_path(targetdir, dirregion) os.system("tar -czf " + os.path.join("..", target) + ".tar.gz " + dirregion) # Clean up temporary directory exit_local_tempdir(tempdir)
jrising/open-estimate
openest/generate/v1/effectset.py
Python
gpl-3.0
23,746
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Forms.Options; using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic.VideoPlayers; using System; using System.Text; using System.Windows.Forms; namespace Nikse.SubtitleEdit.Forms { public partial class VideoError : Form { public VideoError() { UiUtil.PreInitialize(this); InitializeComponent(); UiUtil.FixFonts(this); UiUtil.FixLargeFonts(this, buttonCancel); } public void Initialize(string fileName, Exception exception) { var sb = new StringBuilder(); sb.AppendLine("There seems to be missing a codec (or file is not a valid video/audio file)!"); sb.AppendLine(); var currentVideoPlayer = Configuration.Settings.General.VideoPlayer; var isLibMpvInstalled = LibMpvDynamic.IsInstalled; if (currentVideoPlayer == "MPV" && !isLibMpvInstalled) { currentVideoPlayer = "DirectShow"; } if (currentVideoPlayer == "VLC" && !LibVlcDynamic.IsInstalled) { currentVideoPlayer = "DirectShow"; } if (Configuration.IsRunningOnLinux) { sb.AppendLine("Try installing latest version of libmpv and libvlc!"); sb.Append("Read more about Subtitle Edit on Linux here: https://nikse.dk/SubtitleEdit/Help#linux"); } else if (currentVideoPlayer == "DirectShow") { sb.AppendLine("Try installing/updating \"LAV Filters - DirectShow Media Splitter and Decoders\": https://github.com/Nevcairiel/LAVFilters/releases"); sb.Append("Note that Subtitle Edit is a " + IntPtr.Size * 8 + "-bit program, and hence requires " + IntPtr.Size * 8 + "-bit codecs!"); sb.AppendLine(); } else if (currentVideoPlayer == "VLC") { sb.AppendLine("VLC media player was unable to play this file (perhaps it's not a valid video/audio file) - you can change video player via Options -> Settings -> Video Player"); sb.AppendLine("Latest version of VLC is available here: http://www.videolan.org/vlc/ (get the " + IntPtr.Size * 8 + "-bit version!)"); sb.AppendLine(); } else if (currentVideoPlayer == "MPV" && Configuration.IsRunningOnWindows) { sb.AppendLine("You can re-download mpv or change video player via Options -> Settings -> Video Player"); sb.AppendLine(); } richTextBoxMessage.Text = sb.ToString(); if (!Configuration.IsRunningOnWindows || currentVideoPlayer == "MPV") { buttonMpvSettings.Visible = false; labelMpvInfo.Visible = false; } else if (currentVideoPlayer != "MPV") { labelMpvInfo.Text = $"You could also switch video player from \"{currentVideoPlayer}\" to \"mpv\"."; if (isLibMpvInstalled) { buttonMpvSettings.Text = "Use \"mpv\" as video player"; } } if (exception != null) { var source = string.Empty; if (!string.IsNullOrEmpty(exception.Source)) { source = "Source: " + exception.Source.Trim() + Environment.NewLine + Environment.NewLine; } textBoxError.Text = "Message: " + exception.Message.Trim() + Environment.NewLine + source + "Stack Trace: " + Environment.NewLine + exception.StackTrace.Trim(); } Text += fileName; } private void VideoError_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { DialogResult = DialogResult.Cancel; } } private void richTextBoxMessage_LinkClicked(object sender, LinkClickedEventArgs e) { UiUtil.OpenUrl(e.LinkText); } private void buttonMpvSettings_Click(object sender, EventArgs e) { if (LibMpvDynamic.IsInstalled) { Configuration.Settings.General.VideoPlayer = "MPV"; DialogResult = DialogResult.OK; return; } using (var form = new SettingsMpv(true)) { if (form.ShowDialog(this) == DialogResult.OK) { Configuration.Settings.General.VideoPlayer = "MPV"; DialogResult = DialogResult.OK; } } } } }
ivandrofly/subtitleedit
src/ui/Forms/VideoError.cs
C#
gpl-3.0
4,893
var __v=[ { "Id": 3568, "Panel": 1763, "Name": "紋理動畫", "Sort": 0, "Str": "" }, { "Id": 3569, "Panel": 1763, "Name": "相關API", "Sort": 0, "Str": "" }, { "Id": 3570, "Panel": 1763, "Name": "Example", "Sort": 0, "Str": "" } ]
zuiwuchang/king-document
data/panels/1763.js
JavaScript
gpl-3.0
291
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (version 1.7.0_25) on Mon Dec 09 13:16:02 CET 2013 --> <title>m0.main</title> <meta name="date" content="2013-12-09"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../m0/main/package-summary.html" target="classFrame">m0.main</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="IRemoteConfiguration.html" title="interface in m0.main" target="classFrame"><i>IRemoteConfiguration</i></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="ClientLauncher.html" title="class in m0.main" target="classFrame">ClientLauncher</a></li> <li><a href="RemoteConfiguration.html" title="class in m0.main" target="classFrame">RemoteConfiguration</a></li> <li><a href="ServerLauncher.html" title="class in m0.main" target="classFrame">ServerLauncher</a></li> </ul> </div> </body> </html>
nemolovich/HADL
doc/m0/main/package-frame.html
HTML
gpl-3.0
1,109
/* Zik2ctl * Copyright (C) 2015 Aurélien Zanelli <[email protected]> * * Zik2ctl is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Zik2ctl is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Zik2ctl. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ZIK_API_H #define ZIK_API_H /* Audio */ #define ZIK_API_AUDIO_EQUALIZER_ENABLED_PATH "/api/audio/equalizer/enabled" #define ZIK_API_AUDIO_NOISE_PATH "/api/audio/noise" #define ZIK_API_AUDIO_NOISE_CONTROL_PATH "/api/audio/noise_control" #define ZIK_API_AUDIO_NOISE_CONTROL_ENABLED_PATH "/api/audio/noise_control/enabled" #define ZIK_API_AUDIO_NOISE_CONTROL_AUTO_NC_PATH "/api/audio/noise_control/auto_nc" #define ZIK_API_AUDIO_NOISE_CONTROL_PHONE_MODE_PATH "/api/audio/noise_control/phone_mode" #define ZIK_API_AUDIO_PRESET_BYPASS_PATH "/api/audio/preset/bypass" #define ZIK_API_AUDIO_PRESET_CURRENT_PATH "/api/audio/preset/current" #define ZIK_API_AUDIO_SMART_AUDIO_TUNE_PATH "/api/audio/smart_audio_tune" #define ZIK_API_AUDIO_SOUND_EFFECT_PATH "/api/audio/sound_effect" #define ZIK_API_AUDIO_SOUND_EFFECT_ENABLED_PATH "/api/audio/sound_effect/enabled" #define ZIK_API_AUDIO_SOUND_EFFECT_ROOM_SIZE_PATH "/api/audio/sound_effect/room_size" #define ZIK_API_AUDIO_SOUND_EFFECT_ANGLE_PATH "/api/audio/sound_effect/angle" #define ZIK_API_AUDIO_SOURCE_PATH "/api/audio/source" #define ZIK_API_AUDIO_THUMB_EQUALIZER_VALUE_PATH "/api/audio/thumb_equalizer/value" #define ZIK_API_AUDIO_TRACK_METADATA_PATH "/api/audio/track/metadata" #define ZIK_API_AUDIO_VOLUME_PATH "/api/audio/volume" /* Bluetooth */ #define ZIK_API_BLUETOOTH_FRIENDLY_NAME_PATH "/api/bluetooth/friendlyname" /* Software */ #define ZIK_API_SOFTWARE_VERSION_PATH "/api/software/version" #define ZIK_API_SOFTWARE_TTS_PATH "/api/software/tts" /* System */ #define ZIK_API_SYSTEM_ANC_PHONE_MODE_ENABLED_PATH "/api/system/anc_phone_mode/enabled" #define ZIK_API_SYSTEM_AUTO_CONNECTION_ENABLED_PATH "/api/system/auto_connection/enabled" #define ZIK_API_SYSTEM_BATTERY_PATH "/api/system/battery" #define ZIK_API_SYSTEM_BATTERY_FORECAST_PATH "/api/system/battery/forecast" #define ZIK_API_SYSTEM_COLOR_PATH "/api/system/color" #define ZIK_API_SYSTEM_DEVICE_TYPE_PATH "/api/system/device_type" #define ZIK_API_SYSTEM_FLIGHT_MODE_PATH "/api/flight_mode" #define ZIK_API_SYSTEM_HEAD_DETECTION_ENABLED_PATH "/api/system/head_detection/enabled" #define ZIK_API_SYSTEM_PI_PATH "/api/system/pi" #define ZIK_API_SYSTEM_AUTO_POWER_OFF_PATH "/api/system/auto_power_off" /* Other */ #define ZIK_API_FLIGHT_MODE_PATH "/api/flight_mode" #endif
kradhub/zik2ctl
src/zikapi.h
C
gpl-3.0
3,043
<?php class WP_Gist { /* Properties ---------------------------------------------------------------------------------- */ /** * Instance of the class. * * @var WP_Gist */ protected static $instance = null; /** * Class slug. * * @var string */ protected $slug = 'wp-gist'; /** * Class version. * * Used for cache-busting of style and script file references. */ protected $version = '3.1.0'; /* Public ---------------------------------------------------------------------------------- */ /** * Gets instance of class. * * @return WP_Gist Instance of the class. */ public static function get_instance() { if ( null == self::$instance ) { self::$instance = new self; } return self::$instance; } /** * Gets slug. * * @return string Slug. */ public function get_slug() { return $this->slug; } /** * Gets version. * * @return string Version. */ public function get_version() { return $this->version; } }
manovotny/wp-gist
src/classes/class-wp-gist.php
PHP
gpl-3.0
1,164
adafruit_lcd_menu ================= a menu system to control the raspberry py with the adafruit lcd plate
djo938/adafruit_lcd_menu
README.md
Markdown
gpl-3.0
107
<?php // Clear variables $boardGameError = ""; $boardGameAvailable = ""; // Get the playerID, if null return user to the available page $playerID = null; if (!empty($_GET['playerID'])) { $playerID = $_REQUEST['playerID']; } if ( null==$playerID ) { header("Location: ../available.php"); } if ($_SERVER["REQUEST_METHOD"] == "POST") { $valid = true; if (empty($_POST["boardGameAvailable"])) { $boardGameError = "Board game name is required"; $valid = false; } else { $boardGameAvailable = validate_input($_POST["boardGameAvailable"]); // Check if first name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$boardGameAvailable)) { $boardGameError = "Only letters and white space allowed"; $valid = false; } } } // The database will only be connected to if PHP deems that the input is valid // Connect to DB and add player details if ($valid) { $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO gamesavailable (boardGameAvailable, playerID) values(?, ?)"; $q = $pdo->prepare($sql); $q->execute(array($boardGameAvailable, $playerID)); Database::disconnect(); header("Location: ../available.php"); } // Validate and return input function validate_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>
twominutesalad/PDOBoardGameClub
upload/available/validate_add_available.php
PHP
gpl-3.0
1,457
var events = require('events'), koanize = require('koanizer'), util = require('util'); koanize(this); // Standard and RFC set these values var REFERENCE_CLOCK_FREQUENCY = 90000; // RTP packet constants and masks var RTP_HEADER_SIZE = 12; var RTP_FRAGMENTATION_HEADER_SIZE = 4; var SAMPLES_PER_FRAME = 1152; // ISO 11172-3 var SAMPLING_FREQUENCY = 44100; var TIMESTAMP_DELTA = Math.floor(SAMPLES_PER_FRAME * REFERENCE_CLOCK_FREQUENCY / SAMPLING_FREQUENCY); var SECONDS_PER_FRAME = SAMPLES_PER_FRAME / SAMPLING_FREQUENCY; var RTPProtocol = function(){ events.EventEmitter.call(this); this.setMarker = false; this.ssrc = Math.floor(Math.random() * 100000); this.seqNum = Math.floor(Math.random() * 1000); this.timestamp = Math.floor(Math.random() * 1000); }; util.inherits(RTPProtocol, events.EventEmitter); RTPProtocol.prototype.pack = function(payload){ ++this.seqNum; // RFC3550 says it must increase by the number of samples // sent in a block in case of CBR audio streaming this.timestamp += TIMESTAMP_DELTA; if (!payload) { // Tried to send a packet, but packet was not ready. // Timestamp and Sequence Number should be increased // anyway 'cause interval callback was called and // that's like sending silence this.setMarker = true; return; } var RTPPacket = new Buffer(RTP_HEADER_SIZE + RTP_FRAGMENTATION_HEADER_SIZE + payload.length); // version = 2: 10 // padding = 0: 0 // extension = 0: 0 // CRSCCount = 0: 0000 /* KOAN #1 should write Version, Padding, Extension and Count */ RTPPacket.writeUInt8(128, 0); // Marker = 0: 0 // RFC 1890: RTP Profile for Audio and Video Conferences with Minimal Control // Payload = 14: (MPEG Audio Only) 0001110 RTPPacket.writeUInt8(this.setMarker? 142 : 14, 1); this.setMarker = false; // SequenceNumber /* KOAN #2 should write Sequence Number */ RTPPacket.writeUInt16BE(this.seqNum, 2); // Timestamp /* KOAN #3 should write Timestamp... */ RTPPacket.writeUInt32BE(this.timestamp, 4); // SSRC /* KOAN #3 ...SSRC and... */ RTPPacket.writeUInt32BE(this.ssrc, 8); // RFC 2250: RTP Payload Format for MPEG1/MPEG2 Video // 3.5 MPEG Audio-specific header /* KOAN #3 ...payload Format */ RTPPacket.writeUInt32BE(0, 12); payload.copy(RTPPacket, 16); this.emit('packet', RTPPacket); //return RTPPacket; }; module.exports = exports.RTPProtocol = RTPProtocol;
rfines/NodeKoans
2_dgram/buffer-koans.js
JavaScript
gpl-3.0
2,619
<?php /** * @author Pierre-Henry Soria <[email protected]> * @copyright (c) 2012-2015, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / Affiliate / Controller */ namespace PH7; class HomeController extends Controller { private $sTitle; public function __construct() { parent::__construct(); /** Predefined meta_description and keywords tags **/ $this->view->meta_description = t('Become an Affiliate with the affiliate dating community platform %site_name%'); $this->view->meta_keywords = t('affiliate,dating,dating site,social network,pay per click affiliate program, affiliate program'); } public function index() { $this->view->page_title = t('Affiliate Platform with %site_name%! Dating Social Affiliate'); $this->view->h1_title = t('Affiliate Platform - %site_name%'); if (Affiliate::auth()) $this->view->h3_title = t('Hello <em>%0%</em>, welcome to your site!', $this->session->get('affiliate_first_name')); if (!Affiliate::auth()) $this->design->addCss(PH7_LAYOUT . PH7_SYS . PH7_MOD . $this->registry->module . PH7_SH . PH7_TPL . PH7_TPL_MOD_NAME . PH7_SH . PH7_CSS, 'style.css'); $this->output(); } public function login() { $this->sTitle = t('Login Affiliate'); $this->view->page_title = $this->sTitle; $this->view->meta_description = $this->sTitle; $this->view->h1_title = $this->sTitle; $this->output(); } public function resendActivation() { $this->sTitle = t('Resend activation email'); $this->view->page_title = $this->sTitle; $this->view->h2_title = $this->sTitle; $this->output(); } public function logout() { (new Affiliate)->logout(); } }
erichilarysmithsr/pH7-Social-Dating-CMS
_protected/app/system/modules/affiliate/controllers/HomeController.php
PHP
gpl-3.0
1,983
// // AppDelegate.h // Pedigree // // Created by user on 12.09.13. // Copyright (c) 2013 user. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
AppleLab/Pedigree-training
Pedigree/Pedigree/AppDelegate.h
C
gpl-3.0
265
from abc import ABC import configargparse from sklearn.externals import joblib from termcolor import colored class ScikitBase(ABC): """ Base class for AI strategies """ arg_parser = configargparse.get_argument_parser() arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True) arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)') pipeline = None def __init__(self): args = self.arg_parser.parse_known_args()[0] super(ScikitBase, self).__init__() self.pipeline = self.load_pipeline(args.pipeline) if args.feature_names: self.feature_names = self.load_pipeline(args.feature_names) @staticmethod def load_pipeline(pipeline_file): """ Loads scikit model/pipeline """ print(colored('Loading pipeline: ' + pipeline_file, 'green')) return joblib.load(pipeline_file) def fetch_pipeline_from_server(self): """ Method fetches pipeline from server/cloud """ # TODO pass def predict(self, df): """ Returns predictions based on the model/pipeline """ try: return self.pipeline.predict(df) except (ValueError, TypeError): print(colored('Got ValueError while using scikit model.. ', 'red')) return None
miti0/mosquito
strategies/ai/scikitbase.py
Python
gpl-3.0
1,418
package com.octagon.airships.block; import com.octagon.airships.reference.Reference; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; public abstract class AirshipsBlock extends Block { public AirshipsBlock(Material material) { super(material); } public AirshipsBlock() { this(Material.rock); } @Override public String getUnlocalizedName() { return String.format("tile.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister iconRegister) { blockIcon = iconRegister.registerIcon(String.format("%s", getUnwrappedUnlocalizedName(this.getUnlocalizedName()))); } protected String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } }
Todkommt/Mass-Effect-Ships-Mod
src/main/java/com/octagon/airships/block/AirshipsBlock.java
Java
gpl-3.0
1,152
#include "simple_form_widget.h" #include "ui_simple_form_widget.h" SimpleFormWidget::SimpleFormWidget(QWidget *parent) : QWidget(parent), ui(new Ui::SimpleFormWidget) { ui->setupUi(this); } SimpleFormWidget::~SimpleFormWidget() { delete ui; }
zflat/Receptacle
test/example_plugins/example_util09_SimpleForm/simple_form_widget.cpp
C++
gpl-3.0
261
package itaf.WsUserTakeDeliveryAddressService; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the itaf.WsUserTakeDeliveryAddressService package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private static final QName _DeleteByIdResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "deleteByIdResponse"); private static final QName _GetById_QNAME = new QName("itaf.framework.ws.server.consumer", "getById"); private static final QName _SaveOrUpdateResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "saveOrUpdateResponse"); private static final QName _FindListByUserIdResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "findListByUserIdResponse"); private static final QName _GetByIdResponse_QNAME = new QName("itaf.framework.ws.server.consumer", "getByIdResponse"); private static final QName _FindListByUserId_QNAME = new QName("itaf.framework.ws.server.consumer", "findListByUserId"); private static final QName _DeleteById_QNAME = new QName("itaf.framework.ws.server.consumer", "deleteById"); private static final QName _SaveOrUpdate_QNAME = new QName("itaf.framework.ws.server.consumer", "saveOrUpdate"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: itaf.WsUserTakeDeliveryAddressService * */ public ObjectFactory() { } /** * Create an instance of {@link FindListByUserId } * */ public FindListByUserId createFindListByUserId() { return new FindListByUserId(); } /** * Create an instance of {@link DeleteById } * */ public DeleteById createDeleteById() { return new DeleteById(); } /** * Create an instance of {@link SaveOrUpdate } * */ public SaveOrUpdate createSaveOrUpdate() { return new SaveOrUpdate(); } /** * Create an instance of {@link SaveOrUpdateResponse } * */ public SaveOrUpdateResponse createSaveOrUpdateResponse() { return new SaveOrUpdateResponse(); } /** * Create an instance of {@link GetById } * */ public GetById createGetById() { return new GetById(); } /** * Create an instance of {@link DeleteByIdResponse } * */ public DeleteByIdResponse createDeleteByIdResponse() { return new DeleteByIdResponse(); } /** * Create an instance of {@link GetByIdResponse } * */ public GetByIdResponse createGetByIdResponse() { return new GetByIdResponse(); } /** * Create an instance of {@link FindListByUserIdResponse } * */ public FindListByUserIdResponse createFindListByUserIdResponse() { return new FindListByUserIdResponse(); } /** * Create an instance of {@link BzInvoiceItemDto } * */ public BzInvoiceItemDto createBzInvoiceItemDto() { return new BzInvoiceItemDto(); } /** * Create an instance of {@link BzServiceProviderTypeDto } * */ public BzServiceProviderTypeDto createBzServiceProviderTypeDto() { return new BzServiceProviderTypeDto(); } /** * Create an instance of {@link SysRoleDto } * */ public SysRoleDto createSysRoleDto() { return new SysRoleDto(); } /** * Create an instance of {@link BzStockOrderDto } * */ public BzStockOrderDto createBzStockOrderDto() { return new BzStockOrderDto(); } /** * Create an instance of {@link BzOrderPaymentDto } * */ public BzOrderPaymentDto createBzOrderPaymentDto() { return new BzOrderPaymentDto(); } /** * Create an instance of {@link WsPageResult } * */ public WsPageResult createWsPageResult() { return new WsPageResult(); } /** * Create an instance of {@link BzUserDeliveryAddressDto } * */ public BzUserDeliveryAddressDto createBzUserDeliveryAddressDto() { return new BzUserDeliveryAddressDto(); } /** * Create an instance of {@link BzProductCategoryDto } * */ public BzProductCategoryDto createBzProductCategoryDto() { return new BzProductCategoryDto(); } /** * Create an instance of {@link BzProductEvaluationDto } * */ public BzProductEvaluationDto createBzProductEvaluationDto() { return new BzProductEvaluationDto(); } /** * Create an instance of {@link BzMerchantCreditEvalDto } * */ public BzMerchantCreditEvalDto createBzMerchantCreditEvalDto() { return new BzMerchantCreditEvalDto(); } /** * Create an instance of {@link BzProductDto } * */ public BzProductDto createBzProductDto() { return new BzProductDto(); } /** * Create an instance of {@link BzMerchantCreditDto } * */ public BzMerchantCreditDto createBzMerchantCreditDto() { return new BzMerchantCreditDto(); } /** * Create an instance of {@link BzOrderDto } * */ public BzOrderDto createBzOrderDto() { return new BzOrderDto(); } /** * Create an instance of {@link BzPaymentTypeDto } * */ public BzPaymentTypeDto createBzPaymentTypeDto() { return new BzPaymentTypeDto(); } /** * Create an instance of {@link BzConsumerCreditEvalDto } * */ public BzConsumerCreditEvalDto createBzConsumerCreditEvalDto() { return new BzConsumerCreditEvalDto(); } /** * Create an instance of {@link BzInvoiceDto } * */ public BzInvoiceDto createBzInvoiceDto() { return new BzInvoiceDto(); } /** * Create an instance of {@link SysUserDto } * */ public SysUserDto createSysUserDto() { return new SysUserDto(); } /** * Create an instance of {@link BzProductFavoriteDto } * */ public BzProductFavoriteDto createBzProductFavoriteDto() { return new BzProductFavoriteDto(); } /** * Create an instance of {@link BzPositionDto } * */ public BzPositionDto createBzPositionDto() { return new BzPositionDto(); } /** * Create an instance of {@link BzStockDto } * */ public BzStockDto createBzStockDto() { return new BzStockDto(); } /** * Create an instance of {@link BzDistComCreditDto } * */ public BzDistComCreditDto createBzDistComCreditDto() { return new BzDistComCreditDto(); } /** * Create an instance of {@link BzCollectionOrderDto } * */ public BzCollectionOrderDto createBzCollectionOrderDto() { return new BzCollectionOrderDto(); } /** * Create an instance of {@link BzStockOrderItemDto } * */ public BzStockOrderItemDto createBzStockOrderItemDto() { return new BzStockOrderItemDto(); } /** * Create an instance of {@link BzDistributionModelDto } * */ public BzDistributionModelDto createBzDistributionModelDto() { return new BzDistributionModelDto(); } /** * Create an instance of {@link BzMerchantDto } * */ public BzMerchantDto createBzMerchantDto() { return new BzMerchantDto(); } /** * Create an instance of {@link TrProductStockIdDto } * */ public TrProductStockIdDto createTrProductStockIdDto() { return new TrProductStockIdDto(); } /** * Create an instance of {@link BzOrderItemDto } * */ public BzOrderItemDto createBzOrderItemDto() { return new BzOrderItemDto(); } /** * Create an instance of {@link BzShelfDto } * */ public BzShelfDto createBzShelfDto() { return new BzShelfDto(); } /** * Create an instance of {@link BzCartItemDto } * */ public BzCartItemDto createBzCartItemDto() { return new BzCartItemDto(); } /** * Create an instance of {@link SysResourceDto } * */ public SysResourceDto createSysResourceDto() { return new SysResourceDto(); } /** * Create an instance of {@link BzDistributionOrderDto } * */ public BzDistributionOrderDto createBzDistributionOrderDto() { return new BzDistributionOrderDto(); } /** * Create an instance of {@link BzOrderHistoryDto } * */ public BzOrderHistoryDto createBzOrderHistoryDto() { return new BzOrderHistoryDto(); } /** * Create an instance of {@link BzProductBrandDto } * */ public BzProductBrandDto createBzProductBrandDto() { return new BzProductBrandDto(); } /** * Create an instance of {@link BzProductAttachmentDto } * */ public BzProductAttachmentDto createBzProductAttachmentDto() { return new BzProductAttachmentDto(); } /** * Create an instance of {@link BzDistributionCompanyDto } * */ public BzDistributionCompanyDto createBzDistributionCompanyDto() { return new BzDistributionCompanyDto(); } /** * Create an instance of {@link BzConsumerCreditDto } * */ public BzConsumerCreditDto createBzConsumerCreditDto() { return new BzConsumerCreditDto(); } /** * Create an instance of {@link BzUserPositionDto } * */ public BzUserPositionDto createBzUserPositionDto() { return new BzUserPositionDto(); } /** * Create an instance of {@link BzUserTakeDeliveryAddressDto } * */ public BzUserTakeDeliveryAddressDto createBzUserTakeDeliveryAddressDto() { return new BzUserTakeDeliveryAddressDto(); } /** * Create an instance of {@link TrProductStockDto } * */ public TrProductStockDto createTrProductStockDto() { return new TrProductStockDto(); } /** * Create an instance of {@link BzDistComCreditEvalDto } * */ public BzDistComCreditEvalDto createBzDistComCreditEvalDto() { return new BzDistComCreditEvalDto(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DeleteByIdResponse }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "deleteByIdResponse") public JAXBElement<DeleteByIdResponse> createDeleteByIdResponse(DeleteByIdResponse value) { return new JAXBElement<DeleteByIdResponse>(_DeleteByIdResponse_QNAME, DeleteByIdResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetById }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "getById") public JAXBElement<GetById> createGetById(GetById value) { return new JAXBElement<GetById>(_GetById_QNAME, GetById.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SaveOrUpdateResponse }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "saveOrUpdateResponse") public JAXBElement<SaveOrUpdateResponse> createSaveOrUpdateResponse(SaveOrUpdateResponse value) { return new JAXBElement<SaveOrUpdateResponse>(_SaveOrUpdateResponse_QNAME, SaveOrUpdateResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link FindListByUserIdResponse }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "findListByUserIdResponse") public JAXBElement<FindListByUserIdResponse> createFindListByUserIdResponse(FindListByUserIdResponse value) { return new JAXBElement<FindListByUserIdResponse>(_FindListByUserIdResponse_QNAME, FindListByUserIdResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetByIdResponse }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "getByIdResponse") public JAXBElement<GetByIdResponse> createGetByIdResponse(GetByIdResponse value) { return new JAXBElement<GetByIdResponse>(_GetByIdResponse_QNAME, GetByIdResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link FindListByUserId }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "findListByUserId") public JAXBElement<FindListByUserId> createFindListByUserId(FindListByUserId value) { return new JAXBElement<FindListByUserId>(_FindListByUserId_QNAME, FindListByUserId.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DeleteById }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "deleteById") public JAXBElement<DeleteById> createDeleteById(DeleteById value) { return new JAXBElement<DeleteById>(_DeleteById_QNAME, DeleteById.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SaveOrUpdate }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "saveOrUpdate") public JAXBElement<SaveOrUpdate> createSaveOrUpdate(SaveOrUpdate value) { return new JAXBElement<SaveOrUpdate>(_SaveOrUpdate_QNAME, SaveOrUpdate.class, null, value); } }
zpxocivuby/freetong_mobile_server
itaf-aggregator/itaf-ws-simulator/src/test/java/itaf/WsUserTakeDeliveryAddressService/ObjectFactory.java
Java
gpl-3.0
14,213
<?php ############################### # include files from root dir # ############################### $root_1 = realpath($_SERVER["DOCUMENT_ROOT"]); $currentdir = getcwd(); $root_2 = str_replace($root_1, '', $currentdir); $root_3 = explode("/", $root_2); if ($root_3[1] == 'core') { echo $root_3[1]; $root = realpath($_SERVER["DOCUMENT_ROOT"]); }else{ $root = $root_1 . '/' . $root_3[1]; } $login_module = "modul_g-plus-login";//need to get extra config for modules include($root.'/core/backend/admin/modules/'.$login_module. '/index.php'); ?>
RpicmsTeam/RPICMS
core/backend/admin/modules/navigation.php
PHP
gpl-3.0
562
#ifndef __MAIN_HPP__ #define __MAIN_HPP__ #include <iostream> #include <unistd.h> #include <string> #include <vector> #include <stdint.h> // Para usar uint64_t #include "hanoi.hpp" #include "statistical.hpp" #include "ClaseTiempo.hpp" #define cls() system("clear"); long long combinatorio_iterativo(const int &n,const int &k){ long double fact_n = 1, fact_k = 1, fact_nk = 1; for( long double i = 2 ; i <= n ; ++i ) fact_n *= i; for( long double i = 2 ; i <= k ; ++i ) fact_k *= i; for( long double i = 2 ; i <= (n-k) ; ++i ) fact_nk *= i; return fact_n/fact_k/fact_nk; } long long combinatorio_recursivo(const int &n, const int &k){ if(k == 0 || k == n){ return 1; } return combinatorio_recursivo(n-1, k-1) + combinatorio_recursivo(n-1, k); } long long combinatorio_recursivo_2(const int &n, const int &k, std::vector<std::vector< long long > > &aux){ int a; if(k == 0 || k == n) return 1; if( aux[n-1][k-1] != -1 ){ a = aux[n-1][k-1]; } else{ a = combinatorio_recursivo_2(n-1, k-1, aux) + combinatorio_recursivo_2(n-1, k, aux); aux[n-1][k-1] = a; } return a; } /** * @brief Cabecera que se mostrará durante la ejecución del programa. */ void cabecera(){ cls(); std::cout << "\e[1;92m###############################" << std::endl; std::cout << "###############################" << std::endl; std::cout << "#### ####" << std::endl; std::cout << "#### \e[96mPrograma\e[92m ####" << std::endl; std::cout << "#### ####" << std::endl; std::cout << "###############################" << std::endl; std::cout << "###############################\e[0m" << std::endl << std::endl; } /** * @brief Mensaje que se muestra al final de cada opción del menú. * @note En la función aplicarFloyd() se llama también para dar paso al submenú. * @param count Número de veces a ejecutar std::cin.ignore() * @param mensaje Mensaje a mostar. Por defecto mostrará: "Presiona ENTER para volver al menú." */ void volver(const int &count = 2, const std::string &mensaje="Presiona ENTER para volver al menú."){ std::cout << std::endl << mensaje; for( int i = 0 ; i < count ; ++i) std::cin.ignore(); } /** * @brief Muestra un error personalizado por pantalla. * @note Con 2 segundos de sleep da tiempo a leer los errores. * @param er Error a mostrar. */ void error(const std::string &er){ std::cout << std::endl << "\e[31;1m[ERROR]\e[0m - " << er << std::endl; fflush(stdout); sleep(2); } /** * @brief Muestra las opciones del menú e interactua con el usuario. * @return Opción del menú a ejecutar. * @sa cabecera() * @sa error() */ uint opciones(){ int opcion; do{ cabecera(); std::cout << "Estas son las opciones disponibles:" << std::endl; std::cout << "\t\e[33;1m[1]\e[0m - Menú combinatoria." << std::endl; std::cout << "\t\e[33;1m[2]\e[0m - Menú Hanoi." << std::endl; std::cout << "\t\e[33;1m[0]\e[0m - Salir del programa." << std::endl; std::cout << "Introduce tu opción: \e[33;1m"; std::cin >> opcion; std::cout << "\e[0m"; if(opcion<0 || opcion>2){ error("Opción no válida. Volviendo al menú principal..."); } }while(opcion<0 || opcion>2); return opcion; } /** * @brief Función para despedirse. * @note Con el Adiós en grande mejoramos la experiencia del usuario. * @sa cabecera() */ void despedida(){ cabecera(); std::cout << "Gracias por usar el programa, ¡hasta la próxima!\e[1m" << std::endl; std::cout << " _ _ __ " << std::endl << "\ /\\ | (_) /_/ " << std::endl << "\ / \\ __| |_ ___ ___ " << std::endl << "\ / /\\ \\ / _` | |/ _ \\/ __|" << std::endl << "\ / ____ \\ (_| | | (_) \\__ \\" << std::endl << "\ /_/ \\_\\__,_|_|\\___/|___/" << std::endl << "\ " << std::endl << "\ \e[0m" << std::endl; } void mostrar_determinacion(al::Statistical &stats){ cabecera(); std::cout << std::endl << "Coeficiente de determinación: " << stats.get_coef() << std::endl; volver(); } void mostrar_ecuacion(al::Statistical &stats){ cabecera(); bool lineal = stats.get_lineal(); std::vector<long double> aux = stats.get_params_value(); std::cout << "Ecuación de estimación:" << std::endl << "\tt(n) = "; if(lineal){ for (int i = 0; i < aux.size(); ++i) { std::cout << ((i == 0) ? aux[i] : std::abs(aux[i])) << "*n^" << i; if( i < (aux.size()-1)) aux[i]>0?std::cout<<" + ":std::cout<<" - "; } } else{ std::cout << aux[0] << (aux[1]>0?" + ":" - ") << std::abs(aux[1]) << "*2^n" << std::endl; } volver(); } void mostrar_grafica(const std::string &f_name){ cabecera(); std::string cmd = "xdg-open " + f_name + " 2> /dev/null"; FILE * aux = popen(cmd.c_str(), "r"); pclose(aux); volver(); } void estimar_tiempos(al::Statistical &stats, const std::string &x){ cabecera(); int tam; long double res = 0; std::vector<long double> params = stats.get_params_value(); bool lineal = stats.get_lineal(); std::cout << "Introduce el " << x << " a calcular: "; std::cin >> tam; if(lineal){ for( int i = 0 ; i < params.size() ; ++i ){ res += params[i] * pow(tam, i); } } else{ res = params[0] + params[1] * pow(2, tam); } std::cout << std::endl << "Taradría " << (lineal?res*pow(10,-6)/(60*60):res*(pow(10, -6)/(3600*24))) << (lineal? " horas.":" años.") << std::endl; volver(); } int opciones_comb(){ int opcion; do{ cabecera(); std::cout << "Estas son las opciones disponibles:" << std::endl; std::cout << "\t\e[33;1m[1]\e[0m - Algoritmo recursivo." << std::endl; std::cout << "\t\e[33;1m[2]\e[0m - Algoritmo recursivo con tabla de valores." << std::endl; std::cout << "\t\e[33;1m[3]\e[0m - Algoritmo iterativo." << std::endl; std::cout << "\t\e[33;1m[0]\e[0m - Atrás." << std::endl; std::cout << "Introduce tu opción: \e[33;1m"; std::cin >> opcion; std::cout << "\e[0m"; if(opcion<0 || opcion>3){ error("Opción no válida. Volviendo al menú..."); } }while(opcion<0 || opcion>3); return opcion; } int opciones_stats(){ int opcion; do{ cabecera(); std::cout << "Estas son las opciones disponibles:" << std::endl; std::cout << "\t\e[33;1m[1]\e[0m - Mostrar coeficiente de determinación." << std::endl; std::cout << "\t\e[33;1m[2]\e[0m - Mostrar ecuación de estimación." << std::endl; std::cout << "\t\e[33;1m[3]\e[0m - Mostrar gráfico generado." << std::endl; std::cout << "\t\e[33;1m[4]\e[0m - Estimar tiempos." << std::endl; std::cout << "\t\e[33;1m[0]\e[0m - Atrás." << std::endl; std::cout << "Introduce tu opción: \e[33;1m"; std::cin >> opcion; std::cout << "\e[0m"; if(opcion<0 || opcion>4){ error("Opción no válida. Volviendo..."); } }while(opcion<0 || opcion>4); return opcion; } void menu_combinatoria(const int &type){ cabecera(); int mayor, menor, incremento, n_rpt, opcion; Clock timer; std::string dat_name, eps_name; uint64_t aux_timer1, aux_timer2; al::Statistical stats(true); std::cout << "Introduce el menor número a calcular: "; std::cin >> menor; std::cout << "Introduce el mayor número a calcular: "; std::cin >> mayor; std::cout << "Introduce el incremento: "; std::cin >> incremento; std::cout << "Veces a repetir: "; std::cin >> n_rpt; if(menor > mayor){ menor += mayor; mayor = menor - mayor; menor -= mayor; } if(incremento > (mayor-menor)){ std::cerr << "\e[1;31m[Error]\e[m. The increment mustn't be higher than the upper number minus the lower number." << std::endl; exit(1); } std::cout << std::endl << "Procesando..." << std::endl; for( int i = menor ; i <= mayor ; i+=incremento ){ aux_timer1 = 0; for( int j = 0 ; j <= i ; ++j ){ aux_timer2 = 0; for( int k = 0 ; k < n_rpt ; ++k ){ long long res; std::vector<std::vector< long long > > v = std::vector<std::vector< long long > >(i, std::vector<long long>(j)); if(type == 2){ for( int z = 0 ; z < i ; ++z ){ for( int t = 0 ; t < j ; ++t ) v[z][t] = -1; } } timer.start(); switch (type){ case 1: res = combinatorio_recursivo(i, j); break; case 2: res = combinatorio_recursivo_2(i, j, v); break; case 3: res = combinatorio_iterativo(i, j); break; } timer.stop(); aux_timer2 += timer.elapsed(); } // t(i,0) + t(i,1) .. t(i,i) aux_timer1 += aux_timer2/n_rpt; } stats.add_test_size(i); // t(i) = (t(i,0) + t(i,1) .. t(i,i)) / (i+1) stats.add_elapsed_time(aux_timer1/(i+1)); } stats.estimate_times(4); switch (type){ case 1: dat_name = "comb_rec.dat"; eps_name = "comb_rec.eps"; break; case 2: dat_name = "comb_rec2.dat"; eps_name = "comb_rec2.eps"; break; case 3: dat_name = "comb_iter.dat"; eps_name = "comb_iter.eps"; break; } stats.dump_stats(dat_name.c_str()); bool salir = false; do{ opcion = opciones_stats(); switch (opcion){ case 0: salir = true; break; case 1: mostrar_determinacion(stats); break; case 2: mostrar_ecuacion(stats); break; case 3: mostrar_grafica(eps_name); break; case 4: estimar_tiempos(stats, "tamaño de combinatorio"); break; } }while(!salir); } void menu_combinatoria(){ int opcion; bool salir = false; do{ opcion = opciones_comb(); switch(opcion){ case 0: salir = true; break; default: menu_combinatoria(opcion); } }while(!salir); } int opciones_hanoi(){ int opcion; do{ cabecera(); std::cout << "Estas son las opciones disponibles:" << std::endl; std::cout << "\t\e[33;1m[1]\e[0m - Cálculo de movimientos con n discos." << std::endl; std::cout << "\t\e[33;1m[2]\e[0m - Representación gráfica." << std::endl; std::cout << "\t\e[33;1m[0]\e[0m - Atrás." << std::endl; std::cout << "Introduce tu opción: \e[33;1m"; std::cin >> opcion; std::cout << "\e[0m"; if(opcion<0 || opcion>2){ error("Opción no válida. Volviendo al menú..."); } }while(opcion<0 || opcion>2); return opcion; } void calculo_hanoi(){ cabecera(); int tam, n_rpt, opcion; Clock timer; al::Statistical stats(false); uint64_t aux_timer; std::cout << "Introduce el tamaño máximo de discos a utilizar: "; std::cin >> tam; std::cout << "Veces a repetir: "; std::cin >> n_rpt; for(int i = 0 ; i < tam ; ++i){ aux_timer = 0; for (int j = 0; j < n_rpt ; ++j) { al::Hanoi h(i); timer.start(); h.solve_hanoi(); timer.stop(); aux_timer += timer.elapsed(); } stats.add_test_size(i); stats.add_elapsed_time(aux_timer/n_rpt); } stats.estimate_times(2); stats.dump_stats("hanoi.dat"); bool salir = false; do{ opcion = opciones_stats(); switch (opcion){ case 0: salir = true; break; case 1: mostrar_determinacion(stats); break; case 2: mostrar_ecuacion(stats); break; case 3: mostrar_grafica("hanoi.eps"); break; case 4: estimar_tiempos(stats, "número de discos de hanoi"); break; } }while(!salir); } void hanoi_grafico(){ cabecera(); int tam; std::cout << "Introduce el número de discos (entre 1 y 8): "; std::cin >> tam; al::Hanoi h(tam); cls(); std::cout << std::endl << std::endl << h << std::endl << "Estado inicial, pulsa ENTER para continuar";; std::cin.ignore(); std::cin.ignore(); usleep(500000); h.solve_hanoi(true); std::cout << std::endl << "Hanoi resuelto en " << h.get_moves() << " movimientos." << std::endl; volver(1); } void menu_hanoi(){ int opcion; bool salir = false; do{ opcion = opciones_hanoi(); switch(opcion){ case 1: calculo_hanoi(); break; case 2: hanoi_grafico(); break; case 3: break; case 0: salir = true; break; } }while(!salir); } #endif
i32ropie/Algoritmica
p2/main.hpp
C++
gpl-3.0
13,742
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (1.8.0_111) on Thu Dec 22 11:36:55 CET 2016 --> <title>ch.ethz.inspire.emod.model.units</title> <meta name="date" content="2016-12-22"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ch.ethz.inspire.emod.model.units"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../ch/ethz/inspire/emod/model/thermal/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../../ch/ethz/inspire/emod/simulation/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?ch/ethz/inspire/emod/model/units/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;ch.ethz.inspire.emod.model.units</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/SiConstants.html" title="class in ch.ethz.inspire.emod.model.units">SiConstants</a></td> <td class="colLast"> <div class="block">Implements varoius SI constants</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/SiUnit.html" title="class in ch.ethz.inspire.emod.model.units">SiUnit</a></td> <td class="colLast"> <div class="block">SI unit class</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/SiUnitDefinition.html" title="class in ch.ethz.inspire.emod.model.units">SiUnitDefinition</a></td> <td class="colLast"> <div class="block">Implementation of the SI definitions</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation"> <caption><span>Enum Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Enum</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/ContainerType.html" title="enum in ch.ethz.inspire.emod.model.units">ContainerType</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/Unit.html" title="enum in ch.ethz.inspire.emod.model.units">Unit</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../ch/ethz/inspire/emod/model/thermal/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../../ch/ethz/inspire/emod/simulation/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?ch/ethz/inspire/emod/model/units/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
sizuest/EMod
ch.ethz.inspire.emod/src/ch/ethz/inspire/emod/model/units/package-summary.html
HTML
gpl-3.0
6,507
import commandRunner as cr import subprocess import glob, os, platform, shutil, adb from pathlib import Path def combine_browsers_logs(udid): cmd = 'rebot -N Combined --outputdir browserlogs/ ' for idx, device in enumerate(udid): #Get all the output.xml files for the devices if platform.system() == "Windows": cmd += os.getcwd() + "\\browserlogs\\" + device + "\output.xml " else: cmd += os.getcwd() + "/browserlogs/" + device + "/output.xml " cr.run_command(cmd) pngs = [] #For screenshot images if platform.system() == "Windows": for idx, device in enumerate(udid): pngs += glob.glob(os.getcwd() + "\\browserlogs\\" + device + "\\" + "*.png") for p in pngs: shutil.copy(p, p.replace(device + "\\", "")) #remove those that have been moved/copied pngs = [p for p in pngs if not p] else: for idx, device in enumerate(udid): pngs += glob.glob(os.getcwd() + "/browserlogs/" + device + "/" + "*.png") for p in pngs: shutil.copy(p, p.replace(device + "/", "")) #remove those that have been moved/copied pngs = [p for p in pngs if not p] def combine_logs(udid): cmd = 'rebot -N Combined --outputdir logs/ ' for idx, device in enumerate(udid): #Get all the output.xml files for the devices if platform.system() == "Windows": cmd += os.getcwd() + "\logs\\" + device + "_" + "*\output.xml " else: cmd += os.getcwd() + "/logs/" + device + "_" + "*/output.xml " cr.run_command(cmd) pngs = [] #For screenshot images if platform.system() == "Windows": pngs = glob.glob(os.getcwd() + "\logs\**\*.png") for idx, device in enumerate(udid): for p in pngs: if Path(p).is_file(): #If image exist imgname = p[p.rindex('\\')+1:] k = p.rfind("\logs\\") path = p[:k] newPath = path + "\logs\\" + imgname shutil.move(p,newPath) else: pngs = glob.glob(os.getcwd() + "/logs/**/*.png") for idx, device in enumerate(udid): for p in pngs: if Path(p).is_file(): #If image exist imgname = p[p.rindex('/')+1:] k = p.rfind("/logs/") path = p[:k] newPath = path + "/logs/" + imgname shutil.move(p,newPath) def zip_logs(): if platform.system() == "Windows": cmd = "Compress-Archive logs logs-$(date +%Y-%m-%d-%H%M).zip" subprocess.call(["powershell.exe", cmd]) elif platform.system() == "Linux" or platform.system() == "Darwin": cmd = "zip -vr logs-$(date +%Y-%m-%d-%H%M).zip" + " logs/" cr.run_command(cmd) def zip_browsers_logs(): if platform.system() == "Windows": cmd = "Compress-Archive browserlogs browserlogs-$(date +%Y-%m-%d-%H%M).zip" subprocess.call(["powershell.exe", cmd]) elif platform.system() == "Linux" or platform.system() == "Darwin": cmd = "zip -vr browserlogs-$(date +%Y-%m-%d-%H%M).zip" + " browserlogs/" cr.run_command(cmd) def delete_previous_logs(): cmd = 'rm -rf logs/*' cr.run_command(cmd) def delete_previous_logs_browser(): cmd = 'rm -rf browserlogs/*' cr.run_command(cmd)
younglim/hats-ci
robot_automation/src/logs.py
Python
gpl-3.0
3,513
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * 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.lh64.randomdungeon.actors.buffs; import com.lh64.randomdungeon.ui.BuffIndicator; import com.lh64.utils.Bundle; public class SnipersMark extends FlavourBuff { public int object = 0; private static final String OBJECT = "object"; @Override public void storeInBundle( Bundle bundle ) { super.storeInBundle( bundle ); bundle.put( OBJECT, object ); } @Override public void restoreFromBundle( Bundle bundle ) { super.restoreFromBundle( bundle ); object = bundle.getInt( OBJECT ); } @Override public int icon() { return BuffIndicator.MARK; } @Override public String toString() { return "Zeroed in"; } }
lighthouse64/Random-Dungeon
src/com/lh64/randomdungeon/actors/buffs/SnipersMark.java
Java
gpl-3.0
1,360
namespace Maticsoft.TaoBao.Request { using Maticsoft.TaoBao; using Maticsoft.TaoBao.Util; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; public class SimbaAdgroupCampcatmatchsGetRequest : ITopRequest<SimbaAdgroupCampcatmatchsGetResponse> { private IDictionary<string, string> otherParameters; public void AddOtherParameter(string key, string value) { if (this.otherParameters == null) { this.otherParameters = new TopDictionary(); } this.otherParameters.Add(key, value); } public string GetApiName() { return "taobao.simba.adgroup.campcatmatchs.get"; } public IDictionary<string, string> GetParameters() { TopDictionary dictionary = new TopDictionary(); dictionary.Add("campaign_id", this.CampaignId); dictionary.Add("nick", this.Nick); dictionary.Add("page_no", this.PageNo); dictionary.Add("page_size", this.PageSize); dictionary.AddAll(this.otherParameters); return dictionary; } public void Validate() { RequestValidator.ValidateRequired("campaign_id", this.CampaignId); } public long? CampaignId { get; set; } public string Nick { get; set; } public long? PageNo { get; set; } public long? PageSize { get; set; } } }
51zhaoshi/myyyyshop
Maticsoft.TaoBao_Source/Maticsoft.TaoBao.Request/SimbaAdgroupCampcatmatchsGetRequest.cs
C#
gpl-3.0
1,512
<?php /** * /queue/add.php * * This file is part of DomainMOD, an open source domain and internet asset manager. * Copyright (c) 2010-2016 Greg Chetcuti <[email protected]> * * Project: http://domainmod.org Author: http://chetcuti.com * * DomainMOD is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * DomainMOD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with DomainMOD. If not, see * http://www.gnu.org/licenses/. * */ ?> <?php include("../_includes/start-session.inc.php"); include("../_includes/init.inc.php"); require_once(DIR_ROOT . "classes/Autoloader.php"); spl_autoload_register('DomainMOD\Autoloader::classAutoloader'); $system = new DomainMOD\System(); $error = new DomainMOD\Error(); $layout = new DomainMOD\Layout(); $domain = new DomainMOD\Domain(); $time = new DomainMOD\Time(); $form = new DomainMOD\Form(); include(DIR_INC . "head.inc.php"); include(DIR_INC . "config.inc.php"); include(DIR_INC . "software.inc.php"); include(DIR_INC . "settings/queue-add.inc.php"); include(DIR_INC . "database.inc.php"); $system->authCheck($web_root); $system->readOnlyCheck($_SERVER['HTTP_REFERER']); $new_raid = $_REQUEST['new_raid']; $raw_domain_list = $_POST['raw_domain_list']; if ($new_raid != '' ) { $query = "SELECT apir.name, apir.req_account_username, apir.req_account_password, apir.req_reseller_id, apir.req_api_app_name, apir.req_api_key, apir.req_api_secret, apir.req_ip_address, apir.lists_domains, apir.ret_expiry_date, apir.ret_dns_servers, apir.ret_privacy_status, apir.ret_autorenewal_status, apir.notes, ra.username, ra.password, ra.reseller_id, ra.api_app_name, ra.api_key, ra.api_secret, ra.api_ip_id FROM registrar_accounts AS ra, registrars AS r, api_registrars AS apir WHERE ra.registrar_id = r.id AND r.api_registrar_id = apir.id AND ra.id = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('i', $new_raid); $q->execute(); $q->store_result(); $q->bind_result($api_registrar_name, $req_account_username, $req_account_password, $req_reseller_id, $req_api_app_name, $req_api_key, $req_api_secret, $req_ip_address, $lists_domains, $ret_expiry_date, $ret_dns_servers, $ret_privacy_status, $ret_autorenewal_status, $registrar_notes, $account_username, $account_password, $reseller_id, $api_app_name, $api_key, $api_secret, $api_ip_id); $q->fetch(); $q->close(); } else $error->outputSqlError($conn, "ERROR"); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { $format = new DomainMOD\Format(); $domain_list = $format->cleanAndSplitDomains($raw_domain_list); // If the registrar has the ability to retrieve the list of domains if ($lists_domains == '1' && $raw_domain_list == '') { if ($new_raid == '') { if ($new_raid == '') $_SESSION['s_message_danger'] .= "Please choose the registrar account<BR>"; } else { $query = "SELECT ra.owner_id, ra.registrar_id, r.api_registrar_id FROM registrar_accounts AS ra, registrars AS r WHERE ra.registrar_id = r.id AND ra.id = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('i', $new_raid); $q->execute(); $q->store_result(); $q->bind_result($t_owner_id, $t_registrar_id, $t_api_registrar_id); while ($q->fetch()) { $temp_owner_id = $t_owner_id; $temp_registrar_id = $t_registrar_id; $temp_api_registrar_id = $t_api_registrar_id; } $q->close(); } else $error->outputSqlError($conn, "ERROR"); $query = "INSERT INTO domain_queue_list (api_registrar_id, owner_id, registrar_id, account_id, created_by, insert_time) VALUES (?, ?, ?, ?, ?, ?)"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $timestamp = $time->stamp(); $q->bind_param('iiiiis', $temp_api_registrar_id, $temp_owner_id, $temp_registrar_id, $new_raid, $_SESSION['s_user_id'], $timestamp); $q->execute() or $error->outputSqlError($conn, "Couldn't add registrar account to list queue"); $q->close(); } else $error->outputSqlError($conn, "ERROR"); $_SESSION['s_domains_in_list_queue'] = '1'; $_SESSION['s_message_success'] .= "Registrar Account Added To Domain List Queue<BR>"; header("Location: index.php"); exit; } } else { // If the registrar's API DOES NOT have the ability to retrieve the list of domains, or if there's a // problem with he automatic import, use the list supplied // check to make sure that the registrar associated with the account has API support $query = "SELECT ra.id, ra.registrar_id FROM registrar_accounts AS ra, registrars AS r, api_registrars AS ar WHERE ra.registrar_id = r.id AND r.api_registrar_id = ar.id AND ra.id = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('i', $new_raid); $q->execute(); $q->store_result(); if ($q->num_rows() == 0) { $query2 = "SELECT registrar_id FROM registrar_accounts WHERE id = ?"; $q2 = $conn->stmt_init(); if ($q2->prepare($query2)) { $q2->bind_param('i', $new_raid); $q2->execute(); $q2->store_result(); $q2->bind_result($t_rid); while ($q2->fetch()) { $temp_registrar_id = $t_rid; } $q2->close(); } else $error->outputSqlError($conn, "ERROR"); $has_api_support = '0'; } else { $has_api_support = '1'; } $q->close(); } else $error->outputSqlError($conn, "ERROR"); if ($new_raid == '' || $raw_domain_list == '' || $has_api_support != '1') { if ($has_api_support != '1' && $new_raid != '') { $_SESSION['s_message_danger'] .= "Either the registrar associated with this account doesn't have API support, or you haven't yet updated the registrar to indicate API support.<BR><BR>Please check the <a href='" . $web_root . "/assets/edit/registrar.php?rid=" . $temp_registrar_id . "'>registrar</a> and try again."; } else { if ($new_raid == '') $_SESSION['s_message_danger'] .= "Please choose the registrar account<BR>"; if ($raw_domain_list == '') $_SESSION['s_message_danger'] .= "Enter the list of domains to add to the queue<BR>"; } } else { list($invalid_to_display, $invalid_domains, $invalid_count, $temp_result_message) = $domain->findInvalidDomains($domain_list); if ($raw_domain_list == "" || $invalid_domains == 1) { if ($invalid_domains == 1) { if ($invalid_count == 1) { $_SESSION['s_message_danger'] .= "There is " . number_format($invalid_count) . " invalid domain on your list<BR><BR>" . $temp_result_message; } else { $_SESSION['s_message_danger'] .= "There are " . number_format($invalid_count) . " invalid domains on your list<BR><BR>" . $temp_result_message; if (($invalid_count - $invalid_to_display) == 1) { $_SESSION['s_message_danger'] .= "<BR>Plus " . number_format($invalid_count - $invalid_to_display) . " other<BR>"; } elseif (($invalid_count - $invalid_to_display) > 1) { $_SESSION['s_message_danger'] .= "<BR>Plus " . number_format($invalid_count - $invalid_to_display) . " others<BR>"; } } } else { $_SESSION['s_message_danger'] .= "Enter the list of domains to add to the queue<BR>"; } $submission_failed = 1; } else { $date = new DomainMOD\Date(); reset($domain_list); // cycle through domains here while (list($key, $new_domain) = each($domain_list)) { $query = "SELECT domain FROM domains WHERE domain = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('s', $new_domain); $q->execute(); $q->store_result(); if ($q->num_rows() > 0) { $has_existing_domains = '1'; } } } reset($domain_list); // cycle through domains here while (list($key, $new_domain) = each($domain_list)) { $query = "SELECT domain FROM domain_queue WHERE domain = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('s', $new_domain); $q->execute(); $q->store_result(); if ($q->num_rows() > 0) { $has_existing_domains_queue = '1'; } } } if ($new_raid == "" || $new_raid == "0" || $has_existing_domains == '1' || $has_existing_domains_queue == '1') { if ($has_existing_domains == '1') $_SESSION['s_message_danger'] .= "At least one of the domains you entered already exists in " . $software_title . ".<BR><BR>You should run the domain list through a Segment filter to determine which one(s).<BR><BR>"; if ($has_existing_domains_queue == '1') $_SESSION['s_message_danger'] .= "At least one of the domains you entered is already in the domain queue.<BR>"; if ($new_raid == "" || $new_raid == "0") $_SESSION['s_message_danger'] .= "Please choose the registrar account<BR>"; $submission_failed = 1; } else { $query = "SELECT ra.owner_id, ra.registrar_id, r.api_registrar_id FROM registrar_accounts AS ra, registrars AS r WHERE ra.registrar_id = r.id AND ra.id = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('i', $new_raid); $q->execute(); $q->store_result(); $q->bind_result($t_oid, $t_rid, $t_apirid); while ($q->fetch()) { $temp_owner_id = $t_oid; $temp_registrar_id = $t_rid; $temp_api_registrar_id = $t_apirid; } $q->close(); } else $error->outputSqlError($conn, "ERROR"); reset($domain_list); // cycle through domains here while (list($key, $new_domain) = each($domain_list)) { $domain_temp = new DomainMOD\Domain(); $new_tld = $domain_temp->getTld($new_domain); $query = "INSERT INTO domain_queue (api_registrar_id, domain, owner_id, registrar_id, account_id, tld, created_by, insert_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $timestamp = $time->stamp(); $q->bind_param('isiiisis', $temp_api_registrar_id, $new_domain, $temp_owner_id, $temp_registrar_id, $new_raid, $new_tld, $_SESSION['s_user_id'], $timestamp); $q->execute() or $error->outputSqlError($conn, "Couldn't add domains to queue"); $q->close(); } else $error->outputSqlError($conn, "ERROR"); } // finish cycling through domains here $done = "1"; reset($domain_list); $new_data_unformatted = implode(", ", $domain_list); $_SESSION['s_domains_in_queue'] = '1'; $_SESSION['s_message_success'] .= "Domains Added To Queue<BR>"; } } } } } ?> <?php include(DIR_INC . 'doctype.inc.php'); ?> <html> <head> <title><?php echo $system->pageTitle($software_title, $page_title); ?></title> <?php include(DIR_INC . "layout/head-tags.inc.php"); ?> <?php echo $layout->jumpMenu(); ?> </head> <body class="hold-transition skin-red sidebar-mini"> <?php include(DIR_INC . "layout/header.inc.php"); ?> <?php if ($done == "1") { if ($submission_failed != "1") { ?> <strong>The following domains were added to the queue:</strong><BR> <?php echo htmlentities($new_data_unformatted, ENT_QUOTES, 'UTF-8'); ?><BR><BR><?php } } ?> <strong>Domain Queue & API Prerequisites</strong><BR> Before you can add domains to DomainMOD using the Domain Queue you must first do the following: <ol> <li>Ensure that the registrar has an API and that your account has been granted access to it</li> <li>Enable API Support on the <a href="<?php echo $web_root; ?>/assets/registrars.php">registrar asset</a></li> <li>Save the required API credentials with the <a href="<?php echo $web_root; ?>/assets/registrar-accounts.php">registrar account asset</a></li> </ol><?php echo $form->showFormTop(''); echo $form->showDropdownTopJump('', '', '', ''); $sql_account = "SELECT ra.id, ra.username, o.name AS o_name, r.name AS r_name FROM registrar_accounts AS ra, owners AS o, registrars AS r WHERE ra.owner_id = o.id AND ra.registrar_id = r.id AND r.api_registrar_id != '0' ORDER BY r_name, o_name, ra.username"; $result_account = mysqli_query($connection, $sql_account) or $error->outputOldSqlError($connection); echo $form->showDropdownOptionJump('add.php', '', 'Choose the Registrar Account to import', ''); while ($row_account = mysqli_fetch_object($result_account)) { echo $form->showDropdownOptionJump('add.php?new_raid=', $row_account->id, $row_account->r_name . ', ' . $row_account->o_name . ' (' . $row_account->username . ')', $new_raid); } echo $form->showDropdownBottom(''); if ($new_raid != '') { ?> <strong>API Requirements</strong><BR> <?php echo $api_registrar_name; ?> requires the following credentials in order to use their API. These credentials must to be saved with the <a href="<?php echo $web_root; ?>/assets/edit/registrar-account.php?raid=<?php echo urlencode($new_raid); ?>">registrar account asset</a>. <ul><?php $missing_text = ' (<a href="' . $web_root . '/assets/edit/registrar-account.php?raid=' . htmlentities($new_raid, ENT_QUOTES, 'UTF-8') . '"><span style="color: #a30000"><strong>missing - click here to enter</strong></span></a>)'; $saved_text = ' (<span style="color: darkgreen"><strong>saved</strong></span>)'; if ($req_account_username == '1') { echo '<li>Registrar Account Username'; if ($account_username == '') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_account_password == '1') { echo '<li>Registrar Account Password'; if ($account_password == '') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_reseller_id == '1') { echo '<li>Reseller ID'; if ($reseller_id == '' || $reseller_id == '0') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_api_app_name == '1') { echo '<li>API Application Name'; if ($api_app_name == '') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_api_key == '1') { echo '<li>API Key'; if ($api_key == '') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_api_secret == '1') { echo '<li>API Secret'; if ($api_secret == '') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_ip_address == '1') { echo '<li>Connecting IP Address'; if ($api_ip_id == '0') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } ?> </ul><?php } if ($registrar_notes != '') { echo '<strong>Registrar Notes</strong><BR>'; echo $registrar_notes . "<BR><BR>"; } if ($new_raid != '') { if ($lists_domains == '1') { echo '<strong>Domain List</strong><BR>'; echo htmlentities($api_registrar_name, ENT_QUOTES, 'UTF-8') . '\'s API has a domain list feature, so you don\'t even have to supply a list of the domains you want to import, DomainMOD will retrieve them for you automatically. If for some reason you\'re having issues with the automatic import though, you can still manually paste a list of domains to import below.<BR><BR>'; echo $form->showInputTextarea('raw_domain_list', '[OPTIONAL] Domains to add (one per line)', '', $raw_domain_list, '', '', ''); } else { echo $form->showInputTextarea('raw_domain_list', 'Domains to add (one per line)', '', $raw_domain_list, '1', '', ''); } } if ($new_raid != '') { echo $form->showSubmitButton('Add Domains', '', ''); } echo $form->showInputHidden('new_raid', $new_raid); echo $form->showFormBottom(''); ?> <?php include(DIR_INC . "layout/footer.inc.php"); ?> </body> </html>
koep/domainmod
queue/add.php
PHP
gpl-3.0
19,235
# Copyright (c) 2014 Stefano Palazzo <[email protected]> # 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/>. ''' hello Usage: hello (--help | --version) Options: --help -h display this help message and exit --version print version information and exit ''' import sys import docopt import hello def main(argv=sys.argv[1:]): try: docopt.docopt(__doc__, argv=argv, version=hello.__version__) except docopt.DocoptExit as e: print(str(e), file=sys.stderr) return 2 except SystemExit as e: return 0 if __name__ == "__main__": # pragma: no cover sys.exit(main())
sfstpala/hello
hello/__main__.py
Python
gpl-3.0
1,225
/* * Copyright 2015 Jan von Cosel * * This file is part of utility-scripts. * * utility-scripts 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. * * utility-scripts 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 recieved a copy of the GNU General Public License * along with utility-scripts. If not, see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include <iomanip> #include <fstream> #include <algorithm> #include <iterator> #include <cmath> #include <boost/filesystem.hpp> #include <eigen3/Eigen/Core> #include <eigen3/Eigen/Eigenvalues> #include "constants.h" #include "utilities.h" /* * Call this program like: * * ./mctdh_specinput <dE> <threshold> * * dE: the adiabatic electronic excitation energy in eV * threshold: the cutoff threshold for including terms in * the Hamiltonian (optional, default zero) * * The following files must be present in the working directory: * * 'gs_freqs' the ground and excited state normal mode frequencies in cm-1 * 'es_freqs' * 'Displacement_Vector.dat' the vector K and the matrix J as output from FCClasses * 'Duschinsky_Matrix.dat' */ int main(int argc, char *argv[]) { /* * Test for the command arguments: */ if (argc < 2) { std::cerr << "ERROR: wrong number of arguments\n"; return 2; } double dE = atof(argv[1]); /* * Test for existence of the required files. */ std::ifstream gsfc("gs_freqs", std::ifstream::in); if (!gsfc.good()) { std::cerr << "ERROR: File 'gs_freqs' could not be opened." << std::endl; return 1; } std::ifstream esfc("es_freqs", std::ifstream::in); if (!esfc.good()) { std::cerr << "ERROR: File 'es_freqs' could not be opened." << std::endl; return 1; } std::ifstream shift("Displacement_Vector.dat", std::ifstream::in); if (!shift.good()) { std::cerr << "ERROR: File 'Displacement_Vector.dat' could not be opened." << std::endl; return 1; } std::ifstream dusch("Duschinsky_Matrix.dat", std::ifstream::in); if (!dusch.good()) { std::cerr << "ERROR: File 'Duschinsky_Matrix.dat' could not be opened." << std::endl; return 1; } /* * Get the number of lines (aka normal modes) in the ground state mode file. * Check, if the excited state mode file contains the same number of modes. */ int Nmodes = std::count(std::istreambuf_iterator<char>(gsfc), std::istreambuf_iterator<char>(), '\n'); if (std::count(std::istreambuf_iterator<char>(esfc), std::istreambuf_iterator<char>(), '\n') != Nmodes) { std::cerr << "ERROR: The files 'gs_freqs' and 'es_freqs' do not contain the same number of lines." << std::endl; return 1; } gsfc.seekg(0); // jump back to start of file esfc.seekg(0); /* * Read the ground and excited state frequencies * as well as the Displacement Vector and the Duschinsky Matrix. */ Eigen::VectorXd v1(Nmodes); Eigen::VectorXd v2(Nmodes); Eigen::VectorXd Korig(Nmodes), K(Nmodes); Eigen::MatrixXd Jorig(Nmodes, Nmodes), J(Nmodes, Nmodes); for (int i = 0; i < 2; i++) shift.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip the first two lines in the K file for (int i = 0; i < 5; i++) dusch.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // and the first five lines in the J file for (int i = 0; i < Nmodes; i++) { int dummyIndex, dummyIndex2; gsfc >> v1(i); esfc >> v2(i); shift >> dummyIndex >> Korig(i); for (int j = 0; j < Nmodes; j++) dusch >> dummyIndex >> dummyIndex2 >> Jorig(j,i); } /* * Calculate our J/K quantities from the FCClasses ones. */ J = Jorig.transpose(); K = -Jorig.transpose() * Korig; /* * Calculate the force constants from the frequencies. */ Eigen::VectorXd f1(Nmodes); Eigen::VectorXd f2(Nmodes); /* * conversion from wavenumbers in cm-1 to mass-weighted force constants * in atomic units * * fac = 4 pi**2 * c**2 * (100 cm/m)**2 * me**2 * a0**4 / hbar**2 */ double factor = 40000.0 * M_PI * M_PI * c0 * c0 * me * me * a0 * a0 * a0 * a0 / (hbar * hbar); for (int i = 0; i < Nmodes; i++) { f1(i) = v1(i) * v1(i) * factor; f2(i) = v2(i) * v2(i) * factor; } /* * Calculate the zero-point energies of the two states and print them out. */ double zpe1 = 0.0; double zpe2 = 0.0; for (int i = 0; i < Nmodes; i++) { zpe1 += 0.5 * sqrt(f1(i)); zpe2 += 0.5 * sqrt(f2(i)); } /* * Open the log file and write some statistics: */ std::ofstream logFile("log"); logFile << "Electronic transition energy: " << dE << std::endl; logFile << "Number of normal modes: " << Nmodes << std::endl; logFile << "Ground state force constants:\n"; Utils::WriteVectorToFile(logFile, f1); logFile << "Excited state force constants:\n"; Utils::WriteVectorToFile(logFile, f2); logFile << "Ground state zero-point Energy: " << zpe1 << "Eh\n"; logFile << "Excited state zero-point Energy: " << zpe2 << "Eh\n"; logFile << "Original Displacement Vector from FCClasses:\n"; Utils::WriteVectorToFile(logFile, Korig); logFile << "Original Duschinsky Matrix from FCClasses:\n"; Utils::WriteMatrixToFile(logFile, Jorig); logFile << "Displacement Vector:\n"; Utils::WriteVectorToFile(logFile, K); logFile << "Duschinsky Matrix:\n"; Utils::WriteMatrixToFile(logFile, J, 3, true); logFile << "Metric of the Duschinsky Matrix:\n"; Utils::WriteMatrixToFile(logFile, J.transpose() * J, 3, true); logFile << "Frobenius norm of the Duschinsky matrix: " << J.norm() << std::endl; logFile << "Determinant of the Duschinsky matrix: " << J.determinant() << std::endl; /* * ############################################################################################ * calculate the new PES parameters * ############################################################################################ * * * Calculate the new force constants. */ Eigen::VectorXd fp(Nmodes); for (int m = 0; m < Nmodes; m++) { fp(m) = 0.0; for (int n = 0; n < Nmodes; n++) fp(m) += f2(n) * J(n,m) * J(n,m); } /* * Calculate the first-order coefficients. */ Eigen::VectorXd kappa(Nmodes); for (int m = 0; m < Nmodes; m++) { kappa(m) = 0.0; for (int n = 0; n < Nmodes; n++) kappa(m) += f2(n) * K(n) * J(n,m); } /* * Calculate the couplings. */ Eigen::MatrixXd phi(Eigen::MatrixXd::Zero(Nmodes,Nmodes)); Eigen::MatrixXd phiFull(Eigen::MatrixXd::Zero(Nmodes,Nmodes)); for (int m = 0; m < Nmodes; m++) { for (int o = m + 1; o < Nmodes; o++) { phi(m,o) = 0.0; phiFull(m,o) = 0.0; for (int n = 0; n < Nmodes; n++) phi(m,o) += f2(n) * J(n,m) * J(n,o); phiFull(m,o) = phi(m,o); phiFull(o,m) = phi(m,o); } phiFull(m,m) = fp(m); } /* * Calculate the energy shifts. */ Eigen::VectorXd d(Nmodes); for (int i = 0; i < Nmodes; i++) d(i) = (0.5 * f2(i) * K(i) * K(i)); /* * write the coupling matrix to the log file: */ logFile << "Coupling matrix phi with the force constants fp on the diagonal:\n"; Utils::WriteMatrixToFile(logFile, phiFull, 3, true); /* * ############################################################################################ * write the MCTDH files * ############################################################################################ * * * Now we can finally write the MCTDH input and operator files :) * First, inquire the desired base-name for the files. */ std::cout << "Enter the base-name for the MCTDH files to be generated.\nThe files <name>.inp and <name>.op will then be written.\n>>> "; std::string basename; std::cin >> basename; std::string inputFileName = basename + ".inp"; std::string operatorFileName = basename + ".op"; if (boost::filesystem::exists(inputFileName) || boost::filesystem::exists(operatorFileName)) { std::cout << "One of the MCTDH files already exists. Should they be overwritten? (Y/N)\n>>> "; char answer; std::cin >> answer; if (answer == 'N' || answer == 'n') return 0; } std::ofstream inputFile(inputFileName); std::ofstream operatorFile(operatorFileName); inputFile.precision(1); operatorFile.precision(8); /* * The run-section */ inputFile << "run-section\n"; inputFile << " name =\n"; inputFile << " propagation\n"; inputFile << " tfinal =\n"; inputFile << " tout =\n"; inputFile << " tpsi =\n"; inputFile << " psi gridpop auto steps graphviz\n"; inputFile << "end-run-section\n\n"; /* * The operator-section */ inputFile << "operator-section\n"; inputFile << " opname = " << basename << std::endl; inputFile << "end-operator-section\n\n"; /* * The mlbasis-section */ // rearrange the modes in order of decreasing coupling Eigen::MatrixXd phi_sort = phi.cwiseAbs(); std::vector<int> sortedModes; while (phi_sort.norm() > 0.0) { Eigen::MatrixXd::Index maxRow, maxCol; phi_sort.maxCoeff(&maxRow, &maxCol); phi_sort(maxRow, maxCol) = 0.0; if (std::find(sortedModes.begin(), sortedModes.end(), maxRow) == sortedModes.end()) sortedModes.push_back(maxRow); if (std::find(sortedModes.begin(), sortedModes.end(), maxCol) == sortedModes.end()) sortedModes.push_back(maxCol); } // determine the required number of layers int layers = 1; while (pow(2.0, layers) < Nmodes) layers++; layers--; // determine the number of nodes in each layer std::vector<int> nodesPerLayer(layers); nodesPerLayer.at(layers - 1) = Nmodes / 2; for (int i = layers - 1; i > 0; i--) { nodesPerLayer.at(i - 1) = nodesPerLayer.at(i) / 2; } inputFile << "mlbasis-section\n"; for (int i = 0; i < Nmodes - 1; i += 2) { if (sortedModes.size() - i == 3) inputFile << " [q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i) + 1 << " q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i+1) + 1 << " q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i+2) + 1 << "]\n"; else inputFile << " [q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i) + 1 << " q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i+1) + 1 << "]\n"; } inputFile << "end-mlbasis-section\n\n"; /* * The pbasis-section */ inputFile << "pbasis-section\n"; for (int i = 0; i < Nmodes; i++) inputFile << " q_" << std::setfill('0') << std::setw(3) << i + 1 << " ho " << std::setw(3) << std::setfill(' ') << lrint(-0.8 * log(fp(i))) << " xi-xf " // // the basis boundarie are -kappa / fp +- 4 / fp**1/4 // << std::fixed << std::setfill(' ') << std::setw(8) << -(kappa(i) / fp(i)) - (2.1 / pow(fp(i), 0.305)) << std::fixed << std::setfill(' ') << std::setw(8) << -(kappa(i) / fp(i)) + (2.1 / pow(fp(i), 0.305)) << std::endl; inputFile << "end-pbasis-section\n\n"; /* * The integrator section */ inputFile << "integrator-section\n"; inputFile << " vmf\n"; inputFile << " abm = 6, 1.0d-7, 0.01d0\n"; inputFile << "end-integrator-section\n\n"; /* * The init wf section */ inputFile << "init_wf-section\n"; inputFile << " build\n"; for (int i = 0; i < Nmodes; i++) inputFile << " q_" << std::setfill('0') << std::setw(3) << i + 1 << " eigenf" << " Eq_" << std::setfill('0') << std::setw(3) << i + 1 << " pop = 1\n"; inputFile << " end-build\n"; inputFile << "end-init_wf-section\n\n"; inputFile << "end-input\n\n"; /* * Now the operator file * * First the op-define section */ operatorFile << "op_define-section\n"; operatorFile << " title\n"; operatorFile << " " << basename << std::endl; operatorFile << " end-title\n"; operatorFile << "end-op_define-section\n\n"; /* * The parameter section */ operatorFile << "parameter-section\n"; // the masses for (int i = 0; i < Nmodes; i++) operatorFile << " mass_q_" << std::setfill('0') << std::setw(3) << i + 1 << " = 1.0\n"; // the ground state force constants for (int i = 0; i < Nmodes; i++) { operatorFile << " f1_" << std::setfill('0') << std::setw(3) << i + 1 << " = "; Utils::WriteFortranNumber(operatorFile, f1(i)); operatorFile << std::endl; } // the excited state force constants for (int i = 0; i < Nmodes; i++) { operatorFile << " f2_" << std::setfill('0') << std::setw(3) << i + 1 << " = "; Utils::WriteFortranNumber(operatorFile, f2(i)); operatorFile << std::endl; } // the new effective excited state force constants for (int i = 0; i < Nmodes; i++) { operatorFile << " fp_" << std::setfill('0') << std::setw(3) << i + 1 << " = "; Utils::WriteFortranNumber(operatorFile, fp(i)); operatorFile << std::endl; } // the couplings for (int i = 0; i < Nmodes; i++) for (int j = i + 1; j < Nmodes; j++) { operatorFile << " phi_" << std::setfill('0') << std::setw(3) << i + 1 << "_" << std::setfill('0') << std::setw(3) << j + 1 << " = "; Utils::WriteFortranNumber(operatorFile, phi(i,j)); operatorFile << std::endl; } // the first-order coefficients (shifts) for (int i = 0; i < Nmodes; i++) { operatorFile << " kappa_" << std::setfill('0') << std::setw(3) << i + 1 << " = "; Utils::WriteFortranNumber(operatorFile, kappa(i)); operatorFile << std::endl; } // the energy offsets for (int i = 0; i < Nmodes; i++) { operatorFile << " d_" << std::setfill('0') << std::setw(3) << i + 1 << " = "; Utils::WriteFortranNumber(operatorFile, d(i)); operatorFile << std::endl; } // the electronic offset minus the ground state ZPE operatorFile << " dE = "; Utils::WriteFortranNumber(operatorFile, dE / Eh2eV - zpe1); operatorFile << "\nend-parameter-section\n\n"; /* * The hamiltonian section */ operatorFile << "hamiltonian-section"; for (int i = 0; i < Nmodes; i++) { if (i % 8 == 0) operatorFile << std::endl << "modes"; operatorFile << " | q_" << std::setfill('0') << std::setw(3) << i + 1; } operatorFile << std::endl; for (int i = 0; i < Nmodes; i++) operatorFile << "1.0 |" << i + 1 << " KE\n"; for (int i = 0; i < Nmodes; i++) operatorFile << "0.5*fp_" << std::setfill('0') << std::setw(3) << i + 1 << " |" << i + 1 << " q^2\n"; for (int i = 0; i < Nmodes; i++) for (int j = i + 1; j < Nmodes; j++) operatorFile << "phi_" << std::setfill('0') << std::setw(3) << i + 1 << "_" << std::setfill('0') << std::setw(3) << j + 1 << " |" << i + 1 << " q" << " |" << j + 1 << " q\n"; for (int i = 0; i < Nmodes; i++) operatorFile << "kappa_" << std::setfill('0') << std::setw(3) << i + 1 << " |" << i + 1 << " q\n"; for (int i = 0; i < Nmodes; i++) operatorFile << "d_" << std::setfill('0') << std::setw(3) << i + 1 << " |" << i + 1 << " 1\n"; operatorFile << "dE |1 1\n"; operatorFile << "end-hamiltonian-section\n\n"; /* * One-dimensional Hamiltonians for the ground state normal modes */ for (int i = 0; i < Nmodes; i++) { operatorFile << "hamiltonian-section_Eq_" << std::setfill('0') << std::setw(3) << i + 1 << std::endl; operatorFile << "usediag\n"; operatorFile << "modes | q_" << std::setfill('0') << std::setw(3) << i + 1 << std::endl; operatorFile << "1.0 |1 KE\n"; operatorFile << "0.5*f1_" << std::setfill('0') << std::setw(3) << i + 1 << " |1 q^2\n"; operatorFile << "end-hamiltonian-section\n\n"; } operatorFile << "end-operator\n"; /* * Diagonalize the coupling matrix to get the force constants back */ Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> phiSolv(phiFull); logFile << "Eigenvalues of the full force constant / coupling matrix:\n"; Utils::WriteVectorToFile(logFile, phiSolv.eigenvalues()); /* * Solve the linear system of the full coupling matrix and the kappa vector * to get the coordinates of the minimum */ Eigen::ColPivHouseholderQR<Eigen::MatrixXd> phiLin(phiFull); Eigen::VectorXd minima = phiLin.solve(-kappa); logFile << "minimum coordinates\n"; Utils::WriteVectorToFile(logFile, minima); /* * calculate the potential energy at the minimum */ double Emin = 0.0; // first, quadratic term: for (int i = 0; i < Nmodes; i++) Emin += 0.5 * fp(i) * minima(i) * minima(i); // second, coupling term: for (int i = 0; i < Nmodes; i++) for (int j = i + 1; j < Nmodes; j++) Emin += phi(i,j) * minima(i) * minima(j); // third, displacement term: for (int i = 0; i < Nmodes; i++) Emin += kappa(i) * minima(i); // fourth, constant term: for (int i = 0; i < Nmodes; i++) Emin += d(i); logFile << "Energy at minimum: " << Emin << std::endl; /* * Calculate the 1st moment of the spectrum analytically */ double moment = dE; for (int i = 0; i < Nmodes; i++) moment += 0.25 * (fp(i) - f1(i)) / sqrt(f1(i)); std::cout << "1st moment of the spectrum: " <<std::setprecision(8) << moment << std::endl; return 0; }
janvc/utility-scripts
progs/source/mctdh_specinput.cpp
C++
gpl-3.0
17,237
CREATE TABLE IF NOT EXISTS `stena` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_user` int(11) NOT NULL, `id_stena` int(11) NOT NULL, `time` int(11) NOT NULL, `msg` varchar(1024) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `read` int(11) DEFAULT '1', PRIMARY KEY (`id`), KEY `time` (`time`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `stena_like` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_user` int(11) NOT NULL, `id_stena` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
open-source-wap/dcms-social
upload/install/db_tables/ank_stena.sql
SQL
gpl-3.0
594
#!/bin/sh # split must fail when given length/count of zero. # Copyright (C) 2003-2019 Free Software Foundation, Inc. # 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 <https://www.gnu.org/licenses/>. . "${srcdir=.}/tests/init.sh"; path_prepend_ ./src print_ver_ split getlimits_ touch in || framework_failure_ split -a 0 in 2> /dev/null || fail=1 returns_ 1 split -b 0 in 2> /dev/null || fail=1 returns_ 1 split -C 0 in 2> /dev/null || fail=1 returns_ 1 split -l 0 in 2> /dev/null || fail=1 returns_ 1 split -n 0 in 2> /dev/null || fail=1 returns_ 1 split -n 1/0 in 2> /dev/null || fail=1 returns_ 1 split -n 0/1 in 2> /dev/null || fail=1 returns_ 1 split -n 2/1 in 2> /dev/null || fail=1 # Make sure -C doesn't create empty files. rm -f x?? || fail=1 echo x | split -C 1 || fail=1 test -f xaa && test -f xab || fail=1 test -f xac && fail=1 # Make sure that the obsolete -N notation still works split -1 in 2> /dev/null || fail=1 # Then make sure that -0 evokes a failure. returns_ 1 split -0 in 2> /dev/null || fail=1 split --lines=$UINTMAX_MAX in || fail=1 split --bytes=$OFF_T_MAX in || fail=1 returns_ 1 split --line-bytes=$OFF_T_OFLOW 2> /dev/null in || fail=1 returns_ 1 split --line-bytes=$SIZE_OFLOW 2> /dev/null in || fail=1 if truncate -s$SIZE_OFLOW large; then # Ensure we can split chunks of a large file on 32 bit hosts split --number=$SIZE_OFLOW/$SIZE_OFLOW large >/dev/null || fail=1 fi split --number=r/$UINTMAX_MAX/$UINTMAX_MAX </dev/null >/dev/null || fail=1 returns_ 1 split --number=r/$UINTMAX_OFLOW </dev/null 2>/dev/null || fail=1 # Make sure that a huge obsolete option evokes the right failure. split -99999999999999999991 2> out # On losing systems (x86 Solaris 5.9 c89), we get a message like this: # split: line count option -9999999999... is too large # while on most, we get this: # split: line count option -99999999999999999991... is too large # so map them both to -99*. sed 's/99[19]*/99*/' out > out-t mv -f out-t out cat <<\EOF > exp split: line count option -99*... is too large EOF compare exp out || fail=1 # Make sure split fails when it can't read input # (the current directory in this case) if ! cat . >/dev/null; then # can't read() directories returns_ 1 split . || fail=1 fi Exit $fail
komh/coreutils-os2
tests/split/fail.sh
Shell
gpl-3.0
2,809
/* * This file is part of rpgmapper. * See the LICENSE file for the software license. * (C) Copyright 2018-2019, Oliver Maurhart, [email protected] */ #ifndef RPGMAPPER_MODEL_LAYER_GRID_LAYER_HPP #define RPGMAPPER_MODEL_LAYER_GRID_LAYER_HPP #include <QColor> #include <QJsonObject> #include <QPainter> #include <rpgmapper/layer/layer.hpp> // fwd namespace rpgmapper::model { class Map; } namespace rpgmapper::model::layer { /** * Objects of the GridLayer class draw grids on a map. */ class GridLayer : public Layer { Q_OBJECT public: /** * Constructs a new GridLayer. * * @param map the map this layer belongs to. */ explicit GridLayer(rpgmapper::model::Map * map); /** * Destructs the GridLayer. */ ~GridLayer() override = default; /** * Draws the grid onto the map. * * @param painter the painter used for drawing. * @param tileSize the size of a single tile square side in pixels. */ void draw(QPainter & painter, int tileSize) const override; /** * Gets the color of the grid. * * @return the color used to paint the grid on the map. */ QColor getColor() const; /** * Extracts this layer as JSON object. * * @return a JSON object holding the layer data. */ QJsonObject getJSON() const override; /** * Applies a new grid color. * * @param color the new grid color. */ void setColor(QColor color); signals: /** * The grid color has changed. * * @param color the new grid color. */ void gridColorChanged(QColor color); private: /** * Draws the map border. * * @param painter the painter used for drawing. * @param tileSize the size of a single tile square side in pixels. */ void drawBorder(QPainter & painter, int tileSize) const; /** * Draws all X-axis. * * @param painter the painter used for drawing. * @param tileSize the size of a single tile square side in pixels. */ void drawXAxis(QPainter & painter, int tileSize) const; /** * Draws all Y-axis. * * @param painter the painter used for drawing. * @param tileSize the size of a single tile square side in pixels. */ void drawYAxis(QPainter & painter, int tileSize) const; }; } #endif
dyle/rpgmapper
include/rpgmapper/layer/grid_layer.hpp
C++
gpl-3.0
2,443
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // extrait automatiquement de http://www.spip.net/trad-lang/ // ** ne pas modifier le fichier ** if (!defined("_ECRIRE_INC_VERSION")) return; $GLOBALS[$GLOBALS['idx_lang']] = array( // B 'bouton_effacer' => 'L&ouml;schen', 'bouton_mettre_a_jour' => 'Auf den neuesten Stand bringen', 'bouton_reset' => 'Zur&uuml;cksetzen', // C 'cfg' => 'CFG', 'choisir_module_a_configurer' => 'W&auml;hlen Sie das zu konfigurierende Modul', 'config_enregistree' => 'Speicherung von <b>@nom@</b> erfolgreich', 'config_supprimee' => 'L&ouml;schen von <b>@nom@</b> erfolgreich', 'configuration_modules' => 'Konfiguration der Module', // E 'erreur_copie_fichier' => 'Die Datei @fichier@ kann nicht an ihren Zielort kopiert werden.', 'erreur_enregistrement' => 'Ein Fehler ist aufgetreten beim Speichern von <b>@nom@</b>', 'erreur_lecture' => 'Fehler beim Lesen von @nom@', 'erreur_open_w_fichier' => 'Fehler beim &Ouml;ffnen der Datei @fichier@ zum Schreiben', 'erreur_suppression' => 'Ein Fehler ist aufgetreten beim L&ouml;schen von <b>@nom@</b>', 'erreur_suppression_fichier' => 'Die Datei @fichier@ kann nicht gel&ouml;scht werden.', 'erreur_type_id' => 'Das Feld @champ@ muss mit einem Buchstaben oder einem Unterstrich beginnen.', 'erreur_type_idnum' => 'Das Feld @champ@ muss numerisch sein.', 'erreur_type_pwd' => 'Das Feld @champ@ ben&ouml;tigt mindestens 5 Zeichen.', // I 'id_manquant' => 'Fehlende ID', 'installation_librairies' => 'Herunterladen der Bibliotheken', 'installation_liste_libs' => 'Liste der Bibliotheken', 'installer_dossier_lib' => 'Sie m&uuml;ssen ein beschreibbares Verzeichnis mit dem Namen @dir@ im Wurzelverzeichnis Ihrer SPIP-Website anlegen.', 'installer_lib_192' => 'Um eine Bibliothek zu installieren, entpacken Sie die ZIP-Datei manuell und kopieren Sie den Inhalt des Archivs in das Verzeichnis @dir@.', // L 'label_activer' => 'Aktivieren', 'label_obligatoire' => 'Pflichtfeld', // N 'nom_table_manquant' => 'Fehlender Name der SQL Tabelle', 'nouveau' => 'Neu', // O 'ok' => 'OK', // P 'pas_de_champs_dans' => 'Kein Feld in @nom@ gefunden', 'pas_de_changement' => 'Keine &Auml;nderung in <b>@nom@</b>', // R 'refus_configuration_administrateur' => 'Nur die Administratoren der Site d&uuml;rfen diese Einstellungen &auml;ndern.', 'refus_configuration_webmestre' => 'Nur ein Webmaster darf diese EInstellungen bearbeiten.', 'reset' => 'Reset', // S 'supprimer' => 'Standardeinstellungen wieder herstellen' ); ?>
VertigeASBL/genrespluriels
plugins/auto/cfg/lang/cfg_de.php
PHP
gpl-3.0
2,563
--Begin Tools.lua :) local SUDO = 71377914 -- put Your ID here! <=== function exi_files(cpath) local files = {} local pth = cpath for k, v in pairs(scandir(pth)) do table.insert(files, v) end return files end local function file_exi(name, cpath) for k,v in pairs(exi_files(cpath)) do if name == v then return true end end return false end local function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') return result end local function index_function(user_id) for k,v in pairs(_config.admins) do if user_id == v[1] then print(k) return k end end -- If not found return false end local function getindex(t,id) for i,v in pairs(t) do if v == id then return i end end return nil end local function already_sudo(user_id) for k,v in pairs(_config.sudo_users) do if user_id == v then return k end end -- If not found return false end local function reload_plugins( ) plugins = {} load_plugins() end local function exi_file() local files = {} local pth = tcpath..'/data/document' for k, v in pairs(scandir(pth)) do if (v:match('.lua$')) then table.insert(files, v) end end return files end local function pl_exi(name) for k,v in pairs(exi_file()) do if name == v then return true end end return false end local function sudolist(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = "*List of sudo users :*\n" else text = "_لیست سودو های ربات :_\n" end for i=1,#sudo_users do text = text..i.." - "..sudo_users[i].."\n" end return text end local function adminlist(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = '*List of bot admins :*\n' else text = "_لیست ادمین های ربات :_\n" end local compare = text local i = 1 for v,user in pairs(_config.admins) do text = text..i..'- '..(user[2] or '')..' ➣ ('..user[1]..')\n' i = i +1 end if compare == text then if not lang then text = '_No_ *admins* _available_' else text = '_ادمینی برای ربات تعیین نشده_' end end return text end local function chat_list(msg) i = 1 local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use #join (ID) to join*\n\n' for k,v in pairsByKeys(data[tostring(groups)]) do local group_id = v if data[tostring(group_id)] then settings = data[tostring(group_id)]['settings'] end for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n:gsub("", "") chat_name = name:gsub("‮", "") group_name_id = name .. '\n(ID: ' ..group_id.. ')\n\n' if name:match("[\216-\219][\128-\191]") then group_info = i..' - \n'..group_name_id else group_info = i..' - '..group_name_id end i = i + 1 end end message = message..group_info end return message end local function botrem(msg) local data = load_data(_config.moderation.data) data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) if redis:get('ExpireDate:'..msg.to.id) then redis:del('ExpireDate:'..msg.to.id) end tdcli.changeChatMemberStatus(msg.to.id, our_id, 'Left', dl_cb, nil) end local function warning(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local expiretime = redis:ttl('ExpireDate:'..msg.to.id) if expiretime == -1 then return else local d = math.floor(expiretime / 86400) + 1 if tonumber(d) == 1 and not is_sudo(msg) and is_mod(msg) then if lang then tdcli.sendMessage(msg.to.id, 0, 1, 'از شارژ گروه 1 روز باقی مانده، برای شارژ مجدد با سودو ربات تماس بگیرید وگرنه با اتمام زمان شارژ، گروه از لیست ربات حذف وربات گروه را ترک خواهد کرد.', 1, 'md') else tdcli.sendMessage(msg.to.id, 0, 1, '_Group 1 day remaining charge, to recharge the robot contact with the sudo. With the completion of charging time, the group removed from the robot list and the robot will leave the group._', 1, 'md') end end end end local function action_by_reply(arg, data) local cmd = arg.cmd if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if cmd == "adminprom" then local function adminprom_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, adminprom_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "admindem" then local function admindem_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local nameid = index_function(tonumber(data.id_)) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, admindem_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "visudo" then local function visudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, visudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "desudo" then local function desudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, desudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end else if lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_username(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not arg.username then return false end if data.id_ then if data.type_.user_.username_ then user_name = '@'..check_markdown(data.type_.user_.username_) else user_name = check_markdown(data.title_) end if cmd == "adminprom" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md") end end if cmd == "admindem" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "visudo" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end if cmd == "desudo" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_id(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not tonumber(arg.user_id) then return false end if data.id_ then if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if cmd == "adminprom" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md") end end if cmd == "admindem" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "visudo" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end if cmd == "desudo" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function pre_process(msg) if msg.to.type ~= 'pv' then local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local gpst = data[tostring(msg.to.id)] local chex = redis:get('CheckExpire::'..msg.to.id) local exd = redis:get('ExpireDate:'..msg.to.id) if gpst and not chex and msg.from.id ~= SUDO and not is_sudo(msg) then redis:set('CheckExpire::'..msg.to.id,true) redis:set('ExpireDate:'..msg.to.id,true) redis:setex('ExpireDate:'..msg.to.id, 86400, true) if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به مدت 1 روز شارژ شد. لطفا با سودو برای شارژ بیشتر تماس بگیرید. در غیر اینصورت گروه شما از لیست ربات حذف و ربات گروه را ترک خواهد کرد._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Group charged 1 day. to recharge the robot contact with the sudo. With the completion of charging time, the group removed from the robot list and the robot will leave the group._', 1, 'md') end end if chex and not exd and msg.from.id ~= SUDO and not is_sudo(msg) then local text1 = 'شارژ این گروه به اتمام رسید \n\nID: <code>'..msg.to.id..'</code>\n\nدر صورتی که میخواهید ربات این گروه را ترک کند از دستور زیر استفاده کنید\n\n/leave '..msg.to.id..'\nبرای جوین دادن توی این گروه میتونی از دستور زیر استفاده کنی:\n/jointo '..msg.to.id..'\n_________________\nدر صورتی که میخواهید گروه رو دوباره شارژ کنید میتوانید از کد های زیر استفاده کنید...\n\n<b>برای شارژ 1 ماهه:</b>\n/plan 1 '..msg.to.id..'\n\n<b>برای شارژ 3 ماهه:</b>\n/plan 2 '..msg.to.id..'\n\n<b>برای شارژ نامحدود:</b>\n/plan 3 '..msg.to.id local text2 = '_شارژ این گروه به پایان رسید. به دلیل عدم شارژ مجدد، گروه از لیست ربات حذف و ربات از گروه خارج میشود._' local text3 = '_Charging finished._\n\n*Group ID:*\n\n*ID:* `'..msg.to.id..'`\n\n*If you want the robot to leave this group use the following command:*\n\n`/Leave '..msg.to.id..'`\n\n*For Join to this group, you can use the following command:*\n\n`/Jointo '..msg.to.id..'`\n\n_________________\n\n_If you want to recharge the group can use the following code:_\n\n*To charge 1 month:*\n\n`/Plan 1 '..msg.to.id..'`\n\n*To charge 3 months:*\n\n`/Plan 2 '..msg.to.id..'`\n\n*For unlimited charge:*\n\n`/Plan 3 '..msg.to.id..'`' local text4 = '_Charging finished. Due to lack of recharge remove the group from the robot list and the robot leave the group._' if lang then tdcli.sendMessage(SUDO, 0, 1, text1, 1, 'html') tdcli.sendMessage(msg.to.id, 0, 1, text2, 1, 'md') else tdcli.sendMessage(SUDO, 0, 1, text3, 1, 'md') tdcli.sendMessage(msg.to.id, 0, 1, text4, 1, 'md') end botrem(msg) else local expiretime = redis:ttl('ExpireDate:'..msg.to.id) + local day = (expiretime / 86400) + if tonumber(day) > 0.208 and not is_sudo(msg) and is_mod(msg) then warning(msg) end end end local function run(msg, matches) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if tonumber(msg.from.id) == SUDO then if matches[1] == "clear cache" or matches[1] == "حذف کش" then run_bash("rm -rf ~/.telegram-cli/data/sticker/*") run_bash("rm -rf ~/.telegram-cli/data/photo/*") run_bash("rm -rf ~/.telegram-cli/data/animation/*") run_bash("rm -rf ~/.telegram-cli/data/video/*") run_bash("rm -rf ~/.telegram-cli/data/audio/*") run_bash("rm -rf ~/.telegram-cli/data/voice/*") run_bash("rm -rf ~/.telegram-cli/data/temp/*") run_bash("rm -rf ~/.telegram-cli/data/thumb/*") run_bash("rm -rf ~/.telegram-cli/data/document/*") run_bash("rm -rf ~/.telegram-cli/data/profile_photo/*") run_bash("rm -rf ~/.telegram-cli/data/encrypted/*") return "*All Cache Has Been Cleared*" end if matches[1] == "visudo" or matches[1] == "تنظیم سودو" then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="visudo"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="visudo"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="visudo"}) end end if matches[1] == "desudo" or matches[1] == "حذف سودو" then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="desudo"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="desudo"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="desudo"}) end end end if is_sudo(msg) then if matches[1]:lower() == 'add' or matches[1]:lower() == 'اضافه' and not redis:get('ExpireDate:'..msg.to.id) then redis:set('ExpireDate:'..msg.to.id,true) redis:setex('ExpireDate:'..msg.to.id, 180, true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id,true) end if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به مدت 3 دقیقه برای اجرای تنظیمات شارژ میباشد._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Group charged 3 minutes for settings._', 1, 'md') end end if matches[1] == 'rem' or matches[1] == 'حذف' then if redis:get('CheckExpire::'..msg.to.id) then + redis:del('CheckExpire::'..msg.to.id) + end redis:del('ExpireDate:'..msg.to.id) end if matches[1]:lower() == 'gid' or matches[1]:lower() == 'ایدی گروه' then tdcli.sendMessage(msg.to.id, msg.id_, 1, '`'..msg.to.id..'`', 1,'md') end if matches[1] == 'leave' or matches[1] == 'خروج' and matches[2] then if lang then tdcli.sendMessage(matches[2], 0, 1, 'ربات با دستور سودو از گروه خارج شد.\nبرای اطلاعات بیشتر با سودو تماس بگیرید.', 1, 'md') tdcli.changeChatMemberStatus(matches[2], our_id, 'Left', dl_cb, nil) tdcli.sendMessage(SUDO, msg.id_, 1, 'ربات با موفقیت از گروه '..matches[2]..' خارج شد.', 1,'md') else tdcli.sendMessage(matches[2], 0, 1, '_Robot left the group._\n*For more information contact The SUDO.*', 1, 'md') tdcli.changeChatMemberStatus(matches[2], our_id, 'Left', dl_cb, nil) tdcli.sendMessage(SUDO, msg.id_, 1, '*Robot left from under group successfully:*\n\n`'..matches[2]..'`', 1,'md') end end if matches[1]:lower() == 'charge' or matches[1]:lower() == 'شارژ' and matches[2] and matches[3] then if string.match(matches[2], '^-%d+$') then if tonumber(matches[3]) > 0 and tonumber(matches[3]) < 1001 then local extime = (tonumber(matches[3]) * 86400) redis:setex('ExpireDate:'..matches[2], extime, true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id,true) end if lang then tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت '..matches[3]..' روز تمدید گردید.', 1, 'md') tdcli.sendMessage(matches[2], 0, 1, 'ربات توسط ادمین به مدت `'..matches[3]..'` روز شارژ شد\nبرای مشاهده زمان شارژ گروه دستور /check استفاده کنید...',1 , 'md') else tdcli.sendMessage(SUDO, 0, 1, '*Recharged successfully in the group:* `'..matches[2]..'`\n_Expire Date:_ `'..matches[3]..'` *Day(s)*', 1, 'md') tdcli.sendMessage(matches[2], 0, 1, '*Robot recharged* `'..matches[3]..'` *day(s)*\n*For checking expire date, send* `/check`',1 , 'md') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_تعداد روزها باید عددی از 1 تا 1000 باشد._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Expire days must be between 1 - 1000_', 1, 'md') end end end end if matches[1]:lower() == 'plan' or matches[1]:lower() == 'پلن' and matches[2] == '1' and matches[3] then if string.match(matches[3], '^-%d+$') then local timeplan1 = 2592000 redis:setex('ExpireDate:'..matches[3], timeplan1, true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id,true) end if lang then tdcli.sendMessage(SUDO, msg.id_, 1, 'پلن 1 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه تا 30 روز دیگر اعتبار دارد! ( 1 ماه )', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, '_ربات با موفقیت فعال شد و تا 30 روز دیگر اعتبار دارد!_', 1, 'md') else tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 1 Successfully Activated!\nThis group recharged with plan 1 for 30 days (1 Month)*', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `30` *Days (1 Month)*', 1, 'md') end end end if matches[1]:lower() == 'plan' or matches[1]:lower() == 'پلن' and matches[2] == '2' and matches[3] then if string.match(matches[3], '^-%d+$') then local timeplan2 = 7776000 redis:setex('ExpireDate:'..matches[3],timeplan2,true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id,true) end if lang then tdcli.sendMessage(SUDO, 0, 1, 'پلن 2 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه تا 90 روز دیگر اعتبار دارد! ( 3 ماه )', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, 'ربات با موفقیت فعال شد و تا 90 روز دیگر اعتبار دارد! ( 3 ماه )', 1, 'md') else tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 2 Successfully Activated!\nThis group recharged with plan 2 for 90 days (3 Month)*', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `90` *Days (3 Months)*', 1, 'md') end end end if matches[1]:lower() == 'plan' or matches[1]:lower() == 'پلن' and matches[2] == '3' and matches[3] then if string.match(matches[3], '^-%d+$') then redis:set('ExpireDate:'..matches[3],true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id,true) end if lang then tdcli.sendMessage(SUDO, msg.id_, 1, 'پلن 3 با موفقیت برای گروه '..matches[3]..' فعال شد\nاین گروه به صورت نامحدود شارژ شد!', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, 'ربات بدون محدودیت فعال شد ! ( نامحدود )', 1, 'md') else tdcli.sendMessage(SUDO, msg.id_, 1, '*Plan 3 Successfully Activated!\nThis group recharged with plan 3 for unlimited*', 1, 'md') tdcli.sendMessage(matches[3], 0, 1, '*Successfully recharged*\n*Expire Date:* `Unlimited`', 1, 'md') end end end if matches[1]:lower() == 'jointo' or matches[1]:lower() == 'اددم کن به' and matches[2] then if string.match(matches[2], '^-%d+$') then if lang then tdcli.sendMessage(SUDO, msg.id_, 1, 'با موفقیت تورو به گروه '..matches[2]..' اضافه کردم.', 1, 'md') tdcli.addChatMember(matches[2], SUDO, 0, dl_cb, nil) tdcli.sendMessage(matches[2], 0, 1, '_سودو به گروه اضافه شد._', 1, 'md') else tdcli.sendMessage(SUDO, msg.id_, 1, '*I added you to this group:*\n\n`'..matches[2]..'`', 1, 'md') tdcli.addChatMember(matches[2], SUDO, 0, dl_cb, nil) tdcli.sendMessage(matches[2], 0, 1, 'Admin Joined!', 1, 'md') end end end end if matches[1]:lower() == 'savefile' or matches[1]:lower() == 'ذخیره فایل' and matches[2] and is_sudo(msg) then if msg.reply_id then local folder = matches[2] function get_filemsg(arg, data) function get_fileinfo(arg,data) if data.content_.ID == 'MessageDocument' or data.content_.ID == 'MessagePhoto' or data.content_.ID == 'MessageSticker' or data.content_.ID == 'MessageAudio' or data.content_.ID == 'MessageVoice' or data.content_.ID == 'MessageVideo' or data.content_.ID == 'MessageAnimation' then if data.content_.ID == 'MessageDocument' then local doc_id = data.content_.document_.document_.id_ local filename = data.content_.document_.file_name_ local pathf = tcpath..'/data/document/'..filename local cpath = tcpath..'/data/document' if file_exi(filename, cpath) then local pfile = folder os.rename(pathf, pfile) file_dl(doc_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>فایل</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>File</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessagePhoto' then local photo_id = data.content_.photo_.sizes_[2].photo_.id_ local file = data.content_.photo_.id_ local pathf = tcpath..'/data/photo/'..file..'_(1).jpg' local cpath = tcpath..'/data/photo' if file_exi(file..'_(1).jpg', cpath) then local pfile = folder os.rename(pathf, pfile) file_dl(photo_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>عکس</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Photo</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessageSticker' then local stpath = data.content_.sticker_.sticker_.path_ local sticker_id = data.content_.sticker_.sticker_.id_ local secp = tostring(tcpath)..'/data/sticker/' local ffile = string.gsub(stpath, '-', '') local fsecp = string.gsub(secp, '-', '') local name = string.gsub(ffile, fsecp, '') if file_exi(name, secp) then local pfile = folder os.rename(stpath, pfile) file_dl(sticker_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>استیکر</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Sticker</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessageAudio' then local audio_id = data.content_.audio_.audio_.id_ local audio_name = data.content_.audio_.file_name_ local pathf = tcpath..'/data/audio/'..audio_name local cpath = tcpath..'/data/audio' if file_exi(audio_name, cpath) then local pfile = folder os.rename(pathf, pfile) file_dl(audio_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>صدای</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Audio</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessageVoice' then local voice_id = data.content_.voice_.voice_.id_ local file = data.content_.voice_.voice_.path_ local secp = tostring(tcpath)..'/data/voice/' local ffile = string.gsub(file, '-', '') local fsecp = string.gsub(secp, '-', '') local name = string.gsub(ffile, fsecp, '') if file_exi(name, secp) then local pfile = folder os.rename(file, pfile) file_dl(voice_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>صوت</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Voice</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessageVideo' then local video_id = data.content_.video_.video_.id_ local file = data.content_.video_.video_.path_ local secp = tostring(tcpath)..'/data/video/' local ffile = string.gsub(file, '-', '') local fsecp = string.gsub(secp, '-', '') local name = string.gsub(ffile, fsecp, '') if file_exi(name, secp) then local pfile = folder os.rename(file, pfile) file_dl(video_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>ویديو</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Video</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end if data.content_.ID == 'MessageAnimation' then local anim_id = data.content_.animation_.animation_.id_ local anim_name = data.content_.animation_.file_name_ local pathf = tcpath..'/data/animation/'..anim_name local cpath = tcpath..'/data/animation' if file_exi(anim_name, cpath) then local pfile = folder os.rename(pathf, pfile) file_dl(anim_id) if lang then tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>تصویر متحرک</b> <code>'..folder..'</code> <b>ذخیره شد.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Gif</b> <code>'..folder..'</code> <b>Has Been Saved.</b>', 1, 'html') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_فایل مورد نظر وجود ندارد. فایل را دوباره ارسال کنید._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end end end else return end end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, get_fileinfo, nil) end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, get_filemsg, nil) end end if msg.to.type == 'channel' or msg.to.type == 'chat' then if matches[1] == 'charge' and matches[2] and not matches[3] and is_sudo(msg) then if tonumber(matches[2]) > 0 and tonumber(matches[2]) < 1001 then local extime = (tonumber(matches[2]) * 86400) redis:setex('ExpireDate:'..msg.to.id, extime, true) if not redis:get('CheckExpire::'..msg.to.id) then redis:set('CheckExpire::'..msg.to.id) end if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, 'ربات با موفقیت تنظیم شد\nمدت فعال بودن ربات در گروه به '..matches[2]..' روز دیگر تنظیم شد...', 1, 'md') tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت `'..msg.to.id..'` روز تمدید گردید.', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, 'ربات با موفقیت تنظیم شد\nمدت فعال بودن ربات در گروه به '..matches[2]..' روز دیگر تنظیم شد...', 1, 'md') tdcli.sendMessage(SUDO, 0, 1, 'ربات در گروه '..matches[2]..' به مدت `'..msg.to.id..'` روز تمدید گردید.', 1, 'md') end else if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_تعداد روزها باید عددی از 1 تا 1000 باشد._', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Expire days must be between 1 - 1000_', 1, 'md') end end end if matches[1]:lower() == 'check' or matches[1]:lower() == 'وضعیت' and is_mod(msg) and not matches[2] then local expi = redis:ttl('ExpireDate:'..msg.to.id) if expi == -1 then if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به صورت نامحدود شارژ میباشد!_', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Unlimited Charging!_', 1, 'md') end else local day = math.floor(expi / 86400) + 1 if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, day..' روز تا اتمام شارژ گروه باقی مانده است.', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '`'..day..'` *Day(s) remaining until Expire.*', 1, 'md') end end end if matches[1] == 'check' and is_mod(msg) and matches[2] then if string.match(matches[2], '^-%d+$') then local expi = redis:ttl('ExpireDate:'..matches[2]) if expi == -1 then if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, '_گروه به صورت نامحدود شارژ میباشد!_', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_Unlimited Charging!_', 1, 'md') end else local day = math.floor(expi / 86400 ) + 1 if lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, day..' روز تا اتمام شارژ گروه باقی مانده است.', 1, 'md') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '`'..day..'` *Day(s) remaining until Expire.*', 1, 'md') end end end end end if matches[1] == "adminprom" or matches[1] == "ادمین ربات" and is_sudo(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="adminprom"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="adminprom"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="adminprom"}) end end if matches[1] == "admindem" or matches[1] == "حذف ادمینی" and is_sudo(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.to.id,cmd="admindem"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="admindem"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="admindem"}) end end if matches[1] == 'creategroup' or matches[1] == 'ساخت گروه' and is_admin(msg) then local text = matches[2] tdcli.createNewGroupChat({[0] = msg.from.id}, text, dl_cb, nil) if not lang then return '_Group Has Been Created!_' else return '_گروه ساخته شد!_' end end if matches[1] == 'createsuper' or matches[1] == 'ساخت سوپر گروه' and is_admin(msg) then local text = matches[2] tdcli.createNewChannelChat(text, 1, '', dl_cb, nil) if not lang then return '_SuperGroup Has Been Created!_' else return '_سوپر گروه ساخته شد!_' end end if matches[1] == 'tosuper' or matches[1] == 'تبدیل به سوپر گروه' and is_admin(msg) then local id = msg.to.id tdcli.migrateGroupChatToChannelChat(id, dl_cb, nil) if not lang then return '_Group Has Been Changed To SuperGroup!_' else return '_گروه به سوپر گروه تبدیل شد!_' end end if matches[1] == 'import' or matches[1] == 'جوین به' and is_admin(msg) then tdcli.importChatInviteLink(matches[2]) if not lang then return '*Done!*' else return '*انجام شد!*' end end if matches[1] == 'setbotname' or matches[1] == 'تنظیم نام ربات' and is_sudo(msg) then tdcli.changeName(matches[2]) if not lang then return '_Bot Name Changed To:_ *'..matches[2]..'*' else return '_اسم ربات تغییر کرد به:_ \n*'..matches[2]..'*' end end if matches[1] == 'setbotusername' or matches[1] == 'تنظیم یوزرنیم ربات' and is_sudo(msg) then tdcli.changeUsername(matches[2]) if not lang then return '_Bot Username Changed To:_ @'..matches[2] else return '_یوزرنیم ربات تغییر کرد به:_ \n@'..matches[2]..'' end end if matches[1] == 'delbotusername' or matches[1] == 'حذف یوزرنیم ربات' and is_sudo(msg) then tdcli.changeUsername('') if not lang then return '*Done!*' else return '*انجام شد!*' end end if matches[1] == 'markread' or matches[1] == 'خواندن پیام' and is_sudo(msg) then if matches[2] == 'on' or matches[2] == 'روشن' then redis:set('markread','on') if not lang then return '_Markread >_ *ON*' else return '_تیک دوم >_ *روشن*' end end if matches[2] == 'off' or matches[2] == 'خاموش' then redis:set('markread','off') if not lang then return '_Markread >_ *OFF*' else return '_تیک دوم >_ *خاموش*' end end end if matches[1] == 'bc' or matches[1] == 'ارسال پیام' and is_admin(msg) then local text = matches[2] tdcli.sendMessage(matches[3], 0, 0, text, 0) end if matches[1] == 'broadcast' or matches[1] == 'ارسال همگانی' and is_sudo(msg) then local data = load_data(_config.moderation.data) local bc = matches[2] for k,v in pairs(data) do tdcli.sendMessage(k, 0, 0, bc, 0) end end if is_sudo(msg) then if matches[1]:lower() == "sendfile" or matches[1]:lower() == "ارسال فایل" and matches[2] and matches[3] then local send_file = "./"..matches[2].."/"..matches[3] tdcli.sendDocument(msg.chat_id_, msg.id_,0, 1, nil, send_file, '🇮🇷ARA BOT🇮🇷', dl_cb, nil) end if matches[1]:lower() == "sendplug" or matches[1]:lower() == 'ارسال پلاگین' and matches[2] then local plug = "./plugins/"..matches[2]..".lua" tdcli.sendDocument(msg.chat_id_, msg.id_,0, 1, nil, plug, '🇮🇷ARA BOT🇮🇷', dl_cb, nil) end end if matches[1]:lower() == 'save' or matches[1]:lower() == 'ذخیره' and matches[2] and is_sudo(msg) then if tonumber(msg.reply_to_message_id_) ~= 0 then function get_filemsg(arg, data) function get_fileinfo(arg,data) if data.content_.ID == 'MessageDocument' then fileid = data.content_.document_.document_.id_ filename = data.content_.document_.file_name_ if (filename:lower():match('.lua$')) then local pathf = tcpath..'/data/document/'..filename if pl_exi(filename) then local pfile = 'plugins/'..matches[2]..'.lua' os.rename(pathf, pfile) tdcli.downloadFile(fileid , dl_cb, nil) tdcli.sendMessage(msg.to.id, msg.id_,1, '<b>Plugin</b> <code>'..matches[2]..'</code> <b>Has Been Saved.</b>', 1, 'html') else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file does not exist. Send file again._', 1, 'md') end else tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This file is not Plugin File._', 1, 'md') end else return end end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, get_fileinfo, nil) end tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, get_filemsg, nil) end end if matches[1] == 'sudolist' or matches[1] == 'لیست سودوها' and is_sudo(msg) then return sudolist(msg) end if matches[1] == 'chats' or matches[1] == 'لیست گروه ها' and is_admin(msg) then return chat_list(msg) end if matches[1]:lower() == 'join' or matches[1] == 'ادد' and is_admin(msg) and matches[2] then tdcli.sendMessage(msg.to.id, msg.id, 1, 'I Invite you in '..matches[2]..'', 1, 'html') tdcli.sendMessage(matches[2], 0, 1, "Admin Joined!🌚", 1, 'html') tdcli.addChatMember(matches[2], msg.from.id, 0, dl_cb, nil) end if matches[1] == 'rem' or matches[1] == 'حذف' and matches[2] and is_admin(msg) then local data = load_data(_config.moderation.data) -- Group configuration removal data[tostring(matches[2])] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(matches[2])] = nil save_data(_config.moderation.data, data) tdcli.sendMessage(matches[2], 0, 1, "Group has been removed by admin command", 1, 'html') return '_Group_ *'..matches[2]..'* _removed_' end if matches[1] == 'adminlist' or matches[1] == 'لیست ادمین ها' and is_admin(msg) then return adminlist(msg) end if matches[1] == 'leave' or matches[1] == 'خروج' and is_admin(msg) then tdcli.changeChatMemberStatus(msg.to.id, our_id, 'Left', dl_cb, nil) end if matches[1] == 'autoleave' or matches[1] == 'خروج خودکار' and is_admin(msg) then local hash = 'auto_leave_bot' --Enable Auto Leave if matches[2] == 'enable' or matches[2] == 'فعال' then redis:del(hash) return 'Auto leave has been enabled' --Disable Auto Leave elseif matches[2] == 'disable' or matches[2] == 'غیرفعال' then redis:set(hash, true) return 'Auto leave has been disabled' --Auto Leave Status elseif matches[2] == 'status' then if not redis:get(hash) then return 'Auto leave is enable' else return 'Auto leave is disable' end end end if matches[1] == 'وضعیت خروج خودکار' and is_admin(msg) then local hash = 'auto_leave_bot' if not redis:get(hash) then return 'Auto leave is enable' else return 'Auto leave is disable' end end if matches[1] == "helptools" or matches[1] == "راهنمای مدیریتی" and is_mod(msg) then if not lang then text = [[ _Sudoer And Admins Beyond Bot Help :_ *!visudo* `[username|id|reply]` _Add Sudo_ *!desudo* `[username|id|reply]` _Demote Sudo_ *!sudolist * _Sudo(s) list_ *!adminprom* `[username|id|reply]` _Add admin for bot_ *!admindem* `[username|id|reply]` _Demote bot admin_ *!adminlist * _Admin(s) list_ *!leave * _Leave current group_ *!autoleave* `[disable/enable]` _Automatically leaves group_ *!creategroup* `[text]` _Create normal group_ *!createsuper* `[text]` _Create supergroup_ *!tosuper * _Convert to supergroup_ *!chats* _List of added groups_ *!join* `[id]` _Adds you to the group_ *!rem* `[id]` _Remove a group from Database_ *!import* `[link]` _Bot joins via link_ *!setbotname* `[text]` _Change bot's name_ *!setbotusername* `[text]` _Change bot's username_ *!delbotusername * _Delete bot's username_ *!markread* `[off/on]` _Second mark_ *!broadcast* `[text]` _Send message to all added groups_ *!bc* `[text] [gpid]` _Send message to a specific group_ *!sendfile* `[folder] [file]` _Send file from folder_ *!sendplug* `[plug]` _Send plugin_ *!save* `[plugin name] [reply]` _Save plugin by reply_ *!savefile* `[address/filename] [reply]` _Save File by reply to specific folder_ *!clear cache* _Clear All Cache Of .telegram-cli/data_ *!check* _Stated Expiration Date_ *!check* `[GroupID]` _Stated Expiration Date Of Specific Group_ *!charge* `[GroupID]` `[Number Of Days]` _Set Expire Time For Specific Group_ *!charge* `[Number Of Days]` _Set Expire Time For Group_ *!jointo* `[GroupID]` _Invite You To Specific Group_ *!leave* `[GroupID]` _Leave Bot From Specific Group_ _You can use_ *[!/#]* _at the beginning of commands._ `This help is only for sudoers/bot admins.` *This means only the sudoers and its bot admins can use mentioned commands.* *Good luck ;)*]] tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md') else text = [[ _راهنمای ادمین و سودو های ربات بیوند:_ *!visudo* `[username|id|reply]` _اضافه کردن سودو_ *!desudo* `[username|id|reply]` _حذف کردن سودو_ *!sudolist* _لیست سودو‌های ربات_ *!adminprom* `[username|id|reply]` _اضافه کردن ادمین به ربات_ *!admindem* `[username|id|reply]` _حذف فرد از ادمینی ربات_ *!adminlist* _لیست ادمین ها_ *!leave* _خارج شدن ربات از گروه_ *!autoleave* `[disable/enable]` _خروج خودکار_ *!creategroup* `[text]` _ساخت گروه ریلم_ *!createsuper* `[text]` _ساخت سوپر گروه_ *!tosuper* _تبدیل به سوپر گروه_ *!chats* _لیست گروه های مدیریتی ربات_ *!join* `[id]` _جوین شدن توسط ربات_ *!rem* `[id]` _حذف گروه ازطریق پنل مدیریتی_ *!import* `[link]` _جوین شدن ربات توسط لینک_ *!setbotname* `[text]` _تغییر اسم ربات_ *!setbotusername* `[text]` _تغییر یوزرنیم ربات_ *!delbotusername* _پاک کردن یوزرنیم ربات_ *!markread* `[off/on]` _تیک دوم_ *!broadcast* `[text]` _فرستادن پیام به تمام گروه های مدیریتی ربات_ *!bc* `[text]` `[gpid]` _ارسال پیام مورد نظر به گروه خاص_ *!sendfile* `[cd]` `[file]` _ارسال فایل موردنظر از پوشه خاص_ *!sendplug* `[plug]` _ارسال پلاگ مورد نظر_ *!save* `[plugin name] [reply]` _ذخیره کردن پلاگین_ *!savefile* `[address/filename] [reply]` _ذخیره کردن فایل در پوشه مورد نظر_ *!clear cache* _پاک کردن کش مسیر .telegram-cli/data_ *!check* _اعلام تاریخ انقضای گروه_ *!check* `[GroupID]` _اعلام تاریخ انقضای گروه مورد نظر_ *!charge* `[GroupID]` `[Number Of Days]` _تنظیم تاریخ انقضای گروه مورد نظر_ *!charge* `[Number Of Days]` _تنظیم تاریخ انقضای گروه_ *!jointo* `[GroupID]` _دعوت شدن شما توسط ربات به گروه مورد نظر_ *!leave* `[GroupID]` _خارج شدن ربات از گروه مورد نظر_ *شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید* _این راهنما فقط برای سودو ها/ادمین های ربات میباشد!_ `این به این معناست که فقط سودو ها/ادمین های ربات میتوانند از دستورات بالا استفاده کنند!` *موفق باشید ;)*]] tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md') end end end return { patterns = { "^[!/#](helptools)$", "^(راهنمای مدیریتی)$", "^[!/#](visudo)$", "^(تنظیم سودو)$", "^[!/#](desudo)$", "^(حذف سودو)$", "^[!/#](sudolist)$", "^(لیست سودوها)$", "^[!/#](visudo) (.*)$", "^(تنظیم سودو) (.*)$", "^[!/#](desudo) (.*)$", "^(حذف سودو) (.*)$", "^[!/#](adminprom)$", "^(ادمین ربات)$", "^[!/#](admindem)$", "^(حذف ادمینی)$", "^[!/#](adminlist)$", "^(لیست ادمین ها)$", "^[!/#](adminprom) (.*)$", "^(ادمین ربات) (.*)$", "^[!/#](admindem) (.*)$", "^(حذف ادمینی) (.*)$", "^[!/#](leave)$", "^(خروج)$", "^[!/#](autoleave) (.*)$", "^(خروج خودکار) (.*)$", "^(وضعیت خروج خودکار)$", "^[!/#](creategroup) (.*)$", "^(ساخت گروه) (.*)$", "^[!/#](createsuper) (.*)$", "^(ساخت سوپر گروه) (.*)$", "^[!/#](tosuper)$", "^(تبدیل به سوپر گروه)$", "^[!/#](chats)$", "^(لیست گروه ها)$", "^[!/#](clear cache)$", "^(حذف کش)$", "^[!/#](join) (.*)$", "^(ادد) (.*)$", "^[!/#](rem) (.*)$", "^(حذف گروه) (.*)$", "^[!/#](import) (.*)$", "^(جوین به) (.*)$", "^[!/#](setbotname) (.*)$", "^(تنظیم نام ربات) (.*)$", "^[!/#](setbotusername) (.*)$", "^(تنظیم یوزرنیم ربات) (.*)$", "^[!/#](delbotusername)$", "^(حذف یوزرنیم ربات)$", "^[!/#](markread) (.*)$", "^(خواندن پیام) (.*)$", "^[!/#](bc) +(.*) (.*)$", "^(ارسال پیام) +(.*) (.*)$", "^[!/#](broadcast) (.*)$", "^(ارسال همگانی) (.*)$", "^[!/#](sendfile) (.*) (.*)$", "^(ارسال فایل) (.*) (.*)$", "^[!/#](save) (.*)$", "^(ذخیره) (.*)$", "^[!/#](sendplug) (.*)$", "^(ارسال پلاگین) (.*)$", "^[!/#](savefile) (.*)$", "^(ذخیره فایل) (.*)$", "^[!/#]([Aa]dd)$", "^(اضافه)$", "^[!/#]([Gg]id)$", "^(ایدی گروه)$", "^[!/#]([Cc]heck)$", "^(وضعیت)$", "^[!/#]([Cc]heck) (.*)$", "^(وضعبت) (.*)$", "^[!/#]([Cc]harge) (.*) (%d+)$", "^(شارژ) (.*) (%d+)$", "^[!/#]([Cc]harge) (%d+)$", "^(شارژ گروه) (%d+)$", "^[!/#]([Jj]ointo) (.*)$", "^(اددم کن به) (.*)$", "^[!/#]([Ll]eave) (.*)$", "^(خروج) (.*)$", "^[!/#]([Pp]lan) ([123]) (.*)$", "^(پلن) ([123]) (.*)$", "^[!/#]([Rr]em)$", "^(حذف)$" }, run = run, pre_process = pre_process } -- #End By @BeyondTeam
ara8586/b.v4
plugins/tools.lua
Lua
gpl-3.0
58,624
--- id: 11 question: Telegram – полезные каналы для чтения ежедневных статей, просмотра работ дизайнеров со всего мира, поиска вдохновения title: Telegram subject: design items: 19 ---
IntellectionStudio/intellection.kz
content/questions/question-design-1.md
Markdown
gpl-3.0
278
var searchData= [ ['handler_5fallocator',['handler_allocator',['../classwebsocketpp_1_1transport_1_1asio_1_1handler__allocator.html',1,'websocketpp::transport::asio']]], ['hash32',['Hash32',['../classnfd_1_1name__tree_1_1Hash32.html',1,'nfd::name_tree']]], ['hash64',['Hash64',['../classnfd_1_1name__tree_1_1Hash64.html',1,'nfd::name_tree']]], ['hash_3c_20ndn_3a_3aname_20_3e',['hash&lt; ndn::Name &gt;',['../structstd_1_1hash_3_01ndn_1_1Name_01_4.html',1,'std']]], ['hash_3c_20ndn_3a_3autil_3a_3aethernet_3a_3aaddress_20_3e',['hash&lt; ndn::util::ethernet::Address &gt;',['../structstd_1_1hash_3_01ndn_1_1util_1_1ethernet_1_1Address_01_4.html',1,'std']]], ['hashable',['Hashable',['../classndn_1_1Hashable.html',1,'ndn']]], ['header',['Header',['../classndn_1_1lp_1_1field__location__tags_1_1Header.html',1,'ndn::lp::field_location_tags']]], ['hierarchicalchecker',['HierarchicalChecker',['../classndn_1_1security_1_1conf_1_1HierarchicalChecker.html',1,'ndn::security::conf']]], ['hijacker',['Hijacker',['../classns3_1_1Hijacker.html',1,'ns3']]], ['httpexception',['HttpException',['../classHttpException.html',1,'']]], ['hybi00',['hybi00',['../classwebsocketpp_1_1processor_1_1hybi00.html',1,'websocketpp::processor']]], ['hybi00_3c_20stub_5fconfig_20_3e',['hybi00&lt; stub_config &gt;',['../classwebsocketpp_1_1processor_1_1hybi00.html',1,'websocketpp::processor']]], ['hybi07',['hybi07',['../classwebsocketpp_1_1processor_1_1hybi07.html',1,'websocketpp::processor']]], ['hybi08',['hybi08',['../classwebsocketpp_1_1processor_1_1hybi08.html',1,'websocketpp::processor']]], ['hybi13',['hybi13',['../classwebsocketpp_1_1processor_1_1hybi13.html',1,'websocketpp::processor']]], ['hybi13_3c_20stub_5fconfig_20_3e',['hybi13&lt; stub_config &gt;',['../classwebsocketpp_1_1processor_1_1hybi13.html',1,'websocketpp::processor']]], ['hybi13_3c_20stub_5fconfig_5fext_20_3e',['hybi13&lt; stub_config_ext &gt;',['../classwebsocketpp_1_1processor_1_1hybi13.html',1,'websocketpp::processor']]], ['hyperkeylocatornamechecker',['HyperKeyLocatorNameChecker',['../classndn_1_1security_1_1conf_1_1HyperKeyLocatorNameChecker.html',1,'ndn::security::conf']]] ];
nsol-nmsu/ndnSIM
docs/icens/html/search/classes_7.js
JavaScript
gpl-3.0
2,179
/* * qrest * * Copyright (C) 2008-2012 - Frédéric CORNU * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QT_NO_DEBUG #include <QDebug> #endif #include "progressPie.h" #include "../../../constants.h" #include <QPaintEvent> #include <QPainter> #include <QLineEdit> //////////////////////////////////////////////////////////////////////////// // // INIT // //////////////////////////////////////////////////////////////////////////// ProgressPie::ProgressPie(QWidget* parent) : QWidget(parent), _value(Constants::PROGRESSPIE_DEFAULT_VALUE), _pRedBrush(new QBrush(Qt::red)), _pGreenBrush(new QBrush(Qt::darkGreen)) { /* * we want this widget to be enclosed within a square that has the same * height as a default QLineEdit. */ QLineEdit usedForSizeHintHeight; int size = usedForSizeHintHeight.sizeHint().height(); setFixedSize(size, size); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } ProgressPie::~ProgressPie() { delete _pGreenBrush; delete _pRedBrush; } //////////////////////////////////////////////////////////////////////////// // // OVERRIDES // //////////////////////////////////////////////////////////////////////////// void ProgressPie::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.setPen(Qt::NoPen); painter.setRenderHint(QPainter::Antialiasing, true); /* * Qt draws angles with 1/16 degree precision. */ static const int STEPS = 16; /* * pie is drawn starting from top, so we set startAngle at -270° */ static const int TOP = -270* STEPS ; /* * how many degrees in a full circle ? */ static const int FULL_CIRCLE = 360; /* * draw red circle */ painter.setBrush(*_pRedBrush); painter.drawEllipse(this->visibleRegion().boundingRect()); /* * draw green pie */ painter.setBrush(*_pGreenBrush); painter.drawPie(this->visibleRegion().boundingRect(), TOP, static_cast<int> (-FULL_CIRCLE * _value * STEPS)); event->accept(); } //////////////////////////////////////////////////////////////////////////// // // SLOTS // //////////////////////////////////////////////////////////////////////////// void ProgressPie::setValue(const double value) { _value = value; repaint(); }
deufrai/qrest_deb_packaging
src/gui/widgets/custom/progressPie.cpp
C++
gpl-3.0
3,060
package com.dotmarketing.servlets; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dotcms.repackage.commons_lang_2_4.org.apache.commons.lang.time.FastDateFormat; import com.dotmarketing.util.Constants; import com.dotmarketing.util.Logger; import com.liferay.util.FileUtil; public class IconServlet extends HttpServlet { private static final long serialVersionUID = 1L; FastDateFormat df = FastDateFormat.getInstance(Constants.RFC2822_FORMAT, TimeZone.getTimeZone("GMT"), Locale.US); protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String i = request.getParameter("i"); if(i !=null && i.length() > 0 && i.indexOf('.') < 0){ i="." + i; } String icon = com.dotmarketing.util.UtilMethods.getFileExtension(i); java.text.SimpleDateFormat httpDate = new java.text.SimpleDateFormat(Constants.RFC2822_FORMAT, Locale.US); httpDate.setTimeZone(TimeZone.getDefault()); // -------- HTTP HEADER/ MODIFIED SINCE CODE -----------// Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); c.setTime(new Date(0)); Date _lastModified = c.getTime(); String _eTag = "dot:icon-" + icon + "-" + _lastModified.getTime() ; String ifModifiedSince = request.getHeader("If-Modified-Since"); String ifNoneMatch = request.getHeader("If-None-Match"); /* * If the etag matches then the file is the same * */ if(ifNoneMatch != null){ if(_eTag.equals(ifNoneMatch) || ifNoneMatch.equals("*")){ response.setStatus(HttpServletResponse.SC_NOT_MODIFIED ); return; } } /* Using the If-Modified-Since Header */ if(ifModifiedSince != null){ try{ Date ifModifiedSinceDate = httpDate.parse(ifModifiedSince); if(_lastModified.getTime() <= ifModifiedSinceDate.getTime()){ response.setStatus(HttpServletResponse.SC_NOT_MODIFIED ); return; } } catch(Exception e){} } response.setHeader("Last-Modified", df.format(_lastModified)); response.setHeader("ETag", "\"" + _eTag +"\""); ServletOutputStream out = response.getOutputStream(); response.setContentType("image/png"); java.util.GregorianCalendar expiration = new java.util.GregorianCalendar(); expiration.add(java.util.Calendar.YEAR, 1); response.setHeader("Expires", httpDate.format(expiration.getTime())); response.setHeader("Cache-Control", "max-age=" +(60*60*24*30*12)); File f = new File(FileUtil.getRealPath("/html/images/icons/" + icon + ".png")); if(!f.exists()){ f = new File(FileUtil.getRealPath("/html/images/icons/ukn.png")); } response.setHeader("Content-Length", String.valueOf(f.length())); BufferedInputStream fis = null; try { fis = new BufferedInputStream(new FileInputStream(f)); int n; while ((n = fis.available()) > 0) { byte[] b = new byte[n]; int result = fis.read(b); if (result == -1) break; out.write(b); } // end while } catch (Exception e) { Logger.error(this.getClass(), "cannot read:" + f.toString()); } finally { if (fis != null) fis.close(); f=null; } out.close(); } }
austindlawless/dotCMS
src/com/dotmarketing/servlets/IconServlet.java
Java
gpl-3.0
3,815
# Copyright (C) 2011-2012 Google Inc. # 2016 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe 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. # # YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import # Not installing aliases from python-future; it's unreliable and slow. from builtins import * # noqa from future.utils import iterkeys import vim import os import json import re from collections import defaultdict from ycmd.utils import ( ByteOffsetToCodepointOffset, GetCurrentDirectory, JoinLinesAsUnicode, ToBytes, ToUnicode ) from ycmd import user_options_store BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit', 'horizontal-split' : 'split', 'vertical-split' : 'vsplit', 'new-tab' : 'tabedit' } FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT = ( 'The requested operation will apply changes to {0} files which are not ' 'currently open. This will therefore open {0} new files in the hidden ' 'buffers. The quickfix list can then be used to review the changes. No ' 'files will be written to disk. Do you wish to continue?' ) potential_hint_triggers = list( map( ToBytes, [ '[', '(', ',', ':' ] ) ) def CanComplete(): """Returns whether it's appropriate to provide any completion at the current line and column.""" try: line, column = LineAndColumnAfterLastNonWhitespace() except TypeError: return False if ( line, column ) == CurrentLineAndColumn(): return True return ( ToBytes( vim.current.buffer[ line ][ column - 1 ] ) in potential_hint_triggers ) def SnappedLineAndColumn(): """Will return CurrentLineAndColumn(), except when there's solely whitespace between caret and a potential hint trigger, where it "snaps to trigger", returning hint trigger's line and column instead.""" try: line, column = LineAndColumnAfterLastNonWhitespace() except TypeError: return CurrentLineAndColumn() if ( ToBytes( vim.current.buffer[ line ][ column - 1 ] ) in potential_hint_triggers ): return ( line, column ) return CurrentLineAndColumn() def LineAndColumnAfterLastNonWhitespace(): line, column = CurrentLineAndColumn() line_value = vim.current.line[ :column ].rstrip() while not line_value: line = line - 1 if line == -1: return None line_value = vim.current.buffer[ line ].rstrip() return line, len( line_value ) NO_SELECTION_MADE_MSG = "No valid selection was made; aborting." def CurrentLineAndColumn(): """Returns the 0-based current line and 0-based current column.""" # See the comment in CurrentColumn about the calculation for the line and # column number line, column = vim.current.window.cursor line -= 1 return line, column def CurrentColumn(): """Returns the 0-based current column. Do NOT access the CurrentColumn in vim.current.line. It doesn't exist yet when the cursor is at the end of the line. Only the chars before the current column exist in vim.current.line.""" # vim's columns are 1-based while vim.current.line columns are 0-based # ... but vim.current.window.cursor (which returns a (line, column) tuple) # columns are 0-based, while the line from that same tuple is 1-based. # vim.buffers buffer objects OTOH have 0-based lines and columns. # Pigs have wings and I'm a loopy purple duck. Everything makes sense now. return vim.current.window.cursor[ 1 ] def CurrentLineContents(): return ToUnicode( vim.current.line ) def CurrentLineContentsAndCodepointColumn(): """Returns the line contents as a unicode string and the 0-based current column as a codepoint offset. If the current column is outside the line, returns the column position at the end of the line.""" line = CurrentLineContents() byte_column = CurrentColumn() # ByteOffsetToCodepointOffset expects 1-based offset. column = ByteOffsetToCodepointOffset( line, byte_column + 1 ) - 1 return line, column def TextAfterCursor(): """Returns the text after CurrentColumn.""" return ToUnicode( vim.current.line[ CurrentColumn(): ] ) def TextBeforeCursor(): """Returns the text before CurrentColumn.""" return ToUnicode( vim.current.line[ :CurrentColumn() ] ) # Note the difference between buffer OPTIONS and VARIABLES; the two are not # the same. def GetBufferOption( buffer_object, option ): # NOTE: We used to check for the 'options' property on the buffer_object which # is available in recent versions of Vim and would then use: # # buffer_object.options[ option ] # # to read the value, BUT this caused annoying flickering when the # buffer_object was a hidden buffer (with option = 'ft'). This was all due to # a Vim bug. Until this is fixed, we won't use it. to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option ) return GetVariableValue( to_eval ) def BufferModified( buffer_object ): return bool( int( GetBufferOption( buffer_object, 'mod' ) ) ) def GetUnsavedAndSpecifiedBufferData( including_filepath ): """Build part of the request containing the contents and filetypes of all dirty buffers as well as the buffer with filepath |including_filepath|.""" buffers_data = {} for buffer_object in vim.buffers: buffer_filepath = GetBufferFilepath( buffer_object ) if not ( BufferModified( buffer_object ) or buffer_filepath == including_filepath ): continue buffers_data[ buffer_filepath ] = { # Add a newline to match what gets saved to disk. See #1455 for details. 'contents': JoinLinesAsUnicode( buffer_object ) + '\n', 'filetypes': FiletypesForBuffer( buffer_object ) } return buffers_data def GetBufferNumberForFilename( filename, open_file_if_needed = True ): return GetIntValue( u"bufnr('{0}', {1})".format( EscapeForVim( os.path.realpath( filename ) ), int( open_file_if_needed ) ) ) def GetCurrentBufferFilepath(): return GetBufferFilepath( vim.current.buffer ) def BufferIsVisible( buffer_number ): if buffer_number < 0: return False window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) ) return window_number != -1 def GetBufferFilepath( buffer_object ): if buffer_object.name: return buffer_object.name # Buffers that have just been created by a command like :enew don't have any # buffer name so we use the buffer number for that. return os.path.join( GetCurrentDirectory(), str( buffer_object.number ) ) def GetCurrentBufferNumber(): return vim.current.buffer.number def GetBufferChangedTick( bufnr ): return GetIntValue( 'getbufvar({0}, "changedtick")'.format( bufnr ) ) def UnplaceSignInBuffer( buffer_number, sign_id ): if buffer_number < 0: return vim.command( 'try | exec "sign unplace {0} buffer={1}" | catch /E158/ | endtry'.format( sign_id, buffer_number ) ) def PlaceSign( sign_id, line_num, buffer_num, is_error = True ): # libclang can give us diagnostics that point "outside" the file; Vim borks # on these. if line_num < 1: line_num = 1 sign_name = 'YcmError' if is_error else 'YcmWarning' vim.command( 'sign place {0} name={1} line={2} buffer={3}'.format( sign_id, sign_name, line_num, buffer_num ) ) def ClearYcmSyntaxMatches(): matches = VimExpressionToPythonType( 'getmatches()' ) for match in matches: if match[ 'group' ].startswith( 'Ycm' ): vim.eval( 'matchdelete({0})'.format( match[ 'id' ] ) ) def AddDiagnosticSyntaxMatch( line_num, column_num, line_end_num = None, column_end_num = None, is_error = True ): """Highlight a range in the current window starting from (|line_num|, |column_num|) included to (|line_end_num|, |column_end_num|) excluded. If |line_end_num| or |column_end_num| are not given, highlight the character at (|line_num|, |column_num|). Both line and column numbers are 1-based. Return the ID of the newly added match.""" group = 'YcmErrorSection' if is_error else 'YcmWarningSection' line_num, column_num = LineAndColumnNumbersClamped( line_num, column_num ) if not line_end_num or not column_end_num: return GetIntValue( "matchadd('{0}', '\%{1}l\%{2}c')".format( group, line_num, column_num ) ) # -1 and then +1 to account for column end not included in the range. line_end_num, column_end_num = LineAndColumnNumbersClamped( line_end_num, column_end_num - 1 ) column_end_num += 1 return GetIntValue( "matchadd('{0}', '\%{1}l\%{2}c\_.\\{{-}}\%{3}l\%{4}c')".format( group, line_num, column_num, line_end_num, column_end_num ) ) # Clamps the line and column numbers so that they are not past the contents of # the buffer. Numbers are 1-based byte offsets. def LineAndColumnNumbersClamped( line_num, column_num ): new_line_num = line_num new_column_num = column_num max_line = len( vim.current.buffer ) if line_num and line_num > max_line: new_line_num = max_line max_column = len( vim.current.buffer[ new_line_num - 1 ] ) if column_num and column_num > max_column: new_column_num = max_column return new_line_num, new_column_num def SetLocationList( diagnostics ): """Populate the location list with diagnostics. Diagnostics should be in qflist format; see ":h setqflist" for details.""" vim.eval( 'setloclist( 0, {0} )'.format( json.dumps( diagnostics ) ) ) def OpenLocationList( focus = False, autoclose = False ): """Open the location list to full width at the bottom of the screen with its height automatically set to fit all entries. This behavior can be overridden by using the YcmLocationOpened autocommand. When focus is set to True, the location list window becomes the active window. When autoclose is set to True, the location list window is automatically closed after an entry is selected.""" vim.command( 'botright lopen' ) SetFittingHeightForCurrentWindow() if autoclose: # This autocommand is automatically removed when the location list window is # closed. vim.command( 'au WinLeave <buffer> q' ) if VariableExists( '#User#YcmLocationOpened' ): vim.command( 'doautocmd User YcmLocationOpened' ) if not focus: JumpToPreviousWindow() def SetQuickFixList( quickfix_list ): """Populate the quickfix list and open it. List should be in qflist format: see ":h setqflist" for details.""" vim.eval( 'setqflist( {0} )'.format( json.dumps( quickfix_list ) ) ) def OpenQuickFixList( focus = False, autoclose = False ): """Open the quickfix list to full width at the bottom of the screen with its height automatically set to fit all entries. This behavior can be overridden by using the YcmQuickFixOpened autocommand. See the OpenLocationList function for the focus and autoclose options.""" vim.command( 'botright copen' ) SetFittingHeightForCurrentWindow() if autoclose: # This autocommand is automatically removed when the quickfix window is # closed. vim.command( 'au WinLeave <buffer> q' ) if VariableExists( '#User#YcmQuickFixOpened' ): vim.command( 'doautocmd User YcmQuickFixOpened' ) if not focus: JumpToPreviousWindow() def SetFittingHeightForCurrentWindow(): window_width = GetIntValue( 'winwidth( 0 )' ) fitting_height = 0 for line in vim.current.buffer: fitting_height += len( line ) // window_width + 1 vim.command( '{0}wincmd _'.format( fitting_height ) ) def ConvertDiagnosticsToQfList( diagnostics ): def ConvertDiagnosticToQfFormat( diagnostic ): # See :h getqflist for a description of the dictionary fields. # Note that, as usual, Vim is completely inconsistent about whether # line/column numbers are 1 or 0 based in its various APIs. Here, it wants # them to be 1-based. The documentation states quite clearly that it # expects a byte offset, by which it means "1-based column number" as # described in :h getqflist ("the first column is 1"). location = diagnostic[ 'location' ] line_num = location[ 'line_num' ] # libclang can give us diagnostics that point "outside" the file; Vim borks # on these. if line_num < 1: line_num = 1 text = diagnostic[ 'text' ] if diagnostic.get( 'fixit_available', False ): text += ' (FixIt available)' return { 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ), 'lnum' : line_num, 'col' : location[ 'column_num' ], 'text' : text, 'type' : diagnostic[ 'kind' ][ 0 ], 'valid' : 1 } return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ] def GetVimGlobalsKeys(): return vim.eval( 'keys( g: )' ) def VimExpressionToPythonType( vim_expression ): """Returns a Python type from the return value of the supplied Vim expression. If the expression returns a list, dict or other non-string type, then it is returned unmodified. If the string return can be converted to an integer, returns an integer, otherwise returns the result converted to a Unicode string.""" result = vim.eval( vim_expression ) if not ( isinstance( result, str ) or isinstance( result, bytes ) ): return result try: return int( result ) except ValueError: return ToUnicode( result ) def HiddenEnabled( buffer_object ): return bool( int( GetBufferOption( buffer_object, 'hid' ) ) ) def BufferIsUsable( buffer_object ): return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object ) def EscapedFilepath( filepath ): return filepath.replace( ' ' , r'\ ' ) # Both |line| and |column| need to be 1-based def TryJumpLocationInOpenedTab( filename, line, column ): filepath = os.path.realpath( filename ) for tab in vim.tabpages: for win in tab.windows: if win.buffer.name == filepath: vim.current.tabpage = tab vim.current.window = win vim.current.window.cursor = ( line, column - 1 ) # Center the screen on the jumped-to location vim.command( 'normal! zz' ) return True # 'filename' is not opened in any tab pages return False # Maps User command to vim command def GetVimCommand( user_command, default = 'edit' ): vim_command = BUFFER_COMMAND_MAP.get( user_command, default ) if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ): vim_command = 'split' return vim_command # Both |line| and |column| need to be 1-based def JumpToLocation( filename, line, column ): # Add an entry to the jumplist vim.command( "normal! m'" ) if filename != GetCurrentBufferFilepath(): # We prefix the command with 'keepjumps' so that opening the file is not # recorded in the jumplist. So when we open the file and move the cursor to # a location in it, the user can use CTRL-O to jump back to the original # location, not to the start of the newly opened file. # Sadly this fails on random occasions and the undesired jump remains in the # jumplist. user_command = user_options_store.Value( 'goto_buffer_command' ) if user_command == 'new-or-existing-tab': if TryJumpLocationInOpenedTab( filename, line, column ): return user_command = 'new-tab' vim_command = GetVimCommand( user_command ) try: vim.command( 'keepjumps {0} {1}'.format( vim_command, EscapedFilepath( filename ) ) ) # When the file we are trying to jump to has a swap file # Vim opens swap-exists-choices dialog and throws vim.error with E325 error, # or KeyboardInterrupt after user selects one of the options. except vim.error as e: if 'E325' not in str( e ): raise # Do nothing if the target file is still not opened (user chose (Q)uit) if filename != GetCurrentBufferFilepath(): return # Thrown when user chooses (A)bort in .swp message box except KeyboardInterrupt: return vim.current.window.cursor = ( line, column - 1 ) # Center the screen on the jumped-to location vim.command( 'normal! zz' ) def NumLinesInBuffer( buffer_object ): # This is actually less than obvious, that's why it's wrapped in a function return len( buffer_object ) # Calling this function from the non-GUI thread will sometimes crash Vim. At # the time of writing, YCM only uses the GUI thread inside Vim (this used to # not be the case). def PostVimMessage( message, warning = True, truncate = False ): """Display a message on the Vim status line. By default, the message is highlighted and logged to Vim command-line history (see :h history). Unset the |warning| parameter to disable this behavior. Set the |truncate| parameter to avoid hit-enter prompts (see :h hit-enter) when the message is longer than the window width.""" echo_command = 'echom' if warning else 'echo' # Displaying a new message while previous ones are still on the status line # might lead to a hit-enter prompt or the message appearing without a # newline so we do a redraw first. vim.command( 'redraw' ) if warning: vim.command( 'echohl WarningMsg' ) message = ToUnicode( message ) if truncate: vim_width = GetIntValue( '&columns' ) message = message.replace( '\n', ' ' ) if len( message ) > vim_width: message = message[ : vim_width - 4 ] + '...' old_ruler = GetIntValue( '&ruler' ) old_showcmd = GetIntValue( '&showcmd' ) vim.command( 'set noruler noshowcmd' ) vim.command( "{0} '{1}'".format( echo_command, EscapeForVim( message ) ) ) SetVariableValue( '&ruler', old_ruler ) SetVariableValue( '&showcmd', old_showcmd ) else: for line in message.split( '\n' ): vim.command( "{0} '{1}'".format( echo_command, EscapeForVim( line ) ) ) if warning: vim.command( 'echohl None' ) def PresentDialog( message, choices, default_choice_index = 0 ): """Presents the user with a dialog where a choice can be made. This will be a dialog for gvim users or a question in the message buffer for vim users or if `set guioptions+=c` was used. choices is list of alternatives. default_choice_index is the 0-based index of the default element that will get choosen if the user hits <CR>. Use -1 for no default. PresentDialog will return a 0-based index into the list or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc. If you are presenting a list of options for the user to choose from, such as a list of imports, or lines to insert (etc.), SelectFromList is a better option. See also: :help confirm() in vim (Note that vim uses 1-based indexes) Example call: PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"]) Is this a nice example? [Y]es, (N)o, May(b)e:""" to_eval = "confirm('{0}', '{1}', {2})".format( EscapeForVim( ToUnicode( message ) ), EscapeForVim( ToUnicode( "\n" .join( choices ) ) ), default_choice_index + 1 ) try: return GetIntValue( to_eval ) - 1 except KeyboardInterrupt: return -1 def Confirm( message ): """Display |message| with Ok/Cancel operations. Returns True if the user selects Ok""" return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 ) def SelectFromList( prompt, items ): """Ask the user to select an item from the list |items|. Presents the user with |prompt| followed by a numbered list of |items|, from which they select one. The user is asked to enter the number of an item or click it. |items| should not contain leading ordinals: they are added automatically. Returns the 0-based index in the list |items| that the user selected, or a negative number if no valid item was selected. See also :help inputlist().""" vim_items = [ prompt ] vim_items.extend( [ "{0}: {1}".format( i + 1, item ) for i, item in enumerate( items ) ] ) # The vim documentation warns not to present lists larger than the number of # lines of display. This is sound advice, but there really isn't any sensible # thing we can do in that scenario. Testing shows that Vim just pages the # message; that behaviour is as good as any, so we don't manipulate the list, # or attempt to page it. # For an explanation of the purpose of inputsave() / inputrestore(), # see :help input(). Briefly, it makes inputlist() work as part of a mapping. vim.eval( 'inputsave()' ) try: # Vim returns the number the user entered, or the line number the user # clicked. This may be wildly out of range for our list. It might even be # negative. # # The first item is index 0, and this maps to our "prompt", so we subtract 1 # from the result and return that, assuming it is within the range of the # supplied list. If not, we return negative. # # See :help input() for explanation of the use of inputsave() and inpput # restore(). It is done in try/finally in case vim.eval ever throws an # exception (such as KeyboardInterrupt) selected = GetIntValue( "inputlist( " + json.dumps( vim_items ) + " )" ) - 1 except KeyboardInterrupt: selected = -1 finally: vim.eval( 'inputrestore()' ) if selected < 0 or selected >= len( items ): # User selected something outside of the range raise RuntimeError( NO_SELECTION_MADE_MSG ) return selected def EscapeForVim( text ): return ToUnicode( text.replace( "'", "''" ) ) def CurrentFiletypes(): return VimExpressionToPythonType( "&filetype" ).split( '.' ) def GetBufferFiletypes( bufnr ): command = 'getbufvar({0}, "&ft")'.format( bufnr ) return VimExpressionToPythonType( command ).split( '.' ) def FiletypesForBuffer( buffer_object ): # NOTE: Getting &ft for other buffers only works when the buffer has been # visited by the user at least once, which is true for modified buffers return GetBufferOption( buffer_object, 'ft' ).split( '.' ) def VariableExists( variable ): return GetBoolValue( "exists( '{0}' )".format( EscapeForVim( variable ) ) ) def SetVariableValue( variable, value ): vim.command( "let {0} = {1}".format( variable, json.dumps( value ) ) ) def GetVariableValue( variable ): return vim.eval( variable ) def GetBoolValue( variable ): return bool( int( vim.eval( variable ) ) ) def GetIntValue( variable ): return int( vim.eval( variable ) ) def _SortChunksByFile( chunks ): """Sort the members of the list |chunks| (which must be a list of dictionaries conforming to ycmd.responses.FixItChunk) by their filepath. Returns a new list in arbitrary order.""" chunks_by_file = defaultdict( list ) for chunk in chunks: filepath = chunk[ 'range' ][ 'start' ][ 'filepath' ] chunks_by_file[ filepath ].append( chunk ) return chunks_by_file def _GetNumNonVisibleFiles( file_list ): """Returns the number of file in the iterable list of files |file_list| which are not curerntly open in visible windows""" return len( [ f for f in file_list if not BufferIsVisible( GetBufferNumberForFilename( f, False ) ) ] ) def _OpenFileInSplitIfNeeded( filepath ): """Ensure that the supplied filepath is open in a visible window, opening a new split if required. Returns the buffer number of the file and an indication of whether or not a new split was opened. If the supplied filename is already open in a visible window, return just return its buffer number. If the supplied file is not visible in a window in the current tab, opens it in a new vertical split. Returns a tuple of ( buffer_num, split_was_opened ) indicating the buffer number and whether or not this method created a new split. If the user opts not to open a file, or if opening fails, this method raises RuntimeError, otherwise, guarantees to return a visible buffer number in buffer_num.""" buffer_num = GetBufferNumberForFilename( filepath, False ) # We only apply changes in the current tab page (i.e. "visible" windows). # Applying changes in tabs does not lead to a better user experience, as the # quickfix list no longer works as you might expect (doesn't jump into other # tabs), and the complexity of choosing where to apply edits is significant. if BufferIsVisible( buffer_num ): # file is already open and visible, just return that buffer number (and an # idicator that we *didn't* open a split) return ( buffer_num, False ) # The file is not open in a visible window, so we open it in a split. # We open the file with a small, fixed height. This means that we don't # make the current buffer the smallest after a series of splits. OpenFilename( filepath, { 'focus': True, 'fix': True, 'size': GetIntValue( '&previewheight' ), } ) # OpenFilename returns us to the original cursor location. This is what we # want, because we don't want to disorientate the user, but we do need to # know the (now open) buffer number for the filename buffer_num = GetBufferNumberForFilename( filepath, False ) if not BufferIsVisible( buffer_num ): # This happens, for example, if there is a swap file and the user # selects the "Quit" or "Abort" options. We just raise an exception to # make it clear to the user that the abort has left potentially # partially-applied changes. raise RuntimeError( 'Unable to open file: {0}\nFixIt/Refactor operation ' 'aborted prior to completion. Your files have not been ' 'fully updated. Please use undo commands to revert the ' 'applied changes.'.format( filepath ) ) # We opened this file in a split return ( buffer_num, True ) def ReplaceChunks( chunks ): """Apply the source file deltas supplied in |chunks| to arbitrary files. |chunks| is a list of changes defined by ycmd.responses.FixItChunk, which may apply arbitrary modifications to arbitrary files. If a file specified in a particular chunk is not currently open in a visible buffer (i.e., one in a window visible in the current tab), we: - issue a warning to the user that we're going to open new files (and offer her the option to abort cleanly) - open the file in a new split, make the changes, then hide the buffer. If for some reason a file could not be opened or changed, raises RuntimeError. Otherwise, returns no meaningful value.""" # We apply the edits file-wise for efficiency, and because we must track the # file-wise offset deltas (caused by the modifications to the text). chunks_by_file = _SortChunksByFile( chunks ) # We sort the file list simply to enable repeatable testing sorted_file_list = sorted( iterkeys( chunks_by_file ) ) # Make sure the user is prepared to have her screen mutilated by the new # buffers num_files_to_open = _GetNumNonVisibleFiles( sorted_file_list ) if num_files_to_open > 0: if not Confirm( FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( num_files_to_open ) ): return # Store the list of locations where we applied changes. We use this to display # the quickfix window showing the user where we applied changes. locations = [] for filepath in sorted_file_list: ( buffer_num, close_window ) = _OpenFileInSplitIfNeeded( filepath ) ReplaceChunksInBuffer( chunks_by_file[ filepath ], vim.buffers[ buffer_num ], locations ) # When opening tons of files, we don't want to have a split for each new # file, as this simply does not scale, so we open the window, make the # edits, then hide the window. if close_window: # Some plugins (I'm looking at you, syntastic) might open a location list # for the window we just opened. We don't want that location list hanging # around, so we close it. lclose is a no-op if there is no location list. vim.command( 'lclose' ) # Note that this doesn't lose our changes. It simply "hides" the buffer, # which can later be re-accessed via the quickfix list or `:ls` vim.command( 'hide' ) # Open the quickfix list, populated with entries for each location we changed. if locations: SetQuickFixList( locations ) OpenQuickFixList() PostVimMessage( 'Applied {0} changes'.format( len( chunks ) ), warning = False ) def ReplaceChunksInBuffer( chunks, vim_buffer, locations ): """Apply changes in |chunks| to the buffer-like object |buffer|. Append each chunk's start to the list |locations|""" # We need to track the difference in length, but ensuring we apply fixes # in ascending order of insertion point. chunks.sort( key = lambda chunk: ( chunk[ 'range' ][ 'start' ][ 'line_num' ], chunk[ 'range' ][ 'start' ][ 'column_num' ] ) ) # Remember the line number we're processing. Negative line number means we # haven't processed any lines yet (by nature of being not equal to any # real line number). last_line = -1 line_delta = 0 for chunk in chunks: if chunk[ 'range' ][ 'start' ][ 'line_num' ] != last_line: # If this chunk is on a different line than the previous chunk, # then ignore previous deltas (as offsets won't have changed). last_line = chunk[ 'range' ][ 'end' ][ 'line_num' ] char_delta = 0 ( new_line_delta, new_char_delta ) = ReplaceChunk( chunk[ 'range' ][ 'start' ], chunk[ 'range' ][ 'end' ], chunk[ 'replacement_text' ], line_delta, char_delta, vim_buffer, locations ) line_delta += new_line_delta char_delta += new_char_delta # Replace the chunk of text specified by a contiguous range with the supplied # text. # * start and end are objects with line_num and column_num properties # * the range is inclusive # * indices are all 1-based # * the returned character delta is the delta for the last line # # returns the delta (in lines and characters) that any position after the end # needs to be adjusted by. # # NOTE: Works exclusively with bytes() instances and byte offsets as returned # by ycmd and used within the Vim buffers def ReplaceChunk( start, end, replacement_text, line_delta, char_delta, vim_buffer, locations = None ): # ycmd's results are all 1-based, but vim's/python's are all 0-based # (so we do -1 on all of the values) start_line = start[ 'line_num' ] - 1 + line_delta end_line = end[ 'line_num' ] - 1 + line_delta source_lines_count = end_line - start_line + 1 start_column = start[ 'column_num' ] - 1 + char_delta end_column = end[ 'column_num' ] - 1 if source_lines_count == 1: end_column += char_delta # NOTE: replacement_text is unicode, but all our offsets are byte offsets, # so we convert to bytes replacement_lines = ToBytes( replacement_text ).splitlines( False ) if not replacement_lines: replacement_lines = [ bytes( b'' ) ] replacement_lines_count = len( replacement_lines ) # NOTE: Vim buffers are a list of byte objects on Python 2 but unicode # objects on Python 3. end_existing_text = ToBytes( vim_buffer[ end_line ] )[ end_column : ] start_existing_text = ToBytes( vim_buffer[ start_line ] )[ : start_column ] new_char_delta = ( len( replacement_lines[ -1 ] ) - ( end_column - start_column ) ) if replacement_lines_count > 1: new_char_delta -= start_column replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ] replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:] if locations is not None: locations.append( { 'bufnr': vim_buffer.number, 'filename': vim_buffer.name, # line and column numbers are 1-based in qflist 'lnum': start_line + 1, 'col': start_column + 1, 'text': replacement_text, 'type': 'F', } ) new_line_delta = replacement_lines_count - source_lines_count return ( new_line_delta, new_char_delta ) def InsertNamespace( namespace ): if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ): expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' ) if expr: SetVariableValue( "g:ycm_namespace_to_insert", namespace ) vim.eval( expr ) return pattern = '^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*' existing_indent = '' line = SearchInCurrentBuffer( pattern ) if line: existing_line = LineTextInCurrentBuffer( line ) existing_indent = re.sub( r"\S.*", "", existing_line ) new_line = "{0}using {1};\n\n".format( existing_indent, namespace ) replace_pos = { 'line_num': line + 1, 'column_num': 1 } ReplaceChunk( replace_pos, replace_pos, new_line, 0, 0, vim.current.buffer ) PostVimMessage( 'Add namespace: {0}'.format( namespace ), warning = False ) def SearchInCurrentBuffer( pattern ): """ Returns the 1-indexed line on which the pattern matches (going UP from the current position) or 0 if not found """ return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern ))) def LineTextInCurrentBuffer( line_number ): """ Returns the text on the 1-indexed line (NOT 0-indexed) """ return vim.current.buffer[ line_number - 1 ] def ClosePreviewWindow(): """ Close the preview window if it is present, otherwise do nothing """ vim.command( 'silent! pclose!' ) def JumpToPreviewWindow(): """ Jump the vim cursor to the preview window, which must be active. Returns boolean indicating if the cursor ended up in the preview window """ vim.command( 'silent! wincmd P' ) return vim.current.window.options[ 'previewwindow' ] def JumpToPreviousWindow(): """ Jump the vim cursor to its previous window position """ vim.command( 'silent! wincmd p' ) def JumpToTab( tab_number ): """Jump to Vim tab with corresponding number """ vim.command( 'silent! tabn {0}'.format( tab_number ) ) def OpenFileInPreviewWindow( filename ): """ Open the supplied filename in the preview window """ vim.command( 'silent! pedit! ' + filename ) def WriteToPreviewWindow( message ): """ Display the supplied message in the preview window """ # This isn't something that comes naturally to Vim. Vim only wants to show # tags and/or actual files in the preview window, so we have to hack it a # little bit. We generate a temporary file name and "open" that, then write # the data to it. We make sure the buffer can't be edited or saved. Other # approaches include simply opening a split, but we want to take advantage of # the existing Vim options for preview window height, etc. ClosePreviewWindow() OpenFileInPreviewWindow( vim.eval( 'tempname()' ) ) if JumpToPreviewWindow(): # We actually got to the preview window. By default the preview window can't # be changed, so we make it writable, write to it, then make it read only # again. vim.current.buffer.options[ 'modifiable' ] = True vim.current.buffer.options[ 'readonly' ] = False vim.current.buffer[:] = message.splitlines() vim.current.buffer.options[ 'buftype' ] = 'nofile' vim.current.buffer.options[ 'bufhidden' ] = 'wipe' vim.current.buffer.options[ 'buflisted' ] = False vim.current.buffer.options[ 'swapfile' ] = False vim.current.buffer.options[ 'modifiable' ] = False vim.current.buffer.options[ 'readonly' ] = True # We need to prevent closing the window causing a warning about unsaved # file, so we pretend to Vim that the buffer has not been changed. vim.current.buffer.options[ 'modified' ] = False JumpToPreviousWindow() else: # We couldn't get to the preview window, but we still want to give the user # the information we have. The only remaining option is to echo to the # status area. PostVimMessage( message, warning = False ) def BufferIsVisibleForFilename( filename ): """Check if a buffer exists for a specific file.""" buffer_number = GetBufferNumberForFilename( filename, False ) return BufferIsVisible( buffer_number ) def CloseBuffersForFilename( filename ): """Close all buffers for a specific file.""" buffer_number = GetBufferNumberForFilename( filename, False ) while buffer_number != -1: vim.command( 'silent! bwipeout! {0}'.format( buffer_number ) ) new_buffer_number = GetBufferNumberForFilename( filename, False ) if buffer_number == new_buffer_number: raise RuntimeError( "Buffer {0} for filename '{1}' should already be " "wiped out.".format( buffer_number, filename ) ) buffer_number = new_buffer_number def OpenFilename( filename, options = {} ): """Open a file in Vim. Following options are available: - command: specify which Vim command is used to open the file. Choices are same-buffer, horizontal-split, vertical-split, and new-tab (default: horizontal-split); - size: set the height of the window for a horizontal split or the width for a vertical one (default: ''); - fix: set the winfixheight option for a horizontal split or winfixwidth for a vertical one (default: False). See :h winfix for details; - focus: focus the opened file (default: False); - watch: automatically watch for changes (default: False). This is useful for logs; - position: set the position where the file is opened (default: start). Choices are start and end.""" # Set the options. command = GetVimCommand( options.get( 'command', 'horizontal-split' ), 'horizontal-split' ) size = ( options.get( 'size', '' ) if command in [ 'split', 'vsplit' ] else '' ) focus = options.get( 'focus', False ) # There is no command in Vim to return to the previous tab so we need to # remember the current tab if needed. if not focus and command == 'tabedit': previous_tab = GetIntValue( 'tabpagenr()' ) else: previous_tab = None # Open the file. try: vim.command( '{0}{1} {2}'.format( size, command, filename ) ) # When the file we are trying to jump to has a swap file, # Vim opens swap-exists-choices dialog and throws vim.error with E325 error, # or KeyboardInterrupt after user selects one of the options which actually # opens the file (Open read-only/Edit anyway). except vim.error as e: if 'E325' not in str( e ): raise # Otherwise, the user might have chosen Quit. This is detectable by the # current file not being the target file if filename != GetCurrentBufferFilepath(): return except KeyboardInterrupt: # Raised when the user selects "Abort" after swap-exists-choices return _SetUpLoadedBuffer( command, filename, options.get( 'fix', False ), options.get( 'position', 'start' ), options.get( 'watch', False ) ) # Vim automatically set the focus to the opened file so we need to get the # focus back (if the focus option is disabled) when opening a new tab or # window. if not focus: if command == 'tabedit': JumpToTab( previous_tab ) if command in [ 'split', 'vsplit' ]: JumpToPreviousWindow() def _SetUpLoadedBuffer( command, filename, fix, position, watch ): """After opening a buffer, configure it according to the supplied options, which are as defined by the OpenFilename method.""" if command == 'split': vim.current.window.options[ 'winfixheight' ] = fix if command == 'vsplit': vim.current.window.options[ 'winfixwidth' ] = fix if watch: vim.current.buffer.options[ 'autoread' ] = True vim.command( "exec 'au BufEnter <buffer> :silent! checktime {0}'" .format( filename ) ) if position == 'end': vim.command( 'silent! normal! Gzz' )
oblitum/YouCompleteMe
python/ycm/vimsupport.py
Python
gpl-3.0
40,365
<!-- resources/views/vendor/openpolice/nodes/2713-dept-page-calls-action.blade.php --> <a class="btn btn-primary btn-lg" href="/filing-your-police-complaint/{{ $d['deptRow']->dept_slug }}" <?php /* @if (in_array(substr($d['deptRow']->dept_slug, 0, 3), ['NY-', 'MA-', 'MD-', 'MN-', 'DC-'])) href="/filing-your-police-complaint/{{ $d['deptRow']->dept_slug }}" @else href="/join-beta-test/{{ $d['deptRow']->dept_slug }}" @endif */ ?> >File a Complaint or Compliment</a> <div class="pT15 mT10"></div> <style> #node2707kids { padding-top: 30px; } #blockWrap2710 { margin-bottom: -20px; } </style>
flexyourrights/openpolice
src/Views/nodes/2713-dept-page-calls-action.blade.php
PHP
gpl-3.0
615
<?php Prado::Using('Application.Engine.*'); class CombinedView extends TPage { public $text; public $tiroText; public function onLoad() { global $ABS_PATH,$USERS_PREFIX; $this->text = TextRecord::finder()->findByPk($_GET['id']); $this->tiroText = new TiroText($ABS_PATH.'/'.$USERS_PREFIX.'/'.$this->User->Name.'/'.$this->text->dir_name); // Display the text at the bottom. $textDOM = new DomDocument; $textDOM->loadXML($this->tiroText->getText()); $styleSheet = new DOMDocument; $styleSheet->load('protected/Data/xsl/tiro2js_tree.xsl'); $proc = new XSLTProcessor; $proc->importStyleSheet($styleSheet); $this->LatinPreview->Controls->add($proc->transformToXML($textDOM)); } } ?>
mattkatsenes/tiro-interactive
prado/branch-1.0/protected/Pages/TextManagement/CombinedView.php
PHP
gpl-3.0
712
#if defined HAVE_CONFIG_H #include "config.h" #endif #include <solver_core.hpp> #include <triqs/operators/many_body_operator.hpp> #include <triqs/hilbert_space/fundamental_operator_set.hpp> #include <triqs/gfs.hpp> #include <stdlib.h> #include <stdio.h> #include <iostream> #include <fstream> #include <iomanip> //#include <boost/mpi/communicator.hpp> #include "triqs_cthyb_qmc.hpp" using namespace std; using namespace cthyb; using triqs::utility::many_body_operator; using triqs::utility::c; using triqs::utility::c_dag; using triqs::utility::n; using namespace triqs::gfs; using indices_type = triqs::utility::many_body_operator<double>::indices_t; void ctqmc_triqs_run( bool rot_inv, bool leg_measure, bool hist, bool wrt_files, bool tot_not, /*boolean*/ int n_orbitals, int n_freq, int n_tau, int n_l, int n_cycles_, int cycle_length, int ntherm, int verbo, int seed, /*integer*/ double beta_, /*double*/ double *epsi, double *umat_ij, double *umat_ijkl, std::complex<double> *f_iw_ptr, std::complex<double> *g_iw_ptr, double *g_tau, double *gl, MPI_Fint *MPI_world_ptr ){ /*array pointers & simple pointers*/ cout.setf(ios::fixed); //cout.precision(17); //Initialize Boost mpi environment int rank; boost::mpi::environment env; //int rank = boost::mpi::communicator(MPI_Comm_f2c(*MPI_world_ptr), boost::mpi::comm_attach).rank(); { boost::mpi::communicator c; c << MPI_Comm_f2c( *MPI_world_ptr ); //auto c_ = MPI_Comm_f2c(*MPI_world_ptr); //boost::mpi::communicator c = boost::mpi::communicator(MPI_Comm_f2c(*MPI_world_ptr), boost::mpi::comm_attach); rank=c.rank(); //MPI_Comm_rank(MPI_Comm_f2c(*MPI_world_ptr), &rank); } // Parameters relay from Fortran and default values affectation double beta = beta_; //Temperature inverse int num_orbitals = n_orbitals; //double U = U_; //Impurity site Interaction term double mu = 0.0;//Chemical Potential Functionality avail but not used here //bool n_n_only = !(rot_inv);//density-density? int Nfreq = n_freq; //Number of Matsubara frequencies int Ntau = n_tau; //Number of imaginary times int Nl = n_l; //Number of Legendre measures 30 int n_cycles = n_cycles_; int nspin = 2; //always it's Nature //Print informations about the Solver Parameters if(rank==0 && verbo>0){ std::cout << endl <<" == Key Input Parameters for the TRIQS CTHYB solver == "<<endl<<endl; std::cout <<" Beta = "<< beta <<" [eV]^(-1) "<<endl; std::cout <<" Mu = "<< mu <<" [eV]"<<endl; std::cout <<" Nflavour = "<< num_orbitals <<endl; std::cout <<" Nfreq = "<< Nfreq << endl; std::cout <<" Ntau = "<< Ntau << endl; std::cout <<" Nl = "<< Nl << endl; std::cout <<" Ncycles = "<< n_cycles << endl; std::cout <<" Cycle length = "<< cycle_length << endl; std::cout <<" Ntherm = "<< ntherm << endl; std::cout <<" Verbosity (0->3) = "<< verbo << endl; std::cout <<" Abinit Seed = "<< seed << endl <<endl; for(int o = 0; o < num_orbitals; ++o){ std::cout << " e- level["<< o+1 <<"] = "<< setprecision(17) << epsi[o] <<" [eV]"<< endl; //ed != cste => vecteur a parcourir ensuite } std::cout << endl; std::cout <<" U(i,j) [eV] = " <<endl<< endl<<"\t"; for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ std::cout << setprecision(17) << fixed <<umat_ij[o+oo*num_orbitals] << "\t"; //ed != cste => vecteur a parcourir ensuite } std::cout << endl<<"\t"; } } // Hamiltonian definition many_body_operator<double> H; //Spin Orbit general case num_orbitals*2=Nflavour) //Init Hamiltonian Basic terms ///H = init_Hamiltonian( epsi, num_orbitals, U, J ); // U=cste if(!rot_inv){ if(rank==0 && verbo>0) std::cout <<endl<<" == Density-Density Terms Included == "<<endl<<endl; H = init_Hamiltonian( epsi, num_orbitals, umat_ij ); //}else if(rank==0 && verbo>0) std::cout <<" == Rotationnaly Invariant Terms Not Included == "<< endl << endl; //Include density-density term (J != 0) spin flips and pair hopping => density-density term case }else{//if(rot_inv){ if(rank==0 && verbo>0)std::cout <<" == Rotationnaly Invariant Terms Included == "<< endl << endl; if(tot_not){ H = init_fullHamiltonian( epsi, num_orbitals, umat_ijkl ); }else{ //up and down separation H = init_fullHamiltonianUpDown( epsi, num_orbitals, umat_ijkl ); } }//else if(rank==0 && verbo>0) std::cout <<endl<<" == Density-Density Terms Not Included == "<<endl<<endl; std::map<std::string, indices_type> gf_struct; if( tot_not ){ std::map<std::string, indices_type> gf_struct_tmp{{"tot",indices_type{}}};//{{"tot",indices_type{}}}; //{0,1} for(int o = 0; o < num_orbitals; ++o){ gf_struct_tmp["tot"].push_back(o); } gf_struct = gf_struct_tmp; }else{ //spin orb case: general case std::map<std::string, indices_type> gf_struct_tmp{{"up",indices_type{}},{"down",indices_type{}}}; for(int o = 0; o < num_orbitals; ++o){ gf_struct_tmp["up"].push_back(o); gf_struct_tmp["down"].push_back(o); } gf_struct = gf_struct_tmp; } if(rank==0 && verbo>0) std::cout <<" == Green Function Structure Initialized == "<< endl << endl; // Construct CTQMC solver with mesh parameters solver_core solver(beta, gf_struct, Nfreq, Ntau, Nl); if(rank==0 && verbo>0) std::cout <<" == Solver Core Initialized == "<< endl << endl; //Fill in "hybridation+eps"=F(iw)~Delta(iw) coming from fortran inside delta_iw term RHS gf<imfreq> delta_iw = gf<imfreq>{{beta, Fermion, Nfreq}, {num_orbitals,num_orbitals}}; auto w_mesh = delta_iw.mesh(); ofstream delta_init; delta_init.open("delta_init_check"); // only on one rank ! if(rank==0){ delta_init << "# w_index l l' Im(iw) delta(iw)\n" << endl; } for(std::size_t w_index = 0; w_index < w_mesh.size(); ++w_index){ auto iw = w_mesh.index_to_point(w_index); auto cell = delta_iw[w_index]; for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ cell(o,oo) = f_iw_ptr[o+oo*num_orbitals+w_index*num_orbitals*num_orbitals]; //cout <<"[IN C++]"<<" F[ w= "<< w_index <<" , l= "<< o <<" , l_= "<< oo <<" ] = "<< setprecision(15) << f_iw_ptr[o+oo*num_orbitals+w_index*num_orbitals*num_orbitals] << endl; // if(o==oo){ //std::cout << w_index <<"\t"<< o <<"\t"<< oo <<"\t"<< imag(iw) <<"\t"<< setprecision(15) << f_iw_ptr[o+oo*num_orbitals+w_index*num_orbitals*num_orbitals] << endl; // } if(rank==0){ delta_init << w_index+1 <<"\t"<< o+1 <<"\t"<< oo+1 <<"\t"<< imag(iw) <<"\t"<< setprecision(17) << fixed << f_iw_ptr[o+oo*num_orbitals+w_index*num_orbitals*num_orbitals] << endl; } } } } if(rank==0 && verbo>0) std::cout <<" == F(iw) Initialized == "<< endl << endl; triqs::clef::placeholder<0> om_; auto g0_iw = gf<imfreq>{{beta, Fermion, Nfreq}, {num_orbitals,num_orbitals}}; g0_iw(om_) << om_ + mu - delta_iw(om_); //calculate G0(iw)^-1 matrix if(rank==0 && verbo>0) std::cout <<" == G0(iw)^-1 Initialized == "<< endl << endl; if(tot_not){ solver.G0_iw()[0] = triqs::gfs::inverse( g0_iw ); //inverse G0(iw) matrix and affect to solver }else{ for (int i = 0; i < nspin; ++i){ solver.G0_iw()[i] = triqs::gfs::inverse( g0_iw ); } } if(rank==0 && verbo>0) std::cout <<" == G0(iw)^-1 Inverted => G0(iw) Constructed == "<< endl << endl; // if(rank==0){ //Output Test of none interacting G0 // // ofstream G0_up, G0_down; // // G0_up.open("G0_up_non_interagissant"); // G0_up << "# w_index l l' Im(iw) Real(G0) Im(G0)\n" << endl; // // // //Report G0_iw // int compteur = 0; // for(std::size_t w_index = 0; w_index < w_mesh.size(); ++w_index){ // auto iw = w_mesh.index_to_point(w_index); // for(int oo = 0; oo < num_orbitals; ++oo){ // for(int o = 0; o < num_orbitals; ++o){ // // // // G0_up << fixed << w_index <<"\t"<< o <<"\t"<< oo <<"\t"<< fixed<< imag(iw) <<"\t"<< real(solver.G0_iw()[0].data()(w_index,o,oo)) <<"\t"<< imag(solver.G0_iw()[0].data()(w_index,o,oo)) << endl; // compteur++; // } // } // } // } if(rank==0 && verbo>0) std::cout <<" == Solver Parametrization == "<< endl << endl; // Solver parameters auto paramCTQMC = solve_parameters_t(H, n_cycles); paramCTQMC.max_time = -1; paramCTQMC.random_name = ""; paramCTQMC.random_seed = 123 * rank + 567;//seed; paramCTQMC.length_cycle = cycle_length; paramCTQMC.n_warmup_cycles = ntherm; paramCTQMC.verbosity=verbo; paramCTQMC.measure_g_l = leg_measure; //paramCTQMC.move_double = true; // paramCTQMC.make_histograms=hist; if(rank==0 && verbo>0) std::cout <<" == Starting Solver [node "<< rank <<"] == "<< endl << endl; // Solve! solver.solve(paramCTQMC); if(rank==0 && verbo>0) std::cout <<" == Reporting == "<< endl << endl; // Report some stuff // if(rank==0){ // ofstream glegendre, g_iw; // g_iw.open("g_iw"); //Report G_iw int compteur = 0; //g_iw << fixed << setprecision(17) << w_index << "\t"; for(int oo = 0; oo < num_orbitals; ++oo){ for(int o = 0; o < num_orbitals; ++o){ for(std::size_t w_index = 0; w_index < w_mesh.size(); ++w_index){ //Pour une frequence donnee auto iw = w_mesh.index_to_point(w_index); g_iw_ptr[compteur] = solver.G0_iw()[0].data()(w_index,o,oo); //g_iw << fixed<< setprecision(17) << solver.G0_iw()[0].data()(w_index,o,oo); compteur++; } } //g_iw << endl; } //Report G_tau compteur = 0; for(int oo = 0; oo < num_orbitals; ++oo){ for(int o = 0; o < num_orbitals; ++o){ for(int tau = 0; tau < n_tau; ++tau){ g_tau[compteur]= solver.G_tau()[0].data()(tau,o,oo); compteur++; } } } //Report G(l) if( leg_measure ){ compteur = 0; for(int oo = 0; oo < num_orbitals; ++oo){ for(int o = 0; o < num_orbitals; ++o){ for(int l = 0; l < n_l; ++l){ gl[compteur]= solver.G_l()[0].data()(l,o,oo); compteur++; } } } } //Write G(tau) if( rank==0 && wrt_files ){ ofstream gtau; gtau.open("Gtau_triqs.dat"); double _tau_=0.0; for(int tau = 0; tau < n_tau; ++tau){ _tau_=((tau*beta)/n_tau)*27.2113845; //en Harthree gtau << fixed << setprecision(17) <<_tau_ << "\t"; for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ gtau << fixed<< setprecision(17) << solver.G_tau()[0].data()(tau,o,oo) <<"\t"; } } gtau << endl; } ofstream g_iw; g_iw.open("giw"); for(std::size_t w_index = 0; w_index < w_mesh.size(); ++w_index){ auto iw = w_mesh.index_to_point(w_index); for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ g_iw << fixed << setprecision(17) << solver.G0_iw()[0].data()(w_index,o,oo); } } g_iw << endl; } } //Write U(i,j) if( rank==0 && wrt_files ){ ofstream umat; umat.open("umat"); for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ umat <<"U( "<< o+1 <<" , "<< oo+1 <<" )= "<< fixed << setprecision(17) << umat_ij[o+(oo*num_orbitals)] <<endl; } } } if( leg_measure && rank==0 && wrt_files ){ ofstream g_l; g_l.open("gl"); for(int l = 0; l < n_l; ++l){ for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ g_l << fixed << setprecision(17) << solver.G_l()[0].data()(l,o,oo) <<"\t"; } } g_l << endl; } } if(rank==0 && verbo>0) std::cout <<" == CTHYB-QMC Process Finished [node "<< rank <<"] == "<< endl << endl; } /********************************************************/ /****************** Functions Used **********************/ /********************************************************/ // Hamiltonian Initialization with precalculate coeff (J=0 and U(i,j)) many_body_operator<double> init_Hamiltonian( double *eps, int nflavor, double *U){ many_body_operator<double> H; double coeff; for(int i = 0; i < nflavor; ++i) for(int j = 0; j < nflavor; ++j){ //cas diago principale: if(i==j){ H += eps[i] * n("tot",i) ; } else{ coeff = double(U[i+j*nflavor])*0.5; //cout << "U = "<< U[i+j*nflavor] <<" /2 = "<< coeff <<endl; H += coeff * n("tot",i) * n("tot",j); } } return H; } // Hamiltonian Initialization with precalculated coeff U(i,j,k,l) in "tot" notation many_body_operator<double> init_fullHamiltonian( double *eps, int nflavor, double *U){ many_body_operator<double> H; double coeff; for(int i = 0; i < nflavor; ++i) for(int j = 0; j < nflavor; ++j){ if(i==j){ H += eps[i] * n("tot",i) ; //Levels On diagonal Hamiltonian Matrix } for(int k = 0; k < nflavor; ++k) for(int l = 0; l < nflavor; ++l){ //cas diago principale: coeff = 0.5 * double( U[i+j*nflavor+k*nflavor*nflavor+l*nflavor*nflavor*nflavor] ); H += coeff * c_dag("tot",i)*c_dag("tot",j)*c("tot",l)*c("tot",k); //changing l <-> k order index to be in accordance with the Abinit definition } } return H; } // Hamiltonian Initialization with precalculated coeff U(i,j,k,l) in "up" and "down" notation many_body_operator<double> init_fullHamiltonianUpDown( double *eps, int nflavor, double *U ){ many_body_operator<double> H; double coeff; for(int i = 0; i < nflavor; ++i) for(int j = 0; j < nflavor; ++j){ if(i==j){ H += eps[i] * ( n("up",i) + n("down",i) ); //Levels On diagonal Hamiltonian Matrix } for(int k = 0; k < nflavor; ++k) for(int l = 0; l < nflavor; ++l){ coeff = 0.5 * double(U[i+j*nflavor+k*nflavor*nflavor+l*nflavor*nflavor*nflavor]); // for(int s = 0; s < nspin; ++s) // for(int s1 = 0; s1 < nspin; ++s1){ H += coeff * c_dag("up",i) * c_dag("down",j) * c("up",l) * c("down",k); H += coeff * c_dag("down",i) * c_dag("up",j) * c("down",l) * c("up",k); // } } } return H; }
jmbeuken/abinit
src/01_triqs_ext/triqs_cthyb_qmc.cpp
C++
gpl-3.0
14,888
#!/usr/bin/env python3 import os import logging import tempfile import shutil from graftm.sequence_search_results import SequenceSearchResult from graftm.graftm_output_paths import GraftMFiles from graftm.search_table import SearchTableWriter from graftm.sequence_searcher import SequenceSearcher from graftm.hmmsearcher import NoInputSequencesException from graftm.housekeeping import HouseKeeping from graftm.summarise import Stats_And_Summary from graftm.pplacer import Pplacer from graftm.create import Create from graftm.update import Update from graftm.unpack_sequences import UnpackRawReads from graftm.graftm_package import GraftMPackage from graftm.expand_searcher import ExpandSearcher from graftm.diamond import Diamond from graftm.getaxnseq import Getaxnseq from graftm.sequence_io import SequenceIO from graftm.timeit import Timer from graftm.clusterer import Clusterer from graftm.decorator import Decorator from graftm.external_program_suite import ExternalProgramSuite from graftm.archive import Archive from graftm.decoy_filter import DecoyFilter from biom.util import biom_open T=Timer() class UnrecognisedSuffixError(Exception): pass class Run: PIPELINE_AA = "P" PIPELINE_NT = "D" _MIN_VERBOSITY_FOR_ART = 3 # with 2 then, only errors are printed PPLACER_TAXONOMIC_ASSIGNMENT = 'pplacer' DIAMOND_TAXONOMIC_ASSIGNMENT = 'diamond' MIN_ALIGNED_FILTER_FOR_NUCLEOTIDE_PACKAGES = 95 MIN_ALIGNED_FILTER_FOR_AMINO_ACID_PACKAGES = 30 DEFAULT_MAX_SAMPLES_FOR_KRONA = 100 NO_ORFS_EXITSTATUS = 128 def __init__(self, args): self.args = args self.setattributes(self.args) def setattributes(self, args): self.hk = HouseKeeping() self.s = Stats_And_Summary() if args.subparser_name == 'graft': commands = ExternalProgramSuite(['orfm', 'nhmmer', 'hmmsearch', 'mfqe', 'pplacer', 'ktImportText', 'diamond']) self.hk.set_attributes(self.args) self.hk.set_euk_hmm(self.args) if args.euk_check:self.args.search_hmm_files.append(self.args.euk_hmm_file) self.ss = SequenceSearcher(self.args.search_hmm_files, (None if self.args.search_only else self.args.aln_hmm_file)) self.sequence_pair_list = self.hk.parameter_checks(args) if hasattr(args, 'reference_package'): self.p = Pplacer(self.args.reference_package) elif self.args.subparser_name == "create": commands = ExternalProgramSuite(['taxit', 'FastTreeMP', 'hmmalign', 'mafft']) self.create = Create(commands) def summarise(self, base_list, trusted_placements, reverse_pipe, times, hit_read_count_list, max_samples_for_krona): ''' summarise - write summary information to file, including otu table, biom file, krona plot, and timing information Parameters ---------- base_list : array list of each of the files processed by graftm, with the path and and suffixed removed trusted_placements : dict dictionary of placements with entry as the key, a taxonomy string as the value reverse_pipe : bool True = run reverse pipe, False = run normal pipeline times : array list of the recorded times for each step in the pipeline in the format: [search_step_time, alignment_step_time, placement_step_time] hit_read_count_list : array list containing sublists, one for each file run through the GraftM pipeline, each two entries, the first being the number of putative eukaryotic reads (when searching 16S), the second being the number of hits aligned and placed in the tree. max_samples_for_krona: int If the number of files processed is greater than this number, then do not generate a krona diagram. Returns ------- ''' # Summary steps. placements_list = [] for base in base_list: # First assign the hash that contains all of the trusted placements # to a variable to it can be passed to otu_builder, to be written # to a file. :) placements = trusted_placements[base] self.s.readTax(placements, GraftMFiles(base, self.args.output_directory, False).read_tax_output_path(base)) placements_list.append(placements) #Generate coverage table #logging.info('Building coverage table for %s' % base) #self.s.coverage_of_hmm(self.args.aln_hmm_file, # self.gmf.summary_table_output_path(base), # self.gmf.coverage_table_path(base), # summary_dict[base]['read_length']) logging.info('Writing summary table') with open(self.gmf.combined_summary_table_output_path(), 'w') as f: self.s.write_tabular_otu_table(base_list, placements_list, f) logging.info('Writing biom file') with biom_open(self.gmf.combined_biom_output_path(), 'w') as f: biom_successful = self.s.write_biom(base_list, placements_list, f) if not biom_successful: os.remove(self.gmf.combined_biom_output_path()) logging.info('Building summary krona plot') if len(base_list) > max_samples_for_krona: logging.warn("Skipping creation of Krona diagram since there are too many input files. The maximum can be overridden using --max_samples_for_krona") else: self.s.write_krona_plot(base_list, placements_list, self.gmf.krona_output_path()) # Basic statistics placed_reads=[len(trusted_placements[base]) for base in base_list] self.s.build_basic_statistics(times, hit_read_count_list, placed_reads, \ base_list, self.gmf.basic_stats_path()) # Delete unnecessary files logging.info('Cleaning up') for base in base_list: directions = ['forward', 'reverse'] if reverse_pipe: for i in range(0,2): self.gmf = GraftMFiles(base, self.args.output_directory, directions[i]) self.hk.delete([self.gmf.for_aln_path(base), self.gmf.rev_aln_path(base), self.gmf.conv_output_rev_path(base), self.gmf.conv_output_for_path(base), self.gmf.euk_free_path(base), self.gmf.euk_contam_path(base), self.gmf.readnames_output_path(base), self.gmf.sto_output_path(base), self.gmf.orf_titles_output_path(base), self.gmf.orf_output_path(base), self.gmf.output_for_path(base), self.gmf.output_rev_path(base)]) else: self.gmf = GraftMFiles(base, self.args.output_directory, False) self.hk.delete([self.gmf.for_aln_path(base), self.gmf.rev_aln_path(base), self.gmf.conv_output_rev_path(base), self.gmf.conv_output_for_path(base), self.gmf.euk_free_path(base), self.gmf.euk_contam_path(base), self.gmf.readnames_output_path(base), self.gmf.sto_output_path(base), self.gmf.orf_titles_output_path(base), self.gmf.orf_output_path(base), self.gmf.output_for_path(base), self.gmf.output_rev_path(base)]) logging.info('Done, thanks for using graftM!\n') def graft(self): # The Graft pipeline: # Searches for reads using hmmer, and places them in phylogenetic # trees to derive a community structure. if self.args.graftm_package: gpkg = GraftMPackage.acquire(self.args.graftm_package) else: gpkg = None REVERSE_PIPE = (True if self.args.reverse else False) INTERLEAVED = (True if self.args.interleaved else False) base_list = [] seqs_list = [] search_results = [] hit_read_count_list = [] db_search_results = [] if gpkg: maximum_range = gpkg.maximum_range() if self.args.search_diamond_file: self.args.search_method = self.hk.DIAMOND_SEARCH_METHOD diamond_db = self.args.search_diamond_file[0] else: diamond_db = gpkg.diamond_database_path() if self.args.search_method == self.hk.DIAMOND_SEARCH_METHOD: if not diamond_db: logging.error("%s search method selected, but no diamond database specified. \ Please either provide a gpkg to the --graftm_package flag, or a diamond \ database to the --search_diamond_file flag." % self.args.search_method) raise Exception() else: # Get the maximum range, if none exists, make one from the HMM profile if self.args.maximum_range: maximum_range = self.args.maximum_range else: if self.args.search_method==self.hk.HMMSEARCH_SEARCH_METHOD: if not self.args.search_only: maximum_range = self.hk.get_maximum_range(self.args.aln_hmm_file) else: logging.debug("Running search only pipeline. maximum_range not configured.") maximum_range = None else: logging.warning('Cannot determine maximum range when using %s pipeline and with no GraftM package specified' % self.args.search_method) logging.warning('Setting maximum_range to None (linked hits will not be detected)') maximum_range = None if self.args.search_diamond_file: diamond_db = self.args.search_diamond_file else: if self.args.search_method == self.hk.HMMSEARCH_SEARCH_METHOD: diamond_db = None else: logging.error("%s search method selected, but no gpkg or diamond database selected" % self.args.search_method) if self.args.assignment_method == Run.DIAMOND_TAXONOMIC_ASSIGNMENT: if self.args.reverse: logging.warn("--reverse reads specified with --assignment_method diamond. Reverse reads will be ignored.") self.args.reverse = None # If merge reads is specified, check that there are reverse reads to merge with if self.args.merge_reads and not hasattr(self.args, 'reverse'): raise Exception("Programming error") # Set the output directory if not specified and create that directory logging.debug('Creating working directory: %s' % self.args.output_directory) self.hk.make_working_directory(self.args.output_directory, self.args.force) # Set pipeline and evalue by checking HMM format if self.args.search_only: if self.args.search_method == self.hk.HMMSEARCH_SEARCH_METHOD: hmm_type, hmm_tc = self.hk.setpipe(self.args.search_hmm_files[0]) logging.debug("HMM type: %s Trusted Cutoff: %s" % (hmm_type, hmm_tc)) else: hmm_type, hmm_tc = self.hk.setpipe(self.args.aln_hmm_file) logging.debug("HMM type: %s Trusted Cutoff: %s" % (hmm_type, hmm_tc)) if self.args.search_method == self.hk.HMMSEARCH_SEARCH_METHOD: setattr(self.args, 'type', hmm_type) if hmm_tc: setattr(self.args, 'evalue', '--cut_tc') else: setattr(self.args, 'type', self.PIPELINE_AA) if self.args.filter_minimum is not None: filter_minimum = self.args.filter_minimum else: if self.args.type == self.PIPELINE_NT: filter_minimum = Run.MIN_ALIGNED_FILTER_FOR_NUCLEOTIDE_PACKAGES else: filter_minimum = Run.MIN_ALIGNED_FILTER_FOR_AMINO_ACID_PACKAGES # Generate expand_search database if required if self.args.expand_search_contigs: if self.args.graftm_package: pkg = GraftMPackage.acquire(self.args.graftm_package) else: pkg = None boots = ExpandSearcher( search_hmm_files = self.args.search_hmm_files, maximum_range = self.args.maximum_range, threads = self.args.threads, evalue = self.args.evalue, min_orf_length = self.args.min_orf_length, graftm_package = pkg) # this is a hack, it should really use GraftMFiles but that class isn't currently flexible enough new_database = (os.path.join(self.args.output_directory, "expand_search.hmm") \ if self.args.search_method == self.hk.HMMSEARCH_SEARCH_METHOD \ else os.path.join(self.args.output_directory, "expand_search") ) if boots.generate_expand_search_database_from_contigs( self.args.expand_search_contigs, new_database, self.args.search_method): if self.args.search_method == self.hk.HMMSEARCH_SEARCH_METHOD: self.ss.search_hmm.append(new_database) else: diamond_db = new_database first_search_method = self.args.search_method if self.args.decoy_database: decoy_filter = DecoyFilter(Diamond(diamond_db, threads=self.args.threads), Diamond(self.args.decoy_database, threads=self.args.threads)) doing_decoy_search = True elif self.args.search_method == self.hk.HMMSEARCH_AND_DIAMOND_SEARCH_METHOD: decoy_filter = DecoyFilter(Diamond(diamond_db, threads=self.args.threads)) doing_decoy_search = True first_search_method = self.hk.HMMSEARCH_SEARCH_METHOD else: doing_decoy_search = False # For each pair (or single file passed to GraftM) logging.debug('Working with %i file(s)' % len(self.sequence_pair_list)) for pair in self.sequence_pair_list: # Guess the sequence file type, if not already specified to GraftM unpack = UnpackRawReads(pair[0], self.args.input_sequence_type, INTERLEAVED) # Set the basename, and make an entry to the summary table. base = unpack.basename() pair_direction = ['forward', 'reverse'] logging.info("Working on %s" % base) # Make the working base subdirectory self.hk.make_working_directory(os.path.join(self.args.output_directory, base), self.args.force) # for each of the paired end read files for read_file in pair: unpack = UnpackRawReads(read_file, self.args.input_sequence_type, INTERLEAVED) if read_file is None: # placeholder for interleaved (second file is None) continue if not os.path.isfile(read_file): # Check file exists logging.info('%s does not exist! Skipping this file..' % read_file) continue # Set the output file_name if len(pair) == 2: direction = 'interleaved' if pair[1] is None \ else pair_direction.pop(0) logging.info("Working on %s reads" % direction) self.gmf = GraftMFiles(base, self.args.output_directory, direction) self.hk.make_working_directory(os.path.join(self.args.output_directory, base, direction), self.args.force) else: direction = False self.gmf = GraftMFiles(base, self.args.output_directory, direction) if self.args.type == self.PIPELINE_AA: logging.debug("Running protein pipeline") try: search_time, (result, complement_information) = self.ss.aa_db_search( self.gmf, base, unpack, first_search_method, maximum_range, self.args.threads, self.args.evalue, self.args.min_orf_length, self.args.restrict_read_length, diamond_db ) except NoInputSequencesException as e: logging.error("No sufficiently long open reading frames were found, indicating" " either the input sequences are too short or the min orf length" " cutoff is too high. Cannot continue sorry. Alternatively, there" " is something amiss with the installation of OrfM. The specific" " command that failed was: %s" % e.command) exit(Run.NO_ORFS_EXITSTATUS) # Or the DNA pipeline elif self.args.type == self.PIPELINE_NT: logging.debug("Running nucleotide pipeline") search_time, (result, complement_information) = self.ss.nt_db_search( self.gmf, base, unpack, self.args.euk_check, self.args.search_method, maximum_range, self.args.threads, self.args.evalue ) reads_detected = True if not result.hit_fasta() or os.path.getsize(result.hit_fasta()) == 0: logging.info('No reads found in %s' % base) reads_detected = False if self.args.search_only: db_search_results.append(result) base_list.append(base) continue # Filter out decoys if specified if reads_detected and doing_decoy_search: with tempfile.NamedTemporaryFile(prefix="graftm_decoy", suffix='.fa') as f: tmpname = f.name any_remaining = decoy_filter.filter(result.hit_fasta(), tmpname) if any_remaining: shutil.move(tmpname, result.hit_fasta()) else: # No hits remain after decoy filtering. os.remove(result.hit_fasta()) continue if self.args.assignment_method == Run.PPLACER_TAXONOMIC_ASSIGNMENT: logging.info('aligning reads to reference package database') hit_aligned_reads = self.gmf.aligned_fasta_output_path(base) if reads_detected: aln_time, aln_result = self.ss.align( result.hit_fasta(), hit_aligned_reads, complement_information, self.args.type, filter_minimum ) else: aln_time = 'n/a' if not os.path.exists(hit_aligned_reads): # If all were filtered out, or there just was none.. with open(hit_aligned_reads,'w') as f: pass # just touch the file, nothing else seqs_list.append(hit_aligned_reads) db_search_results.append(result) base_list.append(base) search_results.append(result.search_result) hit_read_count_list.append(result.hit_count) # Write summary table srchtw = SearchTableWriter() srchtw.build_search_otu_table([x.search_objects for x in db_search_results], base_list, self.gmf.search_otu_table()) if self.args.search_only: logging.info('Stopping before alignment and taxonomic assignment phase\n') exit(0) if self.args.merge_reads: # not run when diamond is the assignment mode- enforced by argparse grokking logging.debug("Running merge reads output") if self.args.interleaved: fwd_seqs = seqs_list rev_seqs = [] else: base_list=base_list[0::2] fwd_seqs = seqs_list[0::2] rev_seqs = seqs_list[1::2] merged_output=[GraftMFiles(base, self.args.output_directory, False).aligned_fasta_output_path(base) \ for base in base_list] logging.debug("merged reads to %s", merged_output) self.ss.merge_forev_aln(fwd_seqs, rev_seqs, merged_output) seqs_list=merged_output REVERSE_PIPE = False elif REVERSE_PIPE: base_list=base_list[0::2] # Leave the pipeline if search only was specified if self.args.search_and_align_only: logging.info('Stopping before taxonomic assignment phase\n') exit(0) elif not any(base_list): logging.error('No hits in any of the provided files. Cannot continue with no reads to assign taxonomy to.\n') exit(0) self.gmf = GraftMFiles('', self.args.output_directory, False) if self.args.assignment_method == Run.PPLACER_TAXONOMIC_ASSIGNMENT: clusterer=Clusterer() # Classification steps seqs_list=clusterer.cluster(seqs_list, REVERSE_PIPE) logging.info("Placing reads into phylogenetic tree") taxonomic_assignment_time, assignments=self.p.place(REVERSE_PIPE, seqs_list, self.args.resolve_placements, self.gmf, self.args, result.slash_endings, gpkg.taxtastic_taxonomy_path(), clusterer) assignments = clusterer.uncluster_annotations(assignments, REVERSE_PIPE) elif self.args.assignment_method == Run.DIAMOND_TAXONOMIC_ASSIGNMENT: logging.info("Assigning taxonomy with diamond") taxonomic_assignment_time, assignments = self._assign_taxonomy_with_diamond(\ base_list, db_search_results, gpkg, self.gmf) aln_time = 'n/a' else: raise Exception("Unexpected assignment method encountered: %s" % self.args.placement_method) self.summarise(base_list, assignments, REVERSE_PIPE, [search_time, aln_time, taxonomic_assignment_time], hit_read_count_list, self.args.max_samples_for_krona) @T.timeit def _assign_taxonomy_with_diamond(self, base_list, db_search_results, graftm_package, graftm_files): '''Run diamond to assign taxonomy Parameters ---------- base_list: list of str list of sequence block names db_search_results: list of DBSearchResult the result of running hmmsearches graftm_package: GraftMPackage object Diamond is run against this database graftm_files: GraftMFiles object Result files are written here Returns ------- list of 1. time taken for assignment 2. assignments i.e. dict of base_list entry to dict of read names to to taxonomies, or None if there was no hit detected. ''' runner = Diamond(graftm_package.diamond_database_path(), self.args.threads, self.args.evalue) taxonomy_definition = Getaxnseq().read_taxtastic_taxonomy_and_seqinfo\ (open(graftm_package.taxtastic_taxonomy_path()), open(graftm_package.taxtastic_seqinfo_path())) results = {} # For each of the search results, for i, search_result in enumerate(db_search_results): if search_result.hit_fasta() is None: sequence_id_to_taxonomy = {} else: sequence_id_to_hit = {} # Run diamond logging.debug("Running diamond on %s" % search_result.hit_fasta()) diamond_result = runner.run(search_result.hit_fasta(), UnpackRawReads.PROTEIN_SEQUENCE_TYPE, daa_file_basename=graftm_files.diamond_assignment_output_basename(base_list[i])) for res in diamond_result.each([SequenceSearchResult.QUERY_ID_FIELD, SequenceSearchResult.HIT_ID_FIELD]): if res[0] in sequence_id_to_hit: # do not accept duplicates if sequence_id_to_hit[res[0]] != res[1]: raise Exception("Diamond unexpectedly gave two hits for a single query sequence for %s" % res[0]) else: sequence_id_to_hit[res[0]] = res[1] # Extract taxonomy of the best hit, and add in the no hits sequence_id_to_taxonomy = {} for seqio in SequenceIO().read_fasta_file(search_result.hit_fasta()): name = seqio.name if name in sequence_id_to_hit: # Add Root; to be in line with pplacer assignment method sequence_id_to_taxonomy[name] = ['Root']+taxonomy_definition[sequence_id_to_hit[name]] else: # picked up in the initial search (by hmmsearch, say), but diamond misses it sequence_id_to_taxonomy[name] = ['Root'] results[base_list[i]] = sequence_id_to_taxonomy return results def main(self): if self.args.subparser_name == 'graft': if self.args.verbosity >= self._MIN_VERBOSITY_FOR_ART: print(''' GRAFT Joel Boyd, Ben Woodcroft __/__ ______| _- - _ ________| |_____/ - - - | |____/_ - _ >>>> - >>>> ____| - _- - - | ______ - _ |_____| - |______ ''') self.graft() elif self.args.subparser_name == 'create': if self.args.verbosity >= self._MIN_VERBOSITY_FOR_ART: print(''' CREATE Joel Boyd, Ben Woodcroft / >a / ------------- / >b | | -------- >>> | GPKG | >c |________| ---------- ''') if self.args.dereplication_level < 0: logging.error("Invalid dereplication level selected! please enter a positive integer") exit(1) else: if not self.args.sequences: if not self.args.alignment and not self.args.rerooted_annotated_tree \ and not self.args.rerooted_tree: logging.error("Some sort of sequence data must be provided to run graftM create") exit(1) if self.args.taxonomy: if self.args.rerooted_annotated_tree: logging.error("--taxonomy is incompatible with --rerooted_annotated_tree") exit(1) if self.args.taxtastic_taxonomy or self.args.taxtastic_seqinfo: logging.error("--taxtastic_taxonomy and --taxtastic_seqinfo are incompatible with --taxonomy") exit(1) elif self.args.rerooted_annotated_tree: if self.args.taxtastic_taxonomy or self.args.taxtastic_seqinfo: logging.error("--taxtastic_taxonomy and --taxtastic_seqinfo are incompatible with --rerooted_annotated_tree") exit(1) else: if not self.args.taxtastic_taxonomy or not self.args.taxtastic_seqinfo: logging.error("--taxonomy, --rerooted_annotated_tree or --taxtastic_taxonomy/--taxtastic_seqinfo is required") exit(1) if bool(self.args.taxtastic_taxonomy) ^ bool(self.args.taxtastic_seqinfo): logging.error("Both or neither of --taxtastic_taxonomy and --taxtastic_seqinfo must be defined") exit(1) if self.args.alignment and self.args.hmm: logging.warn("Using both --alignment and --hmm is rarely useful, but proceding on the assumption you understand.") if len([_f for _f in [self.args.rerooted_tree, self.args.rerooted_annotated_tree, self.args.tree] if _f]) > 1: logging.error("Only 1 input tree can be specified") exit(1) self.create.main( dereplication_level = self.args.dereplication_level, sequences = self.args.sequences, alignment = self.args.alignment, taxonomy = self.args.taxonomy, rerooted_tree = self.args.rerooted_tree, unrooted_tree = self.args.tree, tree_log = self.args.tree_log, prefix = self.args.output, rerooted_annotated_tree = self.args.rerooted_annotated_tree, min_aligned_percent = float(self.args.min_aligned_percent)/100, taxtastic_taxonomy = self.args.taxtastic_taxonomy, taxtastic_seqinfo = self.args.taxtastic_seqinfo, hmm = self.args.hmm, search_hmm_files = self.args.search_hmm_files, force = self.args.force, threads = self.args.threads ) elif self.args.subparser_name == 'update': logging.info("GraftM package %s specified to update with sequences in %s" % (self.args.graftm_package, self.args.sequences)) if self.args.regenerate_diamond_db: gpkg = GraftMPackage.acquire(self.args.graftm_package) logging.info("Regenerating diamond DB..") gpkg.create_diamond_db() logging.info("Diamond database regenerated.") return elif not self.args.sequences: logging.error("--sequences is required unless regenerating the diamond DB") exit(1) if not self.args.output: if self.args.graftm_package.endswith(".gpkg"): self.args.output = self.args.graftm_package.replace(".gpkg", "-updated.gpkg") else: self.args.output = self.args.graftm_package + '-update.gpkg' Update(ExternalProgramSuite( ['taxit', 'FastTreeMP', 'hmmalign', 'mafft'])).update( input_sequence_path=self.args.sequences, input_taxonomy_path=self.args.taxonomy, input_graftm_package_path=self.args.graftm_package, output_graftm_package_path=self.args.output) elif self.args.subparser_name == 'expand_search': args = self.args if not args.graftm_package and not args.search_hmm_files: logging.error("expand_search mode requires either --graftm_package or --search_hmm_files") exit(1) if args.graftm_package: pkg = GraftMPackage.acquire(args.graftm_package) else: pkg = None expandsearcher = ExpandSearcher(search_hmm_files = args.search_hmm_files, maximum_range = args.maximum_range, threads = args.threads, evalue = args.evalue, min_orf_length = args.min_orf_length, graftm_package = pkg) expandsearcher.generate_expand_search_database_from_contigs(args.contigs, args.output_hmm, search_method=ExpandSearcher.HMM_SEARCH_METHOD) elif self.args.subparser_name == 'tree': if self.args.graftm_package: # shim in the paths from the graftm package, not overwriting # any of the provided paths. gpkg = GraftMPackage.acquire(self.args.graftm_package) if not self.args.rooted_tree: self.args.rooted_tree = gpkg.reference_package_tree_path() if not self.args.input_greengenes_taxonomy: if not self.args.input_taxtastic_seqinfo: self.args.input_taxtastic_seqinfo = gpkg.taxtastic_seqinfo_path() if not self.args.input_taxtastic_taxonomy: self.args.input_taxtastic_taxonomy = gpkg.taxtastic_taxonomy_path() if self.args.rooted_tree: if self.args.unrooted_tree: logging.error("Both a rooted tree and an un-rooted tree were provided, so it's unclear what you are asking GraftM to do. \ If you're unsure see graftM tree -h") exit(1) elif self.args.reference_tree: logging.error("Both a rooted tree and reference tree were provided, so it's unclear what you are asking GraftM to do. \ If you're unsure see graftM tree -h") exit(1) if not self.args.decorate: logging.error("It seems a rooted tree has been provided, but --decorate has not been specified so it is unclear what you are asking graftM to do.") exit(1) dec = Decorator(tree_path = self.args.rooted_tree) elif self.args.unrooted_tree and self.args.reference_tree: logging.debug("Using provided reference tree %s to reroot %s" % (self.args.reference_tree, self.args.unrooted_tree)) dec = Decorator(reference_tree_path = self.args.reference_tree, tree_path = self.args.unrooted_tree) else: logging.error("Some tree(s) must be provided, either a rooted tree or both an unrooted tree and a reference tree") exit(1) if self.args.output_taxonomy is None and self.args.output_tree is None: logging.error("Either an output tree or taxonomy must be provided") exit(1) if self.args.input_greengenes_taxonomy: if self.args.input_taxtastic_seqinfo or self.args.input_taxtastic_taxonomy: logging.error("Both taxtastic and greengenes taxonomy were provided, so its unclear what taxonomy you want graftM to decorate with") exit(1) logging.debug("Using input GreenGenes style taxonomy file") dec.main(self.args.input_greengenes_taxonomy, self.args.output_tree, self.args.output_taxonomy, self.args.no_unique_tax, self.args.decorate, None) elif self.args.input_taxtastic_seqinfo and self.args.input_taxtastic_taxonomy: logging.debug("Using input taxtastic style taxonomy/seqinfo") dec.main(self.args.input_taxtastic_taxonomy, self.args.output_tree, self.args.output_taxonomy, self.args.no_unique_tax, self.args.decorate, self.args.input_taxtastic_seqinfo) else: logging.error("Either a taxtastic taxonomy or seqinfo file was provided. GraftM cannot continue without both.") exit(1) elif self.args.subparser_name == 'archive': # Back slashes in the ASCII art are escaped. if self.args.verbosity >= self._MIN_VERBOSITY_FOR_ART: print(""" ARCHIVE Joel Boyd, Ben Woodcroft ____.----. ____.----' \\ \\ \\ \\ \\ \\ \\ \\ ____.----'`--.__ \\___.----' | `--.____ /`-._ | __.-' \\ / `-._ ___.---' \\ / `-.____.---' \\ +------+ / / | \\ \\ |`. |`. / / | \\ _.--' <===> | `+--+---+ `-. / | \\ __.--' | | | | `-._ / | \\ __.--' | | | | | | `-./ | \\_.-' | +---+--+ | | | | `. | `. | | | | `+------+ | | | | | | | | | | | | | | | `-. | _.-' `-. | __..--' `-. | __.-' `-|__.--' """) if self.args.create: if self.args.extract: logging.error("Please specify whether to either create or export a GraftM package") exit(1) if not self.args.graftm_package: logging.error("Creating a GraftM package archive requires an package to be specified") exit(1) if not self.args.archive: logging.error("Creating a GraftM package archive requires an output archive path to be specified") exit(1) archive = Archive() archive.create(self.args.graftm_package, self.args.archive, force=self.args.force) elif self.args.extract: archive = Archive() archive.extract(self.args.archive, self.args.graftm_package, force=self.args.force) else: logging.error("Please specify whether to either create or export a GraftM package") exit(1) else: raise Exception("Unexpected subparser name %s" % self.args.subparser_name)
wwood/graftM
graftm/run.py
Python
gpl-3.0
42,090
<?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/>. /** * @package block_fn_marking * @copyright Michael Gardener <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $capabilities = array( 'block/fn_marking:myaddinstance' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/my:manageblocks' ), 'block/fn_marking:addinstance' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/site:manageblocks' ), 'block/fn_marking:viewblock' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'user' => CAP_PREVENT, 'guest' => CAP_PREVENT, 'student' => CAP_PREVENT, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'block/fn_marking:viewreadonly' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'user' => CAP_PREVENT, 'guest' => CAP_PREVENT, 'student' => CAP_PREVENT, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ) );
nitro2010/moodle
blocks/fn_marking/db/access.php
PHP
gpl-3.0
2,269
// Search script generated by doxygen // Copyright (C) 2009 by Dimitri van Heesch. // The code in this file is loosly based on main.js, part of Natural Docs, // which is Copyright (C) 2003-2008 Greg Valure // Natural Docs is licensed under the GPL. var indexSectionsWithContent = { 0: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111001110111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 1: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011010000001010110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 2: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111100010001110111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 3: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111001110111101010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 4: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000101111111001110111110111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 5: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010010000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 6: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011110000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 7: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "files", 3: "functions", 4: "variables", 5: "typedefs", 6: "defines", 7: "pages" }; function convertToId(search) { var result = ''; for (i=0;i<search.length;i++) { var c = search.charAt(i); var cn = c.charCodeAt(0); if (c.match(/[a-z0-9]/)) { result+=c; } else if (cn<16) { result+="_0"+cn.toString(16); } else { result+="_"+cn.toString(16); } } return result; } function getXPos(item) { var x = 0; if (item.offsetWidth) { while (item && item!=document.body) { x += item.offsetLeft; item = item.offsetParent; } } return x; } function getYPos(item) { var y = 0; if (item.offsetWidth) { while (item && item!=document.body) { y += item.offsetTop; item = item.offsetParent; } } return y; } /* A class handling everything associated with the search panel. Parameters: name - The name of the global variable that will be storing this instance. Is needed to be able to set timeouts. resultPath - path to use for external files */ function SearchBox(name, resultsPath, inFrame, label) { if (!name || !resultsPath) { alert("Missing parameters to SearchBox."); } // ---------- Instance variables this.name = name; this.resultsPath = resultsPath; this.keyTimeout = 0; this.keyTimeoutLength = 500; this.closeSelectionTimeout = 300; this.lastSearchValue = ""; this.lastResultsPage = ""; this.hideTimeout = 0; this.searchIndex = 0; this.searchActive = false; this.insideFrame = inFrame; this.searchLabel = label; // ----------- DOM Elements this.DOMSearchField = function() { return document.getElementById("MSearchField"); } this.DOMSearchSelect = function() { return document.getElementById("MSearchSelect"); } this.DOMSearchSelectWindow = function() { return document.getElementById("MSearchSelectWindow"); } this.DOMPopupSearchResults = function() { return document.getElementById("MSearchResults"); } this.DOMPopupSearchResultsWindow = function() { return document.getElementById("MSearchResultsWindow"); } this.DOMSearchClose = function() { return document.getElementById("MSearchClose"); } this.DOMSearchBox = function() { return document.getElementById("MSearchBox"); } // ------------ Event Handlers // Called when focus is added or removed from the search field. this.OnSearchFieldFocus = function(isActive) { this.Activate(isActive); } this.OnSearchSelectShow = function() { var searchSelectWindow = this.DOMSearchSelectWindow(); var searchField = this.DOMSearchSelect(); if (this.insideFrame) { var left = getXPos(searchField); var top = getYPos(searchField); left += searchField.offsetWidth + 6; top += searchField.offsetHeight; // show search selection popup searchSelectWindow.style.display='block'; left -= searchSelectWindow.offsetWidth; searchSelectWindow.style.left = left + 'px'; searchSelectWindow.style.top = top + 'px'; } else { var left = getXPos(searchField); var top = getYPos(searchField); top += searchField.offsetHeight; // show search selection popup searchSelectWindow.style.display='block'; searchSelectWindow.style.left = left + 'px'; searchSelectWindow.style.top = top + 'px'; } // stop selection hide timer if (this.hideTimeout) { clearTimeout(this.hideTimeout); this.hideTimeout=0; } return false; // to avoid "image drag" default event } this.OnSearchSelectHide = function() { this.hideTimeout = setTimeout(this.name +".CloseSelectionWindow()", this.closeSelectionTimeout); } // Called when the content of the search field is changed. this.OnSearchFieldChange = function(evt) { if (this.keyTimeout) // kill running timer { clearTimeout(this.keyTimeout); this.keyTimeout = 0; } var e = (evt) ? evt : window.event; // for IE if (e.keyCode==40 || e.keyCode==13) { if (e.shiftKey==1) { this.OnSearchSelectShow(); var win=this.DOMSearchSelectWindow(); for (i=0;i<win.childNodes.length;i++) { var child = win.childNodes[i]; // get span within a if (child.className=='SelectItem') { child.focus(); return; } } return; } else if (window.frames.MSearchResults.searchResults) { var elem = window.frames.MSearchResults.searchResults.NavNext(0); if (elem) elem.focus(); } } else if (e.keyCode==27) // Escape out of the search field { this.DOMSearchField().blur(); this.DOMPopupSearchResultsWindow().style.display = 'none'; this.DOMSearchClose().style.display = 'none'; this.lastSearchValue = ''; this.Activate(false); return; } // strip whitespaces var searchValue = this.DOMSearchField().value.replace(/ +/g, ""); if (searchValue != this.lastSearchValue) // search value has changed { if (searchValue != "") // non-empty search { // set timer for search update this.keyTimeout = setTimeout(this.name + '.Search()', this.keyTimeoutLength); } else // empty search field { this.DOMPopupSearchResultsWindow().style.display = 'none'; this.DOMSearchClose().style.display = 'none'; this.lastSearchValue = ''; } } } this.SelectItemCount = function(id) { var count=0; var win=this.DOMSearchSelectWindow(); for (i=0;i<win.childNodes.length;i++) { var child = win.childNodes[i]; // get span within a if (child.className=='SelectItem') { count++; } } return count; } this.SelectItemSet = function(id) { var i,j=0; var win=this.DOMSearchSelectWindow(); for (i=0;i<win.childNodes.length;i++) { var child = win.childNodes[i]; // get span within a if (child.className=='SelectItem') { var node = child.firstChild; if (j==id) { node.innerHTML='&#8226;'; } else { node.innerHTML='&#160;'; } j++; } } } // Called when an search filter selection is made. // set item with index id as the active item this.OnSelectItem = function(id) { this.searchIndex = id; this.SelectItemSet(id); var searchValue = this.DOMSearchField().value.replace(/ +/g, ""); if (searchValue!="" && this.searchActive) // something was found -> do a search { this.Search(); } } this.OnSearchSelectKey = function(evt) { var e = (evt) ? evt : window.event; // for IE if (e.keyCode==40 && this.searchIndex<this.SelectItemCount()) // Down { this.searchIndex++; this.OnSelectItem(this.searchIndex); } else if (e.keyCode==38 && this.searchIndex>0) // Up { this.searchIndex--; this.OnSelectItem(this.searchIndex); } else if (e.keyCode==13 || e.keyCode==27) { this.OnSelectItem(this.searchIndex); this.CloseSelectionWindow(); this.DOMSearchField().focus(); } return false; } // --------- Actions // Closes the results window. this.CloseResultsWindow = function() { this.DOMPopupSearchResultsWindow().style.display = 'none'; this.DOMSearchClose().style.display = 'none'; this.Activate(false); } this.CloseSelectionWindow = function() { this.DOMSearchSelectWindow().style.display = 'none'; } // Performs a search. this.Search = function() { this.keyTimeout = 0; // strip leading whitespace var searchValue = this.DOMSearchField().value.replace(/^ +/, ""); var code = searchValue.toLowerCase().charCodeAt(0); var hexCode; if (code<16) { hexCode="0"+code.toString(16); } else { hexCode=code.toString(16); } var resultsPage; var resultsPageWithSearch; var hasResultsPage; if (indexSectionsWithContent[this.searchIndex].charAt(code) == '1') { resultsPage = this.resultsPath + '/' + indexSectionNames[this.searchIndex] + '_' + hexCode + '.html'; resultsPageWithSearch = resultsPage+'?'+escape(searchValue); hasResultsPage = true; } else // nothing available for this search term { resultsPage = this.resultsPath + '/nomatches.html'; resultsPageWithSearch = resultsPage; hasResultsPage = false; } window.frames.MSearchResults.location = resultsPageWithSearch; var domPopupSearchResultsWindow = this.DOMPopupSearchResultsWindow(); if (domPopupSearchResultsWindow.style.display!='block') { var domSearchBox = this.DOMSearchBox(); this.DOMSearchClose().style.display = 'inline'; if (this.insideFrame) { var domPopupSearchResults = this.DOMPopupSearchResults(); domPopupSearchResultsWindow.style.position = 'relative'; domPopupSearchResultsWindow.style.display = 'block'; var width = document.body.clientWidth - 8; // the -8 is for IE :-( domPopupSearchResultsWindow.style.width = width + 'px'; domPopupSearchResults.style.width = width + 'px'; } else { var domPopupSearchResults = this.DOMPopupSearchResults(); var left = getXPos(domSearchBox) + 150; // domSearchBox.offsetWidth; var top = getYPos(domSearchBox) + 20; // domSearchBox.offsetHeight + 1; domPopupSearchResultsWindow.style.display = 'block'; left -= domPopupSearchResults.offsetWidth; domPopupSearchResultsWindow.style.top = top + 'px'; domPopupSearchResultsWindow.style.left = left + 'px'; } } this.lastSearchValue = searchValue; this.lastResultsPage = resultsPage; } // -------- Activation Functions // Activates or deactivates the search panel, resetting things to // their default values if necessary. this.Activate = function(isActive) { if (isActive || // open it this.DOMPopupSearchResultsWindow().style.display == 'block' ) { this.DOMSearchBox().className = 'MSearchBoxActive'; var searchField = this.DOMSearchField(); if (searchField.value == this.searchLabel) // clear "Search" term upon entry { searchField.value = ''; this.searchActive = true; } } else if (!isActive) // directly remove the panel { this.DOMSearchBox().className = 'MSearchBoxInactive'; this.DOMSearchField().value = this.searchLabel; this.searchActive = false; this.lastSearchValue = '' this.lastResultsPage = ''; } } } // ----------------------------------------------------------------------- // The class that handles everything on the search results page. function SearchResults(name) { // The number of matches from the last run of <Search()>. this.lastMatchCount = 0; this.lastKey = 0; this.repeatOn = false; // Toggles the visibility of the passed element ID. this.FindChildElement = function(id) { var parentElement = document.getElementById(id); var element = parentElement.firstChild; while (element && element!=parentElement) { if (element.nodeName == 'DIV' && element.className == 'SRChildren') { return element; } if (element.nodeName == 'DIV' && element.hasChildNodes()) { element = element.firstChild; } else if (element.nextSibling) { element = element.nextSibling; } else { do { element = element.parentNode; } while (element && element!=parentElement && !element.nextSibling); if (element && element!=parentElement) { element = element.nextSibling; } } } } this.Toggle = function(id) { var element = this.FindChildElement(id); if (element) { if (element.style.display == 'block') { element.style.display = 'none'; } else { element.style.display = 'block'; } } } // Searches for the passed string. If there is no parameter, // it takes it from the URL query. // // Always returns true, since other documents may try to call it // and that may or may not be possible. this.Search = function(search) { if (!search) // get search word from URL { search = window.location.search; search = search.substring(1); // Remove the leading '?' search = unescape(search); } search = search.replace(/^ +/, ""); // strip leading spaces search = search.replace(/ +$/, ""); // strip trailing spaces search = search.toLowerCase(); search = convertToId(search); var resultRows = document.getElementsByTagName("div"); var matches = 0; var i = 0; while (i < resultRows.length) { var row = resultRows.item(i); if (row.className == "SRResult") { var rowMatchName = row.id.toLowerCase(); rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); // strip 'sr123_' if (search.length<=rowMatchName.length && rowMatchName.substr(0, search.length)==search) { row.style.display = 'block'; matches++; } else { row.style.display = 'none'; } } i++; } document.getElementById("Searching").style.display='none'; if (matches == 0) // no results { document.getElementById("NoMatches").style.display='block'; } else // at least one result { document.getElementById("NoMatches").style.display='none'; } this.lastMatchCount = matches; return true; } // return the first item with index index or higher that is visible this.NavNext = function(index) { var focusItem; while (1) { var focusName = 'Item'+index; focusItem = document.getElementById(focusName); if (focusItem && focusItem.parentNode.parentNode.style.display=='block') { break; } else if (!focusItem) // last element { break; } focusItem=null; index++; } return focusItem; } this.NavPrev = function(index) { var focusItem; while (1) { var focusName = 'Item'+index; focusItem = document.getElementById(focusName); if (focusItem && focusItem.parentNode.parentNode.style.display=='block') { break; } else if (!focusItem) // last element { break; } focusItem=null; index--; } return focusItem; } this.ProcessKeys = function(e) { if (e.type == "keydown") { this.repeatOn = false; this.lastKey = e.keyCode; } else if (e.type == "keypress") { if (!this.repeatOn) { if (this.lastKey) this.repeatOn = true; return false; // ignore first keypress after keydown } } else if (e.type == "keyup") { this.lastKey = 0; this.repeatOn = false; } return this.lastKey!=0; } this.Nav = function(evt,itemIndex) { var e = (evt) ? evt : window.event; // for IE if (e.keyCode==13) return true; if (!this.ProcessKeys(e)) return false; if (this.lastKey==38) // Up { var newIndex = itemIndex-1; var focusItem = this.NavPrev(newIndex); if (focusItem) { var child = this.FindChildElement(focusItem.parentNode.parentNode.id); if (child && child.style.display == 'block') // children visible { var n=0; var tmpElem; while (1) // search for last child { tmpElem = document.getElementById('Item'+newIndex+'_c'+n); if (tmpElem) { focusItem = tmpElem; } else // found it! { break; } n++; } } } if (focusItem) { focusItem.focus(); } else // return focus to search field { parent.document.getElementById("MSearchField").focus(); } } else if (this.lastKey==40) // Down { var newIndex = itemIndex+1; var focusItem; var item = document.getElementById('Item'+itemIndex); var elem = this.FindChildElement(item.parentNode.parentNode.id); if (elem && elem.style.display == 'block') // children visible { focusItem = document.getElementById('Item'+itemIndex+'_c0'); } if (!focusItem) focusItem = this.NavNext(newIndex); if (focusItem) focusItem.focus(); } else if (this.lastKey==39) // Right { var item = document.getElementById('Item'+itemIndex); var elem = this.FindChildElement(item.parentNode.parentNode.id); if (elem) elem.style.display = 'block'; } else if (this.lastKey==37) // Left { var item = document.getElementById('Item'+itemIndex); var elem = this.FindChildElement(item.parentNode.parentNode.id); if (elem) elem.style.display = 'none'; } else if (this.lastKey==27) // Escape { parent.searchBox.CloseResultsWindow(); parent.document.getElementById("MSearchField").focus(); } else if (this.lastKey==13) // Enter { return true; } return false; } this.NavChild = function(evt,itemIndex,childIndex) { var e = (evt) ? evt : window.event; // for IE if (e.keyCode==13) return true; if (!this.ProcessKeys(e)) return false; if (this.lastKey==38) // Up { if (childIndex>0) { var newIndex = childIndex-1; document.getElementById('Item'+itemIndex+'_c'+newIndex).focus(); } else // already at first child, jump to parent { document.getElementById('Item'+itemIndex).focus(); } } else if (this.lastKey==40) // Down { var newIndex = childIndex+1; var elem = document.getElementById('Item'+itemIndex+'_c'+newIndex); if (!elem) // last child, jump to parent next parent { elem = this.NavNext(itemIndex+1); } if (elem) { elem.focus(); } } else if (this.lastKey==27) // Escape { parent.searchBox.CloseResultsWindow(); parent.document.getElementById("MSearchField").focus(); } else if (this.lastKey==13) // Enter { return true; } return false; } } function setKeyActions(elem,action) { elem.setAttribute('onkeydown',action); elem.setAttribute('onkeypress',action); elem.setAttribute('onkeyup',action); } function setClassAttr(elem,attr) { elem.setAttribute('class',attr); elem.setAttribute('className',attr); } function createResults() { var results = document.getElementById("SRResults"); for (var e=0; e<searchData.length; e++) { var id = searchData[e][0]; var srResult = document.createElement('div'); srResult.setAttribute('id','SR_'+id); setClassAttr(srResult,'SRResult'); var srEntry = document.createElement('div'); setClassAttr(srEntry,'SREntry'); var srLink = document.createElement('a'); srLink.setAttribute('id','Item'+e); setKeyActions(srLink,'return searchResults.Nav(event,'+e+')'); setClassAttr(srLink,'SRSymbol'); srLink.innerHTML = searchData[e][1][0]; srEntry.appendChild(srLink); if (searchData[e][1].length==2) // single result { srLink.setAttribute('href',searchData[e][1][1][0]); if (searchData[e][1][1][1]) { srLink.setAttribute('target','_parent'); } var srScope = document.createElement('span'); setClassAttr(srScope,'SRScope'); srScope.innerHTML = searchData[e][1][1][2]; srEntry.appendChild(srScope); } else // multiple results { srLink.setAttribute('href','javascript:searchResults.Toggle("SR_'+id+'")'); var srChildren = document.createElement('div'); setClassAttr(srChildren,'SRChildren'); for (var c=0; c<searchData[e][1].length-1; c++) { var srChild = document.createElement('a'); srChild.setAttribute('id','Item'+e+'_c'+c); setKeyActions(srChild,'return searchResults.NavChild(event,'+e+','+c+')'); setClassAttr(srChild,'SRScope'); srChild.setAttribute('href',searchData[e][1][c+1][0]); if (searchData[e][1][c+1][1]) { srChild.setAttribute('target','_parent'); } srChild.innerHTML = searchData[e][1][c+1][2]; srChildren.appendChild(srChild); } srEntry.appendChild(srChildren); } srResult.appendChild(srEntry); results.appendChild(srResult); } }
hungly/Pacman
html/search/search.js
JavaScript
gpl-3.0
24,120
/*********************************************************************** ** ** Sturdy - note-taking app ** Copyright (C) 2016 Vladislav Tronko <[email protected]> ** ** Sturdy 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 Sturdy. If not, see <http://www.gnu.org/licenses/>. ** ***********************************************************************/ #include "entrymanager.h" #include <QDateTime> #include <QSqlDatabase> #include <QSqlQuery> #include <QVariant> #include <QDebug> using namespace Core; EntryManager::~EntryManager() { clear(); } void EntryManager::close(int entryId) { Entry* entry = getEntry(entryId); if (!entry) return; delete entry; m_entries.erase(entryId); } void EntryManager::clear() { for (auto entry : m_entries) { save(entry.first); delete entry.second; } m_entries.clear(); } bool EntryManager::save(int entryId) const { Entry* entry = m_entries.at(entryId); if (!entry->isModified) return true; entry->timestamp = QDateTime().toTime_t(); entry->isModified = false; QSqlDatabase db = QSqlDatabase::database(); QSqlQuery query(db); query.prepare(QStringLiteral("UPDATE entries SET content = ?, timestamp = ? WHERE id= ?")); query.addBindValue(entry->content); query.addBindValue(entry->timestamp); query.addBindValue(entryId); return query.exec(); } bool EntryManager::load(int entryId) { QSqlDatabase db = QSqlDatabase::database(); QSqlQuery query(db); query.prepare(QStringLiteral("SELECT id, content, timestamp FROM entries WHERE id= ?")); query.addBindValue(entryId); if (!query.exec()) return false; query.next(); Entry* entry = new Entry; entry->id = query.value(0).toInt(); entry->content = query.value(1).toString(); entry->timestamp = query.value(2).toUInt(); m_entries.insert(std::make_pair<>(entry->id, entry)); return true; } Entry* EntryManager::getEntry(int entryId) { auto it = m_entries.find(entryId); if (it == m_entries.end()) if (!load(entryId)) return nullptr; return m_entries.at(entryId); }
innermous/sturdy
src/core/entrymanager.cpp
C++
gpl-3.0
2,683
# Rain_Water_Trapping def trappedWater(a, size) : # left[i] stores height of tallest bar to the to left of it including itself left = [0] * size # Right [i] stores height of tallest bar to the to right of it including itself right = [0] * size # Initialize result waterVolume = 0 # filling left (list/array) left[0] = a[0] for i in range( 1, size): left[i] = max(left[i-1], a[i]) # filling right (list/array) right[size - 1] = a[size - 1] for i in range(size - 2, - 1, - 1): right[i] = max(right[i + 1], a[i]); # Calculating volume of the accumulated water element by element for i in range(0, size): waterVolume += min(left[i],right[i]) - a[i] return waterVolume # main program arr =[] n = int(input()) #input the number of towers for i in range(n): arr.append(int(input())) #storing length of each tower in array print("Maximum water that can be accumulated is ", trappedWater(arr, len(arr))) #Input: #12 #0 #1 #0 #2 #1 #0 #1 #3 #2 #1 #2 #1 #Output: #The maximum water trapped is 6
jainaman224/Algo_Ds_Notes
Rain_Water_Trapping/Rain_Water_Trapping.py
Python
gpl-3.0
1,208
using System.Reflection; using System.Runtime.CompilerServices; namespace System.Security.Principal { public interface IIdentity { string AuthenticationType { get; } bool IsAuthenticated { get; } string Name { get; } } }
mtenpow/xaeios
Core/XaeiOS.Core/OSCorlib/System/Security/Principal/IIdentity.cs
C#
gpl-3.0
270
/** * Copyright (c) 2017 HES-SO Valais - Smart Infrastructure Laboratory (http://silab.hes.ch) * * This file is part of StructuredSimulationFramework. * * The StructuredSimulationFramework 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. * * The StructuredSimulationFramework 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 StructuredSimulationFramework. * If not, see <http://www.gnu.org/licenses/>. * */ package ch.hevs.silab.structuredsim.interfaces; import java.util.List; /** * Name : IManageModifier * <p> * Description : Class to manage the modifier * <p> * Date : 25 July 2017 * @version 1.0 * @author Audrey Dupont */ public interface IManageModifier { /** * Method to initiate the modifier class inside a List */ public List<AModifier> initiateModifierList(); }
SiLab-group/structSim
structSimV1/src/main/java/ch/hevs/silab/structuredsim/interfaces/IManageModifier.java
Java
gpl-3.0
1,281
## Contribution If you want to add any enhancement feature or have found any bug and want to work on it, please open a new issue regarding that and put a message "I would like to work on it." And make sure every pull request should reference to an issue. #### Points on how to make pull request * You need to fork this repository to your account. * Clone it using ``` git clone https://github.com/FOSSEE/eSim.git ``` * Always create a new branch before making any changes. You can create new branch using ```git branch <branch-name> ``` * Checkout into your new branch using ```git checkout <branch-name>``` * Make changes to code and once you are done use ```git add <path to file changed or added>```. Now commit changes with proper message using ```git commit -m "Your message"```. * After commiting your changes push your changes to your forked repository using ```git push origin <branch-name>``` Finally create a pull request from github. There should be only one commit per pull request. * Please follow below guidelines for your commit message : * Commit message should be like : Fixes issue #[issue_number] - one line message of work you did. * After commit message, there should be a commit body where you can mention what you did in short or in detail. Please follow above method to file pull requests.
FOSSEE/eSim
CONTRIBUTION.md
Markdown
gpl-3.0
1,330
#Region "Microsoft.VisualBasic::e7960fcc4cc15725cc863a98473d765c, ..\interops\visualize\Circos\Circos\TrackDatas\Adapter\Highlights\Repeat.vb" ' Author: ' ' asuka ([email protected]) ' xieguigang ([email protected]) ' xie ([email protected]) ' ' Copyright (c) 2016 GPL3 Licensed ' ' ' GNU GENERAL PUBLIC LICENSE (GPL3) ' ' 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/>. #End Region Imports System.Drawing Imports System.Text Imports System.Text.RegularExpressions Imports Microsoft.VisualBasic Imports Microsoft.VisualBasic.Language Imports Microsoft.VisualBasic.Linq.Extensions Imports SMRUCC.genomics.ComponentModel Imports SMRUCC.genomics.SequenceModel.FASTA Namespace TrackDatas.Highlights Public Class Repeat : Inherits Highlights Sub New(repeat As IEnumerable(Of NtProps.Repeat), attrs As IEnumerable(Of Double)) Dim clMaps As IdentityColors = New IdentityGradients(attrs.Min, attrs.Max, 512) Dim v As Double() = attrs.ToArray Me.__source = New List(Of ValueTrackData)( repeat.ToArray(Function(x) __creates(x, maps:=clMaps, attrs:=v))) End Sub Private Shared Function __creates(loci As NtProps.Repeat, maps As IdentityColors, attrs As Double()) As ValueTrackData Dim left As Integer = CInt(Val(loci.Minimum.Replace(",", ""))) Dim Right As Integer = CInt(Val(loci.Maximum.Replace(",", ""))) Dim r As Double() = attrs.Skip(left).Take(Right - left).ToArray Return New ValueTrackData With { .start = left, .end = Right, .formatting = New Formatting With { .fill_color = maps.GetColor(r.Average) } } End Function Sub New(repeat As IEnumerable(Of NtProps.Repeat), Optional Color As String = "Brown") Me.__source = LinqAPI.MakeList(Of ValueTrackData) <= _ From x As NtProps.Repeat In repeat Let left = CInt(Val(x.Minimum)) Let right = CInt(Val(x.Maximum)) Select New ValueTrackData With { .start = left, .end = right, .formatting = New Formatting With { .fill_color = Color } } End Sub End Class End Namespace
amethyst-asuka/GCModeller
src/interops/visualize/Circos/Circos/TrackDatas/Adapter/Highlights/Repeat.vb
Visual Basic
gpl-3.0
3,104
var __v=[ { "Id": 2046, "Chapter": 630, "Name": "c++", "Sort": 0 } ]
zuiwuchang/king-document
data/chapters/630.js
JavaScript
gpl-3.0
85
/* * $Revision: 2299 $ * * last checkin: * $Author: gutwenger $ * $Date: 2012-05-07 15:57:08 +0200 (Mon, 07 May 2012) $ ***************************************************************/ /** \file * \brief Declaration of class SplitHeuristic. * * \author Andrea Wagner * * \par License: * This file is part of the Open Graph Drawing Framework (OGDF). * * Copyright (C). All rights reserved. * See README.txt in the root directory of the OGDF installation for details. * * \par * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * Version 2 or 3 as published by the Free Software Foundation; * see the file LICENSE.txt included in the packaging of this file * for details. * * \par * 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. * * \par * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * * \see http://www.gnu.org/copyleft/gpl.html ***************************************************************/ #ifdef _MSC_VER #pragma once #endif #ifndef OGDF_SPLIT_HEURISTIC_H #define OGDF_SPLIT_HEURISTIC_H #include <ogdf/basic/EdgeArray.h> #include <ogdf/layered/CrossingsMatrix.h> #include <ogdf/simultaneous/TwoLayerCrossMinSimDraw.h> namespace ogdf { //! The split heuristic for 2-layer crossing minimization. class OGDF_EXPORT SplitHeuristic : public TwoLayerCrossMinSimDraw { public: //! Initializes crossing minimization for hierarchy \a H. void init (const Hierarchy &H); //! Calls the split heuristic for level \a L. void call (Level &L); //! Calls the median heuristic for level \a L (simultaneous drawing). void call (Level &L, const EdgeArray<unsigned int> *edgeSubGraph); //! Does some clean-up after calls. void cleanup (); private: CrossingsMatrix *m_cm; Array<node> buffer; void recCall(Level&, int low, int high); }; }// end namespace ogdf #endif
kdbanman/browseRDF
tulip-3.8.0-src/thirdparty/OGDF/ogdf/layered/SplitHeuristic.h
C
gpl-3.0
2,264
----------------------------------- -- Area: Pashhow Marshlands [S] -- Mob: Virulent Peiste -- Note: PH for Sugaar ----------------------------------- local ID = require("scripts/zones/Pashhow_Marshlands_[S]/IDs") require("scripts/globals/mobs") ----------------------------------- function onMobDeath(mob, player, isKiller) end function onMobDespawn(mob) phOnDespawn(mob, ID.mob.SUGAAR_PH, 5, 3600) -- 1 hour end
m3rlin87/darkstar
scripts/zones/Pashhow_Marshlands_[S]/mobs/Virulent_Peiste.lua
Lua
gpl-3.0
421
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Mon May 06 00:15:52 EDT 2013 --> <title>Uses of Class org.spongycastle.asn1.x509.ReasonFlags</title> <meta name="date" content="2013-05-06"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.spongycastle.asn1.x509.ReasonFlags"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/spongycastle/asn1/x509/class-use/ReasonFlags.html" target="_top">Frames</a></li> <li><a href="ReasonFlags.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.spongycastle.asn1.x509.ReasonFlags" class="title">Uses of Class<br>org.spongycastle.asn1.x509.ReasonFlags</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.spongycastle.asn1.x509">org.spongycastle.asn1.x509</a></td> <td class="colLast"> <div class="block">Support classes useful for encoding and processing X.509 certificates.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.spongycastle.asn1.x509"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a> in <a href="../../../../../org/spongycastle/asn1/x509/package-summary.html">org.spongycastle.asn1.x509</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../org/spongycastle/asn1/x509/package-summary.html">org.spongycastle.asn1.x509</a> declared as <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>private <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></code></td> <td class="colLast"><span class="strong">IssuingDistributionPoint.</span><code><strong><a href="../../../../../org/spongycastle/asn1/x509/IssuingDistributionPoint.html#onlySomeReasons">onlySomeReasons</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>(package private) <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></code></td> <td class="colLast"><span class="strong">DistributionPoint.</span><code><strong><a href="../../../../../org/spongycastle/asn1/x509/DistributionPoint.html#reasons">reasons</a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/spongycastle/asn1/x509/package-summary.html">org.spongycastle.asn1.x509</a> that return <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></code></td> <td class="colLast"><span class="strong">IssuingDistributionPoint.</span><code><strong><a href="../../../../../org/spongycastle/asn1/x509/IssuingDistributionPoint.html#getOnlySomeReasons()">getOnlySomeReasons</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></code></td> <td class="colLast"><span class="strong">DistributionPoint.</span><code><strong><a href="../../../../../org/spongycastle/asn1/x509/DistributionPoint.html#getReasons()">getReasons</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../org/spongycastle/asn1/x509/package-summary.html">org.spongycastle.asn1.x509</a> with parameters of type <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../org/spongycastle/asn1/x509/DistributionPoint.html#DistributionPoint(org.spongycastle.asn1.x509.DistributionPointName, org.spongycastle.asn1.x509.ReasonFlags, org.spongycastle.asn1.x509.GeneralNames)">DistributionPoint</a></strong>(<a href="../../../../../org/spongycastle/asn1/x509/DistributionPointName.html" title="class in org.spongycastle.asn1.x509">DistributionPointName</a>&nbsp;distributionPoint, <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a>&nbsp;reasons, <a href="../../../../../org/spongycastle/asn1/x509/GeneralNames.html" title="class in org.spongycastle.asn1.x509">GeneralNames</a>&nbsp;cRLIssuer)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colLast"><code><strong><a href="../../../../../org/spongycastle/asn1/x509/IssuingDistributionPoint.html#IssuingDistributionPoint(org.spongycastle.asn1.x509.DistributionPointName, boolean, boolean, org.spongycastle.asn1.x509.ReasonFlags, boolean, boolean)">IssuingDistributionPoint</a></strong>(<a href="../../../../../org/spongycastle/asn1/x509/DistributionPointName.html" title="class in org.spongycastle.asn1.x509">DistributionPointName</a>&nbsp;distributionPoint, boolean&nbsp;onlyContainsUserCerts, boolean&nbsp;onlyContainsCACerts, <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a>&nbsp;onlySomeReasons, boolean&nbsp;indirectCRL, boolean&nbsp;onlyContainsAttributeCerts)</code> <div class="block">Constructor from given details.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/spongycastle/asn1/x509/class-use/ReasonFlags.html" target="_top">Frames</a></li> <li><a href="ReasonFlags.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
gnu-user/orwell
Orwell/doc/org/spongycastle/asn1/x509/class-use/ReasonFlags.html
HTML
gpl-3.0
10,495
<?php $plugin->version = 2012060700; //EOF
junwan6/cdhpoodll
blocks/ucla_office_hours/version.php
PHP
gpl-3.0
45
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="fr"> <context> <name></name> <message id="id-app-launcher-name"> <location filename="asteroid-timer.desktop.h" line="6"/> <source>Timer</source> <translation>Timer</translation> </message> </context> </TS>
AsteroidOS/asteroid-timer
i18n/asteroid-timer.en_GB.ts
TypeScript
gpl-3.0
323
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- #ifndef _DEFINES_H #define _DEFINES_H #include <AP_HAL_Boards.h> // Just so that it's completely clear... #define ENABLED 1 #define DISABLED 0 // this avoids a very common config error #define ENABLE ENABLED #define DISABLE DISABLED // Flight modes // ------------ #define YAW_HOLD 0 // heading hold at heading in control_yaw but allow input from pilot #define YAW_ACRO 1 // pilot controlled yaw using rate controller #define YAW_LOOK_AT_NEXT_WP 2 // point towards next waypoint (no pilot input accepted) #define YAW_LOOK_AT_LOCATION 3 // point towards a location held in yaw_look_at_WP (no pilot input accepted) #define YAW_CIRCLE 4 // point towards a location held in yaw_look_at_WP (no pilot input accepted) #define YAW_LOOK_AT_HOME 5 // point towards home (no pilot input accepted) #define YAW_LOOK_AT_HEADING 6 // point towards a particular angle (not pilot input accepted) #define YAW_LOOK_AHEAD 7 // WARNING! CODE IN DEVELOPMENT NOT PROVEN #define YAW_DRIFT 8 // #define YAW_RESETTOARMEDYAW 9 // point towards heading at time motors were armed #define ROLL_PITCH_STABLE 0 // pilot input roll, pitch angles #define ROLL_PITCH_ACRO 1 // pilot inputs roll, pitch rotation rates in body frame #define ROLL_PITCH_AUTO 2 // no pilot input. autopilot roll, pitch is sent to stabilize controller inputs #define ROLL_PITCH_STABLE_OF 3 // pilot inputs roll, pitch angles which are mixed with optical flow based position controller lean anbles #define ROLL_PITCH_DRIFT 4 // #define ROLL_PITCH_LOITER 5 // pilot inputs the desired horizontal velocities #define ROLL_PITCH_SPORT 6 // pilot inputs roll, pitch rotation rates in earth frame #define ROLL_PITCH_AUTOTUNE 7 // description of new roll-pitch mode #define ROLL_PITCH_HYBRID 8 // ST-JD pilot input roll, pitch angles when sticks are moved #define THROTTLE_MANUAL 0 // manual throttle mode - pilot input goes directly to motors #define THROTTLE_MANUAL_TILT_COMPENSATED 1 // mostly manual throttle but with some tilt compensation #define THROTTLE_HOLD 2 // alt hold plus pilot input of climb rate #define THROTTLE_AUTO 3 // auto pilot altitude controller with target altitude held in next_WP.alt #define THROTTLE_LAND 4 // landing throttle controller #define THROTTLE_MANUAL_HELI 5 // pilot manually controlled throttle for traditional helicopters // sonar - for use with CONFIG_SONAR_SOURCE #define SONAR_SOURCE_ADC 1 #define SONAR_SOURCE_ANALOG_PIN 2 // Ch6, Ch7 and Ch8 aux switch control #define AUX_SWITCH_PWM_TRIGGER_HIGH 1800 // pwm value above which the ch7 or ch8 option will be invoked #define AUX_SWITCH_PWM_TRIGGER_LOW 1200 // pwm value below which the ch7 or ch8 option will be disabled #define CH6_PWM_TRIGGER_HIGH 1800 #define CH6_PWM_TRIGGER_LOW 1200 #define AUX_SWITCH_DO_NOTHING 0 // aux switch disabled #define AUX_SWITCH_SET_HOVER 1 // deprecated #define AUX_SWITCH_FLIP 2 // flip #define AUX_SWITCH_SIMPLE_MODE 3 // change to simple mode #define AUX_SWITCH_RTL 4 // change to RTL flight mode #define AUX_SWITCH_SAVE_TRIM 5 // save current position as level #define AUX_SWITCH_ADC_FILTER 6 // deprecated #define AUX_SWITCH_SAVE_WP 7 // save mission waypoint or RTL if in auto mode #define AUX_SWITCH_MULTI_MODE 8 // depending upon CH6 position Flip (if ch6 is low), RTL (if ch6 in middle) or Save WP (if ch6 is high) #define AUX_SWITCH_CAMERA_TRIGGER 9 // trigger camera servo or relay #define AUX_SWITCH_SONAR 10 // allow enabling or disabling sonar in flight which helps avoid surface tracking when you are far above the ground #define AUX_SWITCH_FENCE 11 // allow enabling or disabling fence in flight #define AUX_SWITCH_RESETTOARMEDYAW 12 // changes yaw to be same as when quad was armed #define AUX_SWITCH_SUPERSIMPLE_MODE 13 // change to simple mode in middle, super simple at top #define AUX_SWITCH_ACRO_TRAINER 14 // low = disabled, middle = leveled, high = leveled and limited #define AUX_SWITCH_SPRAYER 15 // enable/disable the crop sprayer #define AUX_SWITCH_AUTO 16 // change to auto flight mode #define AUX_SWITCH_AUTOTUNE 17 // auto tune #define AUX_SWITCH_LAND 18 // change to LAND flight mode // values used by the ap.ch7_opt and ap.ch8_opt flags #define AUX_SWITCH_LOW 0 // indicates auxiliar switch is in the low position (pwm <1200) #define AUX_SWITCH_MIDDLE 1 // indicates auxiliar switch is in the middle position (pwm >1200, <1800) #define AUX_SWITCH_HIGH 2 // indicates auxiliar switch is in the high position (pwm >1800) // Frame types #define UNDEFINED_FRAME 0 #define QUAD_FRAME 1 #define TRI_FRAME 2 #define HEXA_FRAME 3 #define Y6_FRAME 4 #define OCTA_FRAME 5 #define HELI_FRAME 6 #define OCTA_QUAD_FRAME 7 #define SINGLE_FRAME 8 #define PLUS_FRAME 0 #define X_FRAME 1 #define V_FRAME 2 // LED output #define NORMAL_LEDS 0 #define SAVE_TRIM_LEDS 1 // Internal defines, don't edit and expect things to work // ------------------------------------------------------- #define TRUE 1 #define FALSE 0 #define ToRad(x) radians(x) // *pi/180 #define ToDeg(x) degrees(x) // *180/pi #define DEBUG 0 #define LOITER_RANGE 60 // for calculating power outside of loiter radius #define T6 1000000 #define T7 10000000 // GPS type codes - use the names, not the numbers #define GPS_PROTOCOL_NONE -1 #define GPS_PROTOCOL_NMEA 0 #define GPS_PROTOCOL_SIRF 1 #define GPS_PROTOCOL_UBLOX 2 #define GPS_PROTOCOL_IMU 3 #define GPS_PROTOCOL_MTK 4 #define GPS_PROTOCOL_HIL 5 #define GPS_PROTOCOL_MTK19 6 #define GPS_PROTOCOL_AUTO 7 // HIL enumerations #define HIL_MODE_DISABLED 0 #define HIL_MODE_ATTITUDE 1 #define HIL_MODE_SENSORS 2 // Altitude status definitions #define REACHED_ALT 0 #define DESCENDING 1 #define ASCENDING 2 // Auto Pilot modes // ---------------- #define STABILIZE 0 // hold level position #define ACRO 1 // rate control #define ALT_HOLD 2 // AUTO control #define AUTO 3 // AUTO control #define GUIDED 4 // AUTO control #define LOITER 5 // Hold a single location #define RTL 6 // AUTO control #define CIRCLE 7 // AUTO control #define POSITION 8 // AUTO control #define LAND 9 // AUTO control #define OF_LOITER 10 // Hold a single location using optical flow sensor #define DRIFT 11 // DRIFT mode (Note: 12 is no longer used) #define SPORT 13 // earth frame rate control #define HYBRID 14 // ST-JD Hybrid mode = Loiter with direct stick commands #define NUM_MODES 15 // CH_6 Tuning // ----------- #define CH6_NONE 0 // no tuning performed #define CH6_STABILIZE_ROLL_PITCH_KP 1 // stabilize roll/pitch angle controller's P term #define CH6_RATE_ROLL_PITCH_KP 4 // body frame roll/pitch rate controller's P term #define CH6_RATE_ROLL_PITCH_KI 5 // body frame roll/pitch rate controller's I term #define CH6_RATE_ROLL_PITCH_KD 21 // body frame roll/pitch rate controller's D term #define CH6_STABILIZE_YAW_KP 3 // stabilize yaw heading controller's P term #define CH6_YAW_RATE_KP 6 // body frame yaw rate controller's P term #define CH6_YAW_RATE_KD 26 // body frame yaw rate controller's D term #define CH6_ALTITUDE_HOLD_KP 14 // altitude hold controller's P term (alt error to desired rate) #define CH6_THROTTLE_RATE_KP 7 // throttle rate controller's P term (desired rate to acceleration or motor output) #define CH6_THROTTLE_RATE_KD 37 // throttle rate controller's D term (desired rate to acceleration or motor output) #define CH6_THROTTLE_ACCEL_KP 34 // accel based throttle controller's P term #define CH6_THROTTLE_ACCEL_KI 35 // accel based throttle controller's I term #define CH6_THROTTLE_ACCEL_KD 36 // accel based throttle controller's D term #define CH6_LOITER_POSITION_KP 12 // loiter distance controller's P term (position error to speed) #define CH6_LOITER_RATE_KP 22 // loiter rate controller's P term (speed error to tilt angle) #define CH6_LOITER_RATE_KI 28 // loiter rate controller's I term (speed error to tilt angle) #define CH6_LOITER_RATE_KD 23 // loiter rate controller's D term (speed error to tilt angle) #define CH6_WP_SPEED 10 // maximum speed to next way point (0 to 10m/s) #define CH6_ACRO_RP_KP 25 // acro controller's P term. converts pilot input to a desired roll, pitch or yaw rate #define CH6_ACRO_YAW_KP 40 // acro controller's P term. converts pilot input to a desired roll, pitch or yaw rate #define CH6_RELAY 9 // switch relay on if ch6 high, off if low #define CH6_HELI_EXTERNAL_GYRO 13 // TradHeli specific external tail gyro gain #define CH6_OPTFLOW_KP 17 // optical flow loiter controller's P term (position error to tilt angle) #define CH6_OPTFLOW_KI 18 // optical flow loiter controller's I term (position error to tilt angle) #define CH6_OPTFLOW_KD 19 // optical flow loiter controller's D term (position error to tilt angle) #define CH6_AHRS_YAW_KP 30 // ahrs's compass effect on yaw angle (0 = very low, 1 = very high) #define CH6_AHRS_KP 31 // accelerometer effect on roll/pitch angle (0=low) #define CH6_INAV_TC 32 // inertial navigation baro/accel and gps/accel time constant (1.5 = strong baro/gps correction on accel estimatehas very strong does not correct accel estimate, 7 = very weak correction) #define CH6_DECLINATION 38 // compass declination in radians #define CH6_CIRCLE_RATE 39 // circle turn rate in degrees (hard coded to about 45 degrees in either direction) #define CH6_SONAR_GAIN 41 // sonar gain // Acro Trainer types #define ACRO_TRAINER_DISABLED 0 #define ACRO_TRAINER_LEVELING 1 #define ACRO_TRAINER_LIMITED 2 // Commands - Note that APM now uses a subset of the MAVLink protocol // commands. See enum MAV_CMD in the GCS_Mavlink library #define CMD_BLANK 0 // there is no command stored in the mem location // requested #define NO_COMMAND 0 // Navigation modes held in nav_mode variable #define NAV_NONE 0 #define NAV_CIRCLE 1 #define NAV_LOITER 2 #define NAV_WP 3 #define NAV_HYBRID 4 // ST-JD: nav mode, used for initialisation on nav mode change // Yaw behaviours during missions - possible values for WP_YAW_BEHAVIOR parameter #define WP_YAW_BEHAVIOR_NONE 0 // auto pilot will never control yaw during missions or rtl (except for DO_CONDITIONAL_YAW command received) #define WP_YAW_BEHAVIOR_LOOK_AT_NEXT_WP 1 // auto pilot will face next waypoint or home during rtl #define WP_YAW_BEHAVIOR_LOOK_AT_NEXT_WP_EXCEPT_RTL 2 // auto pilot will face next waypoint except when doing RTL at which time it will stay in it's last #define WP_YAW_BEHAVIOR_LOOK_AHEAD 3 // auto pilot will look ahead during missions and rtl (primarily meant for traditional helicotpers) // Waypoint options #define MASK_OPTIONS_RELATIVE_ALT 1 #define WP_OPTION_ALT_CHANGE 2 #define WP_OPTION_YAW 4 #define WP_OPTION_ALT_REQUIRED 8 #define WP_OPTION_RELATIVE 16 //#define WP_OPTION_ 32 //#define WP_OPTION_ 64 #define WP_OPTION_NEXT_CMD 128 // RTL state #define RTL_STATE_START 0 #define RTL_STATE_INITIAL_CLIMB 1 #define RTL_STATE_RETURNING_HOME 2 #define RTL_STATE_LOITERING_AT_HOME 3 #define RTL_STATE_FINAL_DESCENT 4 #define RTL_STATE_LAND 5 // LAND state #define LAND_STATE_FLY_TO_LOCATION 0 #define LAND_STATE_DESCENDING 1 //repeating events #define RELAY_TOGGLE 5 // GCS Message ID's /// NOTE: to ensure we never block on sending MAVLink messages /// please keep each MSG_ to a single MAVLink message. If need be /// create new MSG_ IDs for additional messages on the same /// stream enum ap_message { MSG_HEARTBEAT, MSG_ATTITUDE, MSG_LOCATION, MSG_EXTENDED_STATUS1, MSG_EXTENDED_STATUS2, MSG_NAV_CONTROLLER_OUTPUT, MSG_CURRENT_WAYPOINT, MSG_VFR_HUD, MSG_RADIO_OUT, MSG_RADIO_IN, MSG_RAW_IMU1, MSG_RAW_IMU2, MSG_RAW_IMU3, MSG_GPS_RAW, MSG_SYSTEM_TIME, MSG_SERVO_OUT, MSG_NEXT_WAYPOINT, MSG_NEXT_PARAM, MSG_STATUSTEXT, MSG_LIMITS_STATUS, MSG_AHRS, MSG_SIMSTATE, MSG_HWSTATUS, MSG_RETRY_DEFERRED // this must be last }; // Logging parameters #define TYPE_AIRSTART_MSG 0x00 #define TYPE_GROUNDSTART_MSG 0x01 #define LOG_ATTITUDE_MSG 0x01 #define LOG_MODE_MSG 0x03 #define LOG_CONTROL_TUNING_MSG 0x04 #define LOG_NAV_TUNING_MSG 0x05 #define LOG_PERFORMANCE_MSG 0x06 #define LOG_CMD_MSG 0x08 #define LOG_CURRENT_MSG 0x09 #define LOG_STARTUP_MSG 0x0A #define LOG_OPTFLOW_MSG 0x0C #define LOG_EVENT_MSG 0x0D #define LOG_PID_MSG 0x0E #define LOG_COMPASS_MSG 0x0F #define LOG_INAV_MSG 0x11 #define LOG_CAMERA_MSG 0x12 #define LOG_ERROR_MSG 0x13 #define LOG_DATA_INT16_MSG 0x14 #define LOG_DATA_UINT16_MSG 0x15 #define LOG_DATA_INT32_MSG 0x16 #define LOG_DATA_UINT32_MSG 0x17 #define LOG_DATA_FLOAT_MSG 0x18 #define LOG_AUTOTUNE_MSG 0x19 #define LOG_AUTOTUNEDETAILS_MSG 0x1A #define LOG_INDEX_MSG 0xF0 #define MAX_NUM_LOGS 50 #define MASK_LOG_ATTITUDE_FAST (1<<0) #define MASK_LOG_ATTITUDE_MED (1<<1) #define MASK_LOG_GPS (1<<2) #define MASK_LOG_PM (1<<3) #define MASK_LOG_CTUN (1<<4) #define MASK_LOG_NTUN (1<<5) #define MASK_LOG_RCIN (1<<6) #define MASK_LOG_IMU (1<<7) #define MASK_LOG_CMD (1<<8) #define MASK_LOG_CURRENT (1<<9) #define MASK_LOG_RCOUT (1<<10) #define MASK_LOG_OPTFLOW (1<<11) #define MASK_LOG_PID (1<<12) #define MASK_LOG_COMPASS (1<<13) #define MASK_LOG_INAV (1<<14) #define MASK_LOG_CAMERA (1<<15) // DATA - event logging #define DATA_MAVLINK_FLOAT 1 #define DATA_MAVLINK_INT32 2 #define DATA_MAVLINK_INT16 3 #define DATA_MAVLINK_INT8 4 #define DATA_AP_STATE 7 #define DATA_INIT_SIMPLE_BEARING 9 #define DATA_ARMED 10 #define DATA_DISARMED 11 #define DATA_AUTO_ARMED 15 #define DATA_TAKEOFF 16 #define DATA_LAND_COMPLETE 18 #define DATA_NOT_LANDED 28 #define DATA_LOST_GPS 19 #define DATA_BEGIN_FLIP 21 #define DATA_END_FLIP 22 #define DATA_EXIT_FLIP 23 #define DATA_SET_HOME 25 #define DATA_SET_SIMPLE_ON 26 #define DATA_SET_SIMPLE_OFF 27 #define DATA_SET_SUPERSIMPLE_ON 29 #define DATA_AUTOTUNE_INITIALISED 30 #define DATA_AUTOTUNE_OFF 31 #define DATA_AUTOTUNE_RESTART 32 #define DATA_AUTOTUNE_COMPLETE 33 #define DATA_AUTOTUNE_ABANDONED 34 #define DATA_AUTOTUNE_REACHED_LIMIT 35 #define DATA_AUTOTUNE_TESTING 36 #define DATA_AUTOTUNE_SAVEDGAINS 37 #define DATA_SAVE_TRIM 38 #define DATA_SAVEWP_ADD_WP 39 #define DATA_SAVEWP_CLEAR_MISSION_RTL 40 #define DATA_FENCE_ENABLE 41 #define DATA_FENCE_DISABLE 42 #define DATA_ACRO_TRAINER_DISABLED 43 #define DATA_ACRO_TRAINER_LEVELING 44 #define DATA_ACRO_TRAINER_LIMITED 45 // RADIANS #define RADX100 0.000174532925f #define DEGX100 5729.57795f // EEPROM addresses #define EEPROM_MAX_ADDR 4096 // parameters get the first 1536 bytes of EEPROM, remainder is for waypoints #define WP_START_BYTE 0x600 // where in memory home WP is stored + all other // WP #define WP_SIZE 15 // fence points are stored at the end of the EEPROM #define MAX_FENCEPOINTS 6 #define FENCE_WP_SIZE sizeof(Vector2l) #define FENCE_START_BYTE (EEPROM_MAX_ADDR-(MAX_FENCEPOINTS*FENCE_WP_SIZE)) #define MAX_WAYPOINTS ((FENCE_START_BYTE - WP_START_BYTE) / WP_SIZE) - 1 // - // 1 // to // be // safe // mark a function as not to be inlined #define NOINLINE __attribute__((noinline)) // IMU selection #define CONFIG_IMU_OILPAN 1 #define CONFIG_IMU_MPU6000 2 #define CONFIG_IMU_SITL 3 #define CONFIG_IMU_PX4 4 #define CONFIG_IMU_FLYMAPLE 5 #define AP_BARO_BMP085 1 #define AP_BARO_MS5611 2 #define AP_BARO_PX4 3 #define AP_BARO_MS5611_SPI 1 #define AP_BARO_MS5611_I2C 2 // Error message sub systems and error codes #define ERROR_SUBSYSTEM_MAIN 1 #define ERROR_SUBSYSTEM_RADIO 2 #define ERROR_SUBSYSTEM_COMPASS 3 #define ERROR_SUBSYSTEM_OPTFLOW 4 #define ERROR_SUBSYSTEM_FAILSAFE_RADIO 5 #define ERROR_SUBSYSTEM_FAILSAFE_BATT 6 #define ERROR_SUBSYSTEM_FAILSAFE_GPS 7 #define ERROR_SUBSYSTEM_FAILSAFE_GCS 8 #define ERROR_SUBSYSTEM_FAILSAFE_FENCE 9 #define ERROR_SUBSYSTEM_FLIGHT_MODE 10 #define ERROR_SUBSYSTEM_GPS 11 #define ERROR_SUBSYSTEM_CRASH_CHECK 12 // general error codes #define ERROR_CODE_ERROR_RESOLVED 0 #define ERROR_CODE_FAILED_TO_INITIALISE 1 // subsystem specific error codes -- radio #define ERROR_CODE_RADIO_LATE_FRAME 2 // subsystem specific error codes -- failsafe_thr, batt, gps #define ERROR_CODE_FAILSAFE_RESOLVED 0 #define ERROR_CODE_FAILSAFE_OCCURRED 1 // subsystem specific error codes -- compass #define ERROR_CODE_COMPASS_FAILED_TO_READ 2 // subsystem specific error codes -- gps #define ERROR_CODE_GPS_GLITCH 2 // subsystem specific error codes -- main #define ERROR_CODE_MAIN_INS_DELAY 1 // subsystem specific error codes -- crash checker #define ERROR_CODE_CRASH_CHECK_CRASH 1 // Arming Check Enable/Disable bits #define ARMING_CHECK_NONE 0x00 #define ARMING_CHECK_ALL 0x01 #define ARMING_CHECK_BARO 0x02 #define ARMING_CHECK_COMPASS 0x04 #define ARMING_CHECK_GPS 0x08 #define ARMING_CHECK_INS 0x10 #define ARMING_CHECK_PARAMETERS 0x20 #define ARMING_CHECK_RC 0x40 #define ARMING_CHECK_VOLTAGE 0x80 // Radio failsafe definitions (FS_THR parameter) #define FS_THR_DISABLED 0 #define FS_THR_ENABLED_ALWAYS_RTL 1 #define FS_THR_ENABLED_CONTINUE_MISSION 2 #define FS_THR_ENABLED_ALWAYS_LAND 3 // Battery failsafe definitions (FS_BATT_ENABLE parameter) #define FS_BATT_DISABLED 0 // battery failsafe disabled #define FS_BATT_LAND 1 // switch to LAND mode on battery failsafe #define FS_BATT_RTL 2 // switch to RTL mode on battery failsafe // GPS Failsafe definitions (FS_GPS_ENABLE parameter) #define FS_GPS_DISABLED 0 // GPS failsafe disabled #define FS_GPS_LAND 1 // switch to LAND mode on GPS Failsafe #define FS_GPS_ALTHOLD 2 // switch to ALTHOLD mode on GPS failsafe #define FS_GPS_LAND_EVEN_STABILIZE 3 // switch to LAND mode on GPS failsafe even if in a manual flight mode like Stabilize #endif // _DEFINES_H
Ju1ien/ArdupilotST-JD-outdated
ArduCopter/defines.h
C
gpl-3.0
21,508
using System; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.Core; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; using Geekbot.Core.GuildSettingsManager; using Geekbot.Core.RandomNumberGenerator; using Localization = Geekbot.Core.Localization; namespace Geekbot.Bot.Commands.Randomness { public class Ship : GeekbotCommandBase { private readonly IRandomNumberGenerator _randomNumberGenerator; private readonly DatabaseContext _database; public Ship(DatabaseContext database, IErrorHandler errorHandler, IRandomNumberGenerator randomNumberGenerator, IGuildSettingsManager guildSettingsManager) : base(errorHandler, guildSettingsManager) { _database = database; _randomNumberGenerator = randomNumberGenerator; } [Command("Ship", RunMode = RunMode.Async)] [Summary("Ask the Shipping meter")] public async Task Command([Summary("@user1")] IUser user1, [Summary("@user2")] IUser user2) { try { var userKeys = user1.Id < user2.Id ? new Tuple<long, long>(user1.Id.AsLong(), user2.Id.AsLong()) : new Tuple<long, long>(user2.Id.AsLong(), user1.Id.AsLong()); var dbval = _database.Ships.FirstOrDefault(s => s.FirstUserId.Equals(userKeys.Item1) && s.SecondUserId.Equals(userKeys.Item2)); var shippingRate = 0; if (dbval == null) { shippingRate = _randomNumberGenerator.Next(1, 100); _database.Ships.Add(new ShipsModel() { FirstUserId = userKeys.Item1, SecondUserId = userKeys.Item2, Strength = shippingRate }); await _database.SaveChangesAsync(); } else { shippingRate = dbval.Strength; } var reply = $":heartpulse: **{Localization.Ship.Matchmaking}** :heartpulse:\r\n"; reply += $":two_hearts: {user1.Mention} :heart: {user2.Mention} :two_hearts:\r\n"; reply += $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate)}"; await ReplyAsync(reply); } catch (Exception e) { await ErrorHandler.HandleCommandException(e, Context); } } private string DeterminateSuccess(int rate) { return (rate / 20) switch { 0 => Localization.Ship.NotGoingToHappen, 1 => Localization.Ship.NotSuchAGoodIdea, 2 => Localization.Ship.ThereMightBeAChance, 3 => Localization.Ship.CouldWork, 4 => Localization.Ship.ItsAMatch, _ => "nope" }; } private string BlockCounter(int rate) { var amount = rate / 10; Console.WriteLine(amount); var blocks = ""; for (var i = 1; i <= 10; i++) if (i <= amount) { blocks += ":white_medium_small_square:"; if (i == amount) blocks += $" {rate}% "; } else { blocks += ":black_medium_small_square:"; } return blocks; } } }
pizzaandcoffee/Geekbot.net
src/Bot/Commands/Randomness/Ship.cs
C#
gpl-3.0
3,809
class CreateIp4NetworkLocationJoinTable < ActiveRecord::Migration def change create_join_table :ip4_networks, :locations do |t| t.index [:ip4_network_id,:location_id], unique: true, name: 'ip4_network_location' end end end
iqeo/iqeo-server
db/migrate/20141024015712_create_ip4_network_location_join_table.rb
Ruby
gpl-3.0
241
using System; using System.Diagnostics.CodeAnalysis; using JetBrains.Annotations; using NSubstitute; using NUnit.Framework; using Ploeh.AutoFixture.NUnit3; using Selkie.EasyNetQ; using Selkie.NUnit.Extensions; using Selkie.Services.Common.Messages; using Selkie.Windsor; namespace Selkie.Services.Racetracks.Tests { [ExcludeFromCodeCoverage] [TestFixture] internal sealed class ServiceTests { [Theory] [AutoNSubstituteData] public void Constructor_ReturnsInstance_WhenCalled([NotNull] [Frozen] ISelkieBus bus, [NotNull] Service service) { // assemble // act var sut = new Service(Substitute.For <ISelkieBus>(), Substitute.For <ISelkieLogger>(), Substitute.For <ISelkieManagementClient>()); // assert Assert.NotNull(sut); } [Theory] [AutoNSubstituteData] public void ServiceInitializeSubscribesToPingRequestMessageTest([NotNull] [Frozen] ISelkieBus bus, [NotNull] Service service) { // assemble // act service.Initialize(); string subscriptionId = service.GetType().ToString(); // assert bus.Received().SubscribeAsync(subscriptionId, Arg.Any <Action <PingRequestMessage>>()); } [Theory] [AutoNSubstituteData] public void ServiceStartSendsMessageTest([NotNull] [Frozen] ISelkieBus bus, [NotNull] Service service) { // assemble // act service.Start(); // assert bus.Received().Publish(Arg.Is <ServiceStartedResponseMessage>(x => x.ServiceName == Service.ServiceName)); } [Theory] [AutoNSubstituteData] public void ServiceStopSendsMessageTest([NotNull] [Frozen] ISelkieBus bus, [NotNull] Service service) { // assemble // act service.Stop(); // assert bus.Received().Publish(Arg.Is <ServiceStoppedResponseMessage>(x => x.ServiceName == Service.ServiceName)); } } }
tschroedter/Selkie.Services.Racetracks
Selkie.Services.Racetracks.Tests/ServiceTests.cs
C#
gpl-3.0
2,442
<!doctype html> <html lang="{{ .Site.Language.Lang }}" class="no-js"> <head> {{ partial "head.html" . }} </head> <body class="td-{{ .Kind }}"> <header> {{ partial "navbar.html" . }} </header> <div class="container-fluid td-outer"> <div class="td-main"> <div class="row flex-xl-nowrap"> <aside class="col-12 col-md-3 col-xl-2 td-sidebar d-print-none"> {{ partial "sidebar.html" . }} </aside> <aside class="d-none d-xl-block col-xl-2 td-sidebar-toc d-print-none"> {{ partial "page-meta-links.html" . }} {{ partial "toc.html" . }} {{ partial "taxonomy_terms_clouds.html" . }} </aside> <main class="col-12 col-md-9 col-xl-8 pl-md-5" role="main"> {{ partial "version-banner.html" . }} {{ if not .Site.Params.ui.breadcrumb_disable }}{{ partial "breadcrumb.html" . }}{{ end }} {{ block "main" . }}{{ end }} </main> </div> </div> {{ partial "footer.html" . }} </div> {{ partial "scripts.html" . }} </body> </html>
e154/smart-home
doc/themes/docsy/layouts/docs/baseof.html
HTML
gpl-3.0
1,122
// Copyright 2014 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package types import ( "bytes" "fmt" "io" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/rlp" ) type Receipt struct { PostState []byte CumulativeGasUsed *big.Int Bloom Bloom TxHash common.Hash ContractAddress common.Address logs state.Logs GasUsed *big.Int } func NewReceipt(root []byte, cumulativeGasUsed *big.Int) *Receipt { return &Receipt{PostState: common.CopyBytes(root), CumulativeGasUsed: new(big.Int).Set(cumulativeGasUsed)} } func (self *Receipt) SetLogs(logs state.Logs) { self.logs = logs } func (self *Receipt) Logs() state.Logs { return self.logs } func (self *Receipt) EncodeRLP(w io.Writer) error { return rlp.Encode(w, []interface{}{self.PostState, self.CumulativeGasUsed, self.Bloom, self.logs}) } func (self *Receipt) DecodeRLP(s *rlp.Stream) error { var r struct { PostState []byte CumulativeGasUsed *big.Int Bloom Bloom TxHash common.Hash ContractAddress common.Address Logs state.Logs GasUsed *big.Int } if err := s.Decode(&r); err != nil { return err } self.PostState, self.CumulativeGasUsed, self.Bloom, self.TxHash, self.ContractAddress, self.logs, self.GasUsed = r.PostState, r.CumulativeGasUsed, r.Bloom, r.TxHash, r.ContractAddress, r.Logs, r.GasUsed return nil } type ReceiptForStorage Receipt func (self *ReceiptForStorage) EncodeRLP(w io.Writer) error { storageLogs := make([]*state.LogForStorage, len(self.logs)) for i, log := range self.logs { storageLogs[i] = (*state.LogForStorage)(log) } return rlp.Encode(w, []interface{}{self.PostState, self.CumulativeGasUsed, self.Bloom, self.TxHash, self.ContractAddress, storageLogs, self.GasUsed}) } func (self *Receipt) RlpEncode() []byte { bytes, err := rlp.EncodeToBytes(self) if err != nil { fmt.Println("TMP -- RECEIPT ENCODE ERROR", err) } return bytes } func (self *Receipt) Cmp(other *Receipt) bool { if bytes.Compare(self.PostState, other.PostState) != 0 { return false } return true } func (self *Receipt) String() string { return fmt.Sprintf("receipt{med=%x cgas=%v bloom=%x logs=%v}", self.PostState, self.CumulativeGasUsed, self.Bloom, self.logs) } type Receipts []*Receipt func (self Receipts) RlpEncode() []byte { bytes, err := rlp.EncodeToBytes(self) if err != nil { fmt.Println("TMP -- RECEIPTS ENCODE ERROR", err) } return bytes } func (self Receipts) Len() int { return len(self) } func (self Receipts) GetRlp(i int) []byte { return common.Rlp(self[i]) }
crazyquark/go-ethereum
core/types/receipt.go
GO
gpl-3.0
3,431
/* Simple DirectMedia Layer Copyright (C) 1997-2015 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /** * \file SDL_clipboard.h * * Include file for SDL clipboard handling */ #ifndef _SDL_clipboard_h #define _SDL_clipboard_h #include "SDL_stdinc.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Function prototypes */ /** * \brief Put UTF-8 text into the clipboard * * \sa SDL_GetClipboardText() */ extern DECLSPEC int SDLCALL SDL_SetClipboardText(const char *text); /** * \brief Get UTF-8 text from the clipboard, which must be freed with SDL_free() * * \sa SDL_SetClipboardText() */ extern DECLSPEC char * SDLCALL SDL_GetClipboardText(void); /** * \brief Returns a flag indicating whether the clipboard exists and contains a text string that is non-empty * * \sa SDL_GetClipboardText() */ extern DECLSPEC SDL_bool SDLCALL SDL_HasClipboardText(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_clipboard_h */ /* vi: set ts=4 sw=4 expandtab: */
bagnalla/puddi
windows_dependencies/include/SDL2/SDL_clipboard.h
C
gpl-3.0
2,037
/** * Hub Miner: a hubness-aware machine learning experimentation library. * Copyright (C) 2014 Nenad Tomasev. Email: nenad.tomasev at gmail.com * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 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 draw.basic; import java.awt.*; import java.awt.image.*; import java.io.*; import java.util.Arrays; import java.util.List; import javax.imageio.*; import javax.swing.*; /** * This is a convenience class to create and optionally save to a file a * BufferedImage of an area shown on the screen. It covers several different * scenarios, so the image can be created of: * * a) an entire component b) a region of the component c) the entire desktop d) * a region of the desktop * * This class can also be used to create images of components not displayed on a * GUI. The only foolproof way to get an image in such cases is to make sure the * component has been added to a realized window with code something like the * following: * * JFrame frame = new JFrame(); frame.setContentPane( someComponent ); * frame.pack(); ScreenImage.createImage( someComponent ); * * @author This code has been taken from the following web sources: * https://www.wuestkamp.com/2012/02/java-save-component-to-image-make-screen-shot-of-component/ * http://tips4java.wordpress.com/2008/10/13/screen-image/ */ public class ScreenImage { private static List<String> imageTypes = Arrays.asList( ImageIO.getWriterFileSuffixes()); /** * Create a BufferedImage for Swing components. The entire component will be * captured to an image. * * @param component Swing component to create the image from. * @return image The image for the given region. */ public static BufferedImage createImage(JComponent component) { Dimension dim = component.getSize(); if (dim.width == 0 || dim.height == 0) { dim = component.getPreferredSize(); component.setSize(dim); } Rectangle region = new Rectangle(0, 0, dim.width, dim.height); return ScreenImage.createImage(component, region); } /** * Create a BufferedImage for Swing components. All or part of the component * can be captured to an image. * * @param component Swing component to create the image from. * @param region The region of the component to be captured to an image. * @return image The image for the given region. */ public static BufferedImage createImage(JComponent component, Rectangle region) { if (!component.isDisplayable()) { Dimension dim = component.getSize(); if (dim.width == 0 || dim.height == 0) { dim = component.getPreferredSize(); component.setSize(dim); } layoutComponent(component); } BufferedImage image = new BufferedImage(region.width, region.height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); // Paint a background for non-opaque components. if (!component.isOpaque()) { g2d.setColor(component.getBackground()); g2d.fillRect(region.x, region.y, region.width, region.height); } g2d.translate(-region.x, -region.y); component.paint(g2d); g2d.dispose(); return image; } /** * Convenience method to create a BufferedImage of the desktop. * * @param fileName Name of file to be created or null. * @return image The image for the given region. * @exception AWTException * @exception IOException */ public static BufferedImage createDesktopImage() throws AWTException, IOException { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle region = new Rectangle(0, 0, dim.width, dim.height); return ScreenImage.createImage(region); } /** * Create a BufferedImage for AWT components. * * @param component AWT component to create image from * @return image the image for the given region * @exception AWTException see Robot class constructors */ public static BufferedImage createImage(Component component) throws AWTException { Point p = new Point(0, 0); SwingUtilities.convertPointToScreen(p, component); Rectangle region = component.getBounds(); region.x = p.x; region.y = p.y; return ScreenImage.createImage(region); } /** * Create a BufferedImage from a rectangular region on the screen. This will * include Swing components JFrame, JDialog and JWindow which all extend * from Component, not JComponent. * * @param Region region on the screen to create image from * @return Image the image for the given region * @exception AWTException see Robot class constructors */ public static BufferedImage createImage(Rectangle region) throws AWTException { BufferedImage image = new Robot().createScreenCapture(region); return image; } /** * Write a BufferedImage to a File. * * @param Image image to be written. * @param FileName name of file to be created. * @exception IOException if an error occurs during writing. */ public static void writeImage(BufferedImage image, String fileName) throws IOException { if (fileName == null) { return; } int offset = fileName.lastIndexOf("."); if (offset == -1) { String message = "file type was not specified"; throw new IOException(message); } String fileType = fileName.substring(offset + 1); if (imageTypes.contains(fileType)) { ImageIO.write(image, fileType, new File(fileName)); } else { String message = "unknown writer file type (" + fileType + ")"; throw new IOException(message); } } /** * A recursive layout call on the component. * * @param component Component object. */ static void layoutComponent(Component component) { synchronized (component.getTreeLock()) { component.doLayout(); if (component instanceof Container) { for (Component child : ((Container) component).getComponents()) { layoutComponent(child); } } } } }
datapoet/hubminer
src/main/java/draw/basic/ScreenImage.java
Java
gpl-3.0
7,076
--- title: "爬虫之 Scrapy 框架" layout: post date: 2018-02-24 22:48 tag: - 爬虫 blog: true author: Topaz summary: "BeautifulSoup Xpath" permalink: Spiders-Scrapy-01 --- <h1 class="title"> 爬虫之 Scrapy 框架 </h1> <h2> Table of Contents </h2> - [Scrapy 简介](#c1) - [主要组件](#c2) - [工作流程](#c3) - [安装](#c4) - [基本命令](#c5) - [HtmlXpathSelector](#c6) - [写个基于 Scrapy 的爬虫项目](#c7) - [Scrapy 自定义](#c8) <a style="color: #AED6F1" href="https://topaz1618.github.io/Spiders-Scrapy-02"> ☞ Scrapy 文件详解</a> <h2 id="c1"> Scrapy 简介 </h2> Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架,使用Twisted异步网络库处理网络通讯,爬取网站数据,提取结构性数据的应用框架,可以应用在数据挖掘,信息处理,监测和自动化测试或存储历史数据等一系列的程序中 <h2 id="c2"> 主要组件 </h2> {% highlight raw %} - 引擎(Scrapy):用来处理整个系统的数据流处理, 触发事务(框架核心) - 调度器(Scheduler):用来接受引擎发过来的请求, 压入队列中, 并在引擎再次请求的时候返回. 可以想像成一个URL(抓取网页的网址或者说是链接)的优先队列, 由它来决定下一个要抓取的网址是什么, 同时去除重复的网址 - 下载器(Downloader):用于下载网页内容, 并将网页内容返回给蜘蛛(Scrapy下载器是建立在twisted这个高效的异步模型上的) - 爬虫(Spiders):爬虫是主要干活的, 用于从特定的网页中提取自己需要的信息, 即所谓的实体(Item) 。用户也可以从中提取出链接,让Scrapy继续抓取下一个页面 - 项目管道(Pipeline):负责处理爬虫从网页中抽取的实体,主要的功能是持久化实体、验证实体的有效性、清除不需要的信息。当页面被 爬虫解析后,将被发送到项目管道,并经过几个特定的次序处理数据 - 下载器中间件(Downloader Middlewares) :位于Scrapy引擎和下载器之间的框架,主要是处理Scrapy引擎与下载器之间的请求及响应 - 爬虫中间件(Spider Middlewares):介于Scrapy引擎和爬虫之间的框架,主要工作是处理蜘蛛的响应输入和请求输出 - 调度中间件(Scheduler Middewares):介于Scrapy引擎和调度之间的中间件,从Scrapy引擎发送到调度的请求和响应 {% endhighlight %} <h2 id="c3"> 工作流程 </h2> {% highlight raw %} 1. 引擎从调度器中取出一个链接(URL)用于接下来的抓取 2. 引擎把URL封装成一个请求(Request)传给下载器 3. 下载器把资源下载下来,并封装成应答包(Response) 4. 爬虫解析Response 5. 解析出实体(Item),则交给实体管道进行进一步的处理 6. 解析出的是链接(URL),则把URL交给调度器等待抓取 {% endhighlight %} <h2 id="c4"> 安装 </h2> #### Linux & Mac {% highlight python %} pip3 install scrapy {% endhighlight %} #### Windows {% highlight python %} pip3 install wheel - 下载twisted http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted - 进入下载目录 pip3 install Twisted-17.5.0-cp35-cp35m-win_amd64.whl - 安装 scrapy pip3 install scrapy - 下载并安装pywin32 https://sourceforge.net/projects/pywin32/files/ {% endhighlight %} <h2 id="c5"> 基本命令</h2> {% highlight python %} scrapy startproject [项目名称] # 创建项目 scrapy genspider [-t template] <name> <domain> #创建爬虫应用 scrapy list #展示爬虫应用列表 scrapy crawl [爬虫应用名称] #运行单独爬虫应用 scrapy genspider -l #查看所有命令 scrapy genspider -d [模板名称] #查看模板命令 {% endhighlight %} <h2 id="c6"> HtmlXpathSelector </h2> #### 简介 HtmlXpathSelector 是 Scrapy 自有的用于处理HTML文档的选择器,被称为XPath选择器(或简称为“选择器”),是因为它们“选择”由XPath表达式指定的HTML文档的某些部分。 #### 其它选择器 - BeautifulSoup:非常流行,缺点:速度很慢 - lxml:基于 ElementTree 的XML解析库(也解析HTML ) #### 应用 {% highlight python %} from scrapy.selector import Selector, HtmlXPathSelector from scrapy.http import HtmlResponse html = """ <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <ul> <li class="item-"><a id='i12' href="link.html">first item</a></li> <li class="item-0"><a id='i2' href="llink.html">first item</a></li> <li class="item-1"><a href="llink2.html">second item<span>vv</span></a></li> </ul> <div><a href="llink2.html">second item</a></div> </body> </html> """ response = HtmlResponse(url='http://example.com', body=html,encoding='utf-8') hxs = Selector(response) #取出所有a标签 hxs = Selector(response=response).xpath('//a') #取出所有有id属性的a标签 hxs = Selector(response=response).xpath('//a[@id]') #取出开头为link的href标签 hxs = Selector(response=response).xpath('//a[starts-with(@href,"link")]' ) #取出链接包含link的href标签 hxs = Selector(response=response).xpath('//a[contains(@href, "link")]') #正则,取出i开头后边是数字的 hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]') hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]/text()').extract() hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]/@href').extract() hxs = Selector(response=response).xpath('/html/body/ul/li/a/@href').extract() hxs = Selector(response=response).xpath('//body/ul/li/a/@href').extract_first() #参考:https://doc.scrapy.org/en/0.12/topics/selectors.html {% endhighlight %} <h2 id="c7"> 写个基于 Scrapy 的爬虫项目 </h2> #### 项目结构 {% highlight raw %} cutetopaz/ scrapy.cfg #项目的主配置信息(真正爬虫相关的配置信息在settings.py文件中) cutetopaz/ __init__.py items.py #设置数据存储模板,用于结构化数据 如:Django的Model pipelines.py #数据处理行为 如:一般结构化的数据持久化 settings.py #配置文件 如:递归的层数、并发数,延迟下载等 spiders/ #爬虫目录 如:创建文件,编写爬虫规则 __init__.py xiaohuar.py #爬虫文件,一般正常人以网站域名命名 {% endhighlight %} #### xiaohuar.py {% highlight python %} import scrapy import hashlib scrapy.selector import Selector scrapy.http.request import Request scrapy.http.cookies import CookieJar scrapy import FormRequest ..items import XiaoHuarItem class XiaoHuarSpider(scrapy.Spider): name = "hira" allowed_domains = ["xiaohuar.com"] start_urls = ["http://www.xiaohuar.com/list-1-1.html",] has_request_set = {} def parse(self, response): hxs = Selector(response) items = hxs.select('//div[@class="item_list infinite_scroll"]/div') for item in items: src = item.xpath('.//div[@class="img"]/a/img/@src').extract_first() name = item.xpath('.//div[@class="img"]/span/text()').extract_first() school = item.xpath('.//div[@class="img"]/div[@class="btns"]/a/text()').extract_first() #==>广西大学 url = "http://www.xiaohuar.com%s" % src obj = XiaoHuarItem(name=name,school=school, url=url) yield obj urls = hxs.xpath('//a[re:test(@href, "http://www.xiaohuar.com/ list-1-\d+.html")]/@href').extract() #拿到所有页面 for url in urls: print("here is url:",url) key = self.md5(url) print('key!!!!!',key) if key in self.has_request_set: # print('你要的大字典',self.has_request_set) pass else: self.has_request_set[key] = url req = Request(url=url,method='GET',callback=self.parse) yield req @staticmethod def md5(val): ha = hashlib.md5() ha.update(bytes(val, encoding='utf-8')) key = ha.hexdigest() return key {% endhighlight %} #### items.py {% highlight python %} import scrapy class CutetopazItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() pass class XiaoHuarItem(scrapy.Item): name = scrapy.Field() school = scrapy.Field() url = scrapy.Field() {% endhighlight %} #### pipelines.py {% highlight python %} import json import os import requests class JsonPipeline(object): '''按照settings.py里的顺序,先执行这个''' def __init__(self): self.file = open('xiaohua.txt', 'w') def process_item(self, item, spider): v = json.dumps(dict(item), ensure_ascii=False) #item ==> <class 'cutetopaz.items.XiaoHuarItem'> dict(item) ==> <class 'dict'> ,肉眼看的话item就是个字典啊,去掉dict()报错is not JSON serializable self.file.write(v) self.file.write('\n') self.file.flush() return item #返回一个json序列化后的item class FilePipeline(object): def __init__(self): if not os.path.exists('imgs'): #创建个文件夹 os.makedirs('imgs') def process_item(self, item, spider): response = requests.get(item['url'], stream=True) print('看看',response.__attrs__) file_name = '%s_%s.jpg' % (item['name'], item['school']) with open(os.path.join('imgs', file_name), mode='wb') as f: f.write(response.content) return item {% endhighlight %} #### settings.py {% highlight python %} ITEM_PIPELINES = { 'cutetopaz.pipelines.JsonPipeline': 100, 'cutetopaz.pipelines.FilePipeline': 300, } {% endhighlight %} <h2 id="c8"> Scrapy 自定义 </h2> #### 自定制命令 {% highlight raw %} 1.在spiders同级创建任意目录,如:commands 2.在其中创建 crawlall.py 文件 (此处文件名就是自定义的命令) 3.settings.py 中添加配置 COMMANDS_MODULE = '项目名称.目录名称' 4.项目目录中执行命令:scrapy crawlall {% endhighlight %} 代码: {% highlight python %} from scrapy.commands import ScrapyCommand from scrapy.utils.project import get_project_settings class Command(ScrapyCommand): requires_project = True def syntax(self): return '[options]' def short_desc(self): return 'Runs all of the spiders' def run(self, args, opts): spider_list = self.crawler_process.spiders.list() for name in spider_list: self.crawler_process.crawl(name, **opts.__dict__) self.crawler_process.start() {% endhighlight %} #### 自定义扩展 自定义扩展时,利用信号在指定位置注册制定操作 {% highlight python %} from scrapy import signals class MyExtension(object): def __init__(self, value): self.value = value @classmethod def from_crawler(cls, crawler): val = crawler.settings.getint('MMMM') ext = cls(val) crawler.signals.connect(ext.spider_opened, signal=signals.spider_opened) crawler.signals.connect(ext.spider_closed, signal=signals.spider_closed) return ext def spider_opened(self, spider): print('open') def spider_closed(self, spider): print('close') {% endhighlight %} #### 避免重复访问 Scrapy 默认使用 scrapy.dupefilter.RFPDupeFilter 进行去重,相关配置有 {% highlight raw %} DUPEFILTER_CLASS = 'scrapy.dupefilter.RFPDupeFilter' DUPEFILTER_DEBUG = False JOBDIR = "保存范文记录的日志路径,如:/root/" # 最终路径为 /root/requests.seen {% endhighlight %}
Topaz1618/Topaz1618.github.io
_posts/2018-06-10-Spiders-Scrapy-01.markdown
Markdown
gpl-3.0
11,350
@extends('admin.layout') @section('styles') <link href="/assets/css/pdfexport.css" rel="stylesheet"> @stop @section('content') <div class="container"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <p><a href="{{ url('admin/stavkeposla/show',[$evidencija->id]) }}" class="btn btn-warning pull-right"><i class="fa fa-arrow-circle-left"></i> Natrag</a></p> <h4>Pregled stavke ponude</h4> </div> <div class="panel-body"> <div class="col-md-4 col-md-offset-5"> <button class="btn btn-primary" id="create_pdf"><i class="fa fa-file-pdf-o" aria-hidden="true"></i> Pretvori u PDF</button> </div> </div> </div> </div> </div> <page size="A4"> <div id="target"> <div class="row"> <div class="col-xs-12"> <div class="row top-head"> <div class="col-xs-3 head-left"> <img src="/assets/images/lukic-logo.png" alt="Waterrproofing co"> <h2>Mob. 098 111 222</h2> </div> <div class="col-xs-6 head-center"> <address> <h1>WATERPROOFING CO</h1> <h2>Zagreb <span>Ilica BB</span></h2> <h2>OIB:72818256208</h2> <h2><span>Žiro račun:</span> IBAN HR78948499611050015727</h2> </address> </div> <div class="col-xs-3 head-right"> <img src="/assets/images/lukic-logo.png" alt="Waterrproofing co"> <h2>Tel fax 01 111 22 33</h2> </div> </div><!--top-head--> <hr> <div class="row top-adddress"> <div class="col-xs-6 head-adddress-left"> <p>Mjesto rada: {{ $evidencija->narucitelj_adresa }} </p> </div> <div class="col-xs-6 head-adddress-right"> <address class="pull-right"> <p><strong>{{ $evidencija->mjesto_rada }}</strong></p> <p><strong>{{ $evidencija->narucitelj_adresa }}</strong></p> <p><strong>OIB: {{ $evidencija->narucitelj_oib }}</strong></p> </address> </div> </div><!--top-adddress--> <div class="row invoice"> <div class="col-xs-12"> <h3>STAVKA PONUDE BR: 0{{ $evidencija->id }}.{{ $evidencija->created_at->format('my') }}-1</h3> </div> </div><!--invoice--> <div class="row stavke"> <div class="col-xs-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><strong>Stavka br: {{ $stavka->broj_stavke }}</strong></h3> <p><strong>Opis radova:</strong> {{ $stavka->opis_radova }}</p> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table table-condensed stavkamaterijal"> <thead> <tr> <th>Naziv materijala</th> <th>Mjerna jedinica</th> <th>Cijena materijala</th> <th>Potrošnja</th> <th>Materijal</th> <th>Kalkul sat</th> <th>Norma sat</th> <th>Rad</th> <th>Cijena po jm.</th> <th>Ucinak m2 sat</th> </tr> </thead> <tbody> @foreach($stavkeposlovi as $pm) <!-- foreach ($order->lineItems as $line) or some such thing here --> <tr> <td>{{ $pm->naziv_materijala }}</td> <td>{{ $pm->mjerna_jedinica }}</td> <td>{{ $pm->cijena_sa_popustom }}</td> <td>{{ $pm->potrosnja_mat }}</td> <td>{{ $pm->materijal }}</td> <td>{{ $pm->kalkul_sat }}</td> <td>{{ $pm->norma_sat }}</td> <td>{{ $pm->rad }}</td> <td>{{ $pm->cijena_po_jm }}</td> <td>{{ $pm->ucinak_m2_sat }}</td> </tr> @endforeach <tr> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line text-left"><strong>Cijena posla:</strong></td> <td class="no-line text-right">{{ $stavka->cijena_posla }} - kn</td> </tr> <tr> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line text-left"><strong>Ukupna cijena:</strong></td> <td class="no-line text-right">{{ $stavka->ukupna_cijena }} - kn</td> </tr> </tbody> </table> </div> </div> </div> <div class="row"> <div class="col-xs-12"> <div class="col-xs-7"> <p>Obračun prema stvarnim količinama.</p> <p>{{ date('d.m.Y') }}</p> </div> <div class="col-xs-4"> <div class="pull-right"> <p class="line"><strong>Direktor</strong></p> <p class="no-line"><strong>Ivica Ivić</strong></p> </div> </div> <div class="col-xs-1"></div> </div> </div> </div> </div><!--/.stavke--> <div class="row end"> </div><!--end--> </div><!--col-xs-12--> </div><!--row--> </div> </page> @stop @section('scripts') <script src="/assets/js/jspdf.min.js"></script> <script src="http://mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script> <script type="text/javascript" src="//cdn.rawgit.com/niklasvh/html2canvas/0.5.0-alpha2/dist/html2canvas.min.js"></script> <script type="text/javascript"> (function(){ var target = $('#target'), cache_width = target.width(), a4 =[ 595.28, 841.89]; // for a4 size paper width and height $('#create_pdf').on('click',function(){ $('#target').scrollTop(0); createPDF(); }); //create pdf function createPDF(){ getCanvas().then(function(canvas){ var img = canvas.toDataURL("image/png"), doc = new jsPDF({ unit:'px', format:'a4' }); doc.addImage(img, 'JPEG', 20, 20); doc.save('ponuda.pdf'); target.width(cache_width); }); } // create canvas object function getCanvas(){ target.width((a4[0]*1.33333) -60).css('max-width','none'); return html2canvas(target,{ imageTimeout:2000, removeContainer:true }); } }()); </script> @stop
DraganValjak/WaterrproofingApp-Laravel5
resources/views/admin/pdfponude/stavkamaterijal.blade.php
PHP
gpl-3.0
10,356
/* * Copyright (C) 2015 Bailey Forrest <[email protected]> * * This file is part of CCC. * * CCC 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. * * CCC 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 CCC. If not, see <http://www.gnu.org/licenses/>. */ /** * Interface for compliation manager */ #ifndef _MANAGER_H_ #define _MANAGER_H_ #include "ast/ast.h" #include "ir/ir.h" #include "lex/lex.h" #include "lex/symtab.h" #include "util/status.h" /** * Compilation manager structure. Manages data structures necessary for compiles */ typedef struct manager_t { vec_t tokens; symtab_t symtab; lexer_t lexer; token_man_t token_man; fmark_man_t mark_man; trans_unit_t *ast; ir_trans_unit_t *ir; bool parse_destroyed; } manager_t; /** * Initialize a compilation mananger * * @param manager The compilation mananger to initialize */ void man_init(manager_t *manager); /** * Destroy a compilation mananger * * @param manager The compilation mananger to destroy */ void man_destroy(manager_t *manager); /** * Destroy a compilation mananger parsing data structures * * Calling this is optional because destructor destroys these. May be used to * reduce memory usage however. * * @param manager The compilation mananger to destroy ast */ void man_destroy_parse(manager_t *manager); /** * Destroy a compilation mananger's ir * * Calling this is optional because destructor destroys ir. May be used to * reduce memory usage however. * * @param manager The compilation mananger to destroy ir */ void man_destroy_ir(manager_t *manager); status_t man_lex(manager_t *manager, char *filepath); /** * Parse a translation unit from a compilation manager. * * The manager's preprocessor must be set up first * * @param manager The compilation mananger to parse * @param filepath Path to file to parse * @param ast The parsed ast * @return CCC_OK on success, error code on error. */ status_t man_parse(manager_t *manager, trans_unit_t **ast); /** * Parse an expression from a compilation manager. * * The manager's preprocessor must be set up first * * @param manager The compilation mananger to parse * @param expr The parsed expression * @return CCC_OK on success, error code on error. */ status_t man_parse_expr(manager_t *manager, expr_t **expr); /** * Translate the ast in a manager * * The manager must have a vaild ast from man_parse * * @param manager The compilation mananger to use * @return Returns the ir tree */ ir_trans_unit_t *man_translate(manager_t *manager); /** * Print the tokens from a compilation manager * * The manager's preprocessor must be set up first * * @param manager The compilation mananger to use * @return CCC_OK on success, error code on error. */ status_t man_dump_tokens(manager_t *manager); #endif /* _MANAGER_H_ */
bcforres/ccc
src/top/manager.h
C
gpl-3.0
3,307
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model common\models\Sparesused */ $this->title = 'Create Sparesused'; $this->params['breadcrumbs'][] = ['label' => 'Sparesuseds', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="sparesused-create"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
sudeeptalati/rapportforindependentengineers
rapport-chs-mobile/frontend/views/sparesused/create.php
PHP
gpl-3.0
431
{% extends "base_nav.html" %} {% load humanize %} {% load i18n %} {% load staticfiles %} {% block "title" %}{% trans "Review Access Request" %}{% endblock %} {% block "css" %} <link href="{% static 'css/secrets.css' %}" rel="stylesheet"> {% endblock %} {% block "content" %} <script type="text/javascript"> $(function () { $("[data-toggle='tooltip']").tooltip({container: 'body'}); }); </script> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>{% trans "Review Access Request" %}</h1> <br> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="secret-attributes panel"> <br> <table class="table-responsive"> <tr> <td>{% trans "Requester" %}</td> <td> {{ access_request.requester }} </td> </tr> <tr> <td>{% trans "Secret" %}</td> <td> <a href="{{ access_request.secret.get_absolute_url }}">{{ access_request.secret.name }}</a> </td> </tr> <tr> <td>{% trans "Requested" %}</td> <td> <span data-toggle="tooltip" data-placement="top" title="{{ access_request.created|date:"Y-m-d H:i:s" }}"> {{ access_request.created|naturalday:"Y-m-d" }} </span> </td> </tr> {% if access_request.reason_request %} <tr> <td>{% trans "Reason" %}</td> <td> {{ access_request.reason_request }} </td> </tr> {% endif %} </table> <br> </div> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form role="form" method="POST" action="{% url "secrets.access_request-review" hashid=access_request.hashid action="deny" %}"> {% csrf_token %} <input type="text" class="form-control input-lg" name="reason" placeholder="{% trans "Reason for turning down the request (optional)" %}"> <br> <button type="submit" class="btn btn-danger btn-lg pull-left"> &nbsp; &nbsp; &nbsp; <i class="fa fa-thumbs-down"></i>&nbsp; {% trans "Deny access" %} &nbsp; &nbsp; &nbsp; </button> </form> <form role="form" method="POST" action="{% url "secrets.access_request-review" hashid=access_request.hashid action="allow" %}"> {% csrf_token %} <button type="submit" class="btn btn-success btn-lg pull-right"> &nbsp; &nbsp; &nbsp; <i class="fa fa-thumbs-up"></i>&nbsp; {% trans "Allow access" %} &nbsp; &nbsp; &nbsp; </button> </form> </div> </div> </div> {% endblock %}
drscream/teamvault
src/teamvault/apps/secrets/templates/secrets/accessrequest_detail.html
HTML
gpl-3.0
2,467
#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: main() if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1)
braynebuddy/PyBrayne
act_twitter.py
Python
gpl-3.0
3,157
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - SALTMARSH, Nellie</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> <link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../families.html" title="Families">Families</a></li> <li><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="IndividualDetail"> <h3>SALTMARSH, Nellie<sup><small></small></sup></h3> <div id="summaryarea"> <table class="infolist"> <tr> <td class="ColumnAttribute">Birth Name</td> <td class="ColumnValue"> SALTMARSH, Nellie </td> </tr> <tr> <td class="ColumnAttribute">Gramps&nbsp;ID</td> <td class="ColumnValue">I3011</td> </tr> <tr> <td class="ColumnAttribute">Gender</td> <td class="ColumnValue">female</td> </tr> <tr> <td class="ColumnAttribute">Age at Death</td> <td class="ColumnValue">72 years, 7 months, 30 days</td> </tr> </table> </div> <div class="subsection" id="events"> <h4>Events</h4> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> <a href="../../../evt/2/9/d15f5fdfc737c6ae020b165a92.html" title="Birth"> Birth <span class="grampsid"> [E3288]</span> </a> </td> <td class="ColumnDate">1875-05-02</td> <td class="ColumnPlace"> <a href="../../../plc/c/4/d15f5fb92e843882bcabe3e6e4c.html" title=""> </a> </td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> <tr> <td class="ColumnEvent"> <a href="../../../evt/1/2/d15f5fdfc7d2cb5bb6e4db0aa21.html" title="Death"> Death <span class="grampsid"> [E3289]</span> </a> </td> <td class="ColumnDate">1948</td> <td class="ColumnPlace"> <a href="../../../plc/1/d/d15f5fdfc80455f1da835d10d1.html" title=""> </a> </td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </div> <div class="subsection" id="parents"> <h4>Parents</h4> <table class="infolist"> <thead> <tr> <th class="ColumnAttribute">Relation to main person</th> <th class="ColumnValue">Name</th> <th class="ColumnValue">Relation within this family (if not by birth)</th> </tr> </thead> <tbody> </tbody> <tr> <td class="ColumnAttribute">Father</td> <td class="ColumnValue"> <a href="../../../ppl/e/5/d15f5fde9511e3067925f537c5e.html">SALTMARSH, Richard<span class="grampsid"> [I2916]</span></a> </td> </tr> <tr> <td class="ColumnAttribute">Mother</td> <td class="ColumnValue"> <a href="../../../ppl/b/6/d15f5fdfa0c318cef314f61c96b.html">DYER, Elizabeth<span class="grampsid"> [I2998]</span></a> </td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/c/9/d15f5fdfa2844c2b56a5686d19c.html">SALTMARSH, Elizabeth<span class="grampsid"> [I2999]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/b/4/d15f5fdfa4e48dce8bbcbeedf4b.html">SALTMARSH, Richard<span class="grampsid"> [I3000]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/f/a/d15f5fdfa92337411784f7a40af.html">SALTMARSH, Sarah<span class="grampsid"> [I3001]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/4/4/d15f5fdfabb4cd317d555aa9644.html">SALTMARSH, Annie<span class="grampsid"> [I3002]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/d/3/d15f5fdfadc673a028570d3303d.html">SALTMARSH, Fanny<span class="grampsid"> [I3003]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/b/5/d15f5fdfb11159d19acff5c205b.html">SALTMARSH, Dinah<span class="grampsid"> [I3004]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/8/2/d15f5fdfb454eceb98fec921e28.html">SALTMARSH, Laura Sarah<span class="grampsid"> [I3005]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/1/1/d15f5fdfb674ec8396cde6ae911.html">SALTMARSH, Joseph<span class="grampsid"> [I3006]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/d/e/d15f5fdfb866c91391ac0aec8ed.html">SALTMARSH, Arthur<span class="grampsid"> [I3007]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/9/3/d15f5fdfbec2053f1d4c3bd7c39.html">SALTMARSH, Emily<span class="grampsid"> [I3008]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/d/8/d15f5fdfc1d3c32c960346d388d.html">SALTMARSH, John<span class="grampsid"> [I3009]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/b/b/d15f5fdfc3e3113bc7dca41b4bb.html">SALTMARSH, Charlotte<span class="grampsid"> [I3010]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/9/3/d15f5fdfc6f1c1b003779b54739.html">SALTMARSH, Nellie<span class="grampsid"> [I3011]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Sister</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/b/2/d15f5fdfca4389f740f1857e02b.html">SALTMARSH, Florence<span class="grampsid"> [I3012]</span></a></td> <td class="ColumnValue"></td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;Brother</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/1/b/d15f5fdfcc6c1c2b1026d4a6b1.html">SALTMARSH, William<span class="grampsid"> [I3013]</span></a></td> <td class="ColumnValue"></td> </tr> </table> </div> <div class="subsection" id="families"> <h4>Families</h4> <table class="infolist"> <tr class="BeginFamily"> <td class="ColumnType">&nbsp</td> <td class="ColumnAttribute">&nbsp</td> <td class="ColumnValue"><a href="../../../fam/4/c/d15f5fdfc9867118ce73148f4c4.html" title="Family of OGILVIE, John and SALTMARSH, Nellie">Family of OGILVIE, John and SALTMARSH, Nellie<span class="grampsid"> [F6404]</span></a></td> </tr> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Husband</td> <td class="ColumnValue"> <a href="../../../ppl/7/3/d15f60a2363420ed3fb6201ac37.html">OGILVIE, John<span class="grampsid"> [I18668]</span></a> </td> </tr> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">&nbsp;</td> <td class="ColumnValue"> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> <a href="../../../evt/a/b/d15f60e15b35b46d4260945aba.html" title="Marriage"> Marriage <span class="grampsid"> [E26432]</span> </a> </td> <td class="ColumnDate">1918-07-10</td> <td class="ColumnPlace"> <a href="../../../plc/8/f/d15f60e15bc16afb84461bc9bf8.html" title=""> </a> </td> <td class="ColumnDescription">&nbsp;</td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> <a href="#sref1a">1a</a> </td> </tr> </tbody> </table> </td> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">Attributes</td> <td class="ColumnValue"> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">70B154F442C634468BD1883D388376FD3A35</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </td> </tr> </tr> </table> </div> <div class="subsection" id="attributes"> <h4>Attributes</h4> <table class="infolist attrlist"> <thead> <tr> <th class="ColumnType">Type</th> <th class="ColumnValue">Value</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnType">_UID</td> <td class="ColumnValue">EB539E2A33426F4CA6DF9FA0688D30C5E41E</td> <td class="ColumnNotes"><div></div></td> <td class="ColumnSources">&nbsp;</td> </tr> </tbody> </table> </div> <div class="subsection" id="pedigree"> <h4>Pedigree</h4> <ol class="pedigreegen"> <li> <a href="../../../ppl/e/5/d15f5fde9511e3067925f537c5e.html">SALTMARSH, Richard<span class="grampsid"> [I2916]</span></a> <ol> <li class="spouse"> <a href="../../../ppl/b/6/d15f5fdfa0c318cef314f61c96b.html">DYER, Elizabeth<span class="grampsid"> [I2998]</span></a> <ol> <li> <a href="../../../ppl/c/9/d15f5fdfa2844c2b56a5686d19c.html">SALTMARSH, Elizabeth<span class="grampsid"> [I2999]</span></a> </li> <li> <a href="../../../ppl/b/4/d15f5fdfa4e48dce8bbcbeedf4b.html">SALTMARSH, Richard<span class="grampsid"> [I3000]</span></a> </li> <li> <a href="../../../ppl/f/a/d15f5fdfa92337411784f7a40af.html">SALTMARSH, Sarah<span class="grampsid"> [I3001]</span></a> </li> <li> <a href="../../../ppl/4/4/d15f5fdfabb4cd317d555aa9644.html">SALTMARSH, Annie<span class="grampsid"> [I3002]</span></a> </li> <li> <a href="../../../ppl/d/3/d15f5fdfadc673a028570d3303d.html">SALTMARSH, Fanny<span class="grampsid"> [I3003]</span></a> </li> <li> <a href="../../../ppl/8/2/d15f5fdfb454eceb98fec921e28.html">SALTMARSH, Laura Sarah<span class="grampsid"> [I3005]</span></a> </li> <li> <a href="../../../ppl/b/5/d15f5fdfb11159d19acff5c205b.html">SALTMARSH, Dinah<span class="grampsid"> [I3004]</span></a> </li> <li> <a href="../../../ppl/1/1/d15f5fdfb674ec8396cde6ae911.html">SALTMARSH, Joseph<span class="grampsid"> [I3006]</span></a> </li> <li> <a href="../../../ppl/d/e/d15f5fdfb866c91391ac0aec8ed.html">SALTMARSH, Arthur<span class="grampsid"> [I3007]</span></a> </li> <li> <a href="../../../ppl/9/3/d15f5fdfbec2053f1d4c3bd7c39.html">SALTMARSH, Emily<span class="grampsid"> [I3008]</span></a> </li> <li> <a href="../../../ppl/d/8/d15f5fdfc1d3c32c960346d388d.html">SALTMARSH, John<span class="grampsid"> [I3009]</span></a> </li> <li> <a href="../../../ppl/b/b/d15f5fdfc3e3113bc7dca41b4bb.html">SALTMARSH, Charlotte<span class="grampsid"> [I3010]</span></a> </li> <li class="thisperson"> SALTMARSH, Nellie <ol class="spouselist"> <li class="spouse"> <a href="../../../ppl/7/3/d15f60a2363420ed3fb6201ac37.html">OGILVIE, John<span class="grampsid"> [I18668]</span></a> </li> </ol> </li> <li> <a href="../../../ppl/b/2/d15f5fdfca4389f740f1857e02b.html">SALTMARSH, Florence<span class="grampsid"> [I3012]</span></a> </li> <li> <a href="../../../ppl/1/b/d15f5fdfcc6c1c2b1026d4a6b1.html">SALTMARSH, William<span class="grampsid"> [I3013]</span></a> </li> </ol> </li> </ol> </li> </ol> </div> <div class="subsection" id="tree"> <h4>Ancestors</h4> <div id="treeContainer" style="width:735px; height:602px;"> <div class="boxbg female AncCol0" style="top: 269px; left: 6px;"> <a class="noThumb" href="../../../ppl/9/3/d15f5fdfc6f1c1b003779b54739.html"> SALTMARSH, Nellie </a> </div> <div class="shadow" style="top: 274px; left: 10px;"></div> <div class="bvline" style="top: 301px; left: 165px; width: 15px"></div> <div class="gvline" style="top: 306px; left: 165px; width: 20px"></div> <div class="boxbg male AncCol1" style="top: 119px; left: 196px;"> <a class="noThumb" href="../../../ppl/e/5/d15f5fde9511e3067925f537c5e.html"> SALTMARSH, Richard </a> </div> <div class="shadow" style="top: 124px; left: 200px;"></div> <div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div> <div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div> <div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div> <div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div> <div class="bvline" style="top: 151px; left: 355px; width: 15px"></div> <div class="gvline" style="top: 156px; left: 355px; width: 20px"></div> <div class="boxbg male AncCol2" style="top: 44px; left: 386px;"> <a class="noThumb" href="../../../ppl/7/0/d15f5fb93c47b8feec7c96fd107.html"> SALTMARSH, William </a> </div> <div class="shadow" style="top: 49px; left: 390px;"></div> <div class="bvline" style="top: 76px; left: 370px; width: 15px;"></div> <div class="gvline" style="top: 81px; left: 375px; width: 20px;"></div> <div class="bhline" style="top: 76px; left: 370px; height: 75px;"></div> <div class="gvline" style="top: 81px; left: 375px; height: 75px;"></div> <div class="bvline" style="top: 76px; left: 545px; width: 15px"></div> <div class="gvline" style="top: 81px; left: 545px; width: 20px"></div> <div class="boxbg male AncCol3" style="top: 7px; left: 576px;"> <a class="noThumb" href="../../../ppl/b/5/d15f5fb94714b44224670d12b5b.html"> SALTMARSH, William </a> </div> <div class="shadow" style="top: 12px; left: 580px;"></div> <div class="bvline" style="top: 39px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 44px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 39px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 44px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol3" style="top: 81px; left: 576px;"> <a class="noThumb" href="../../../ppl/7/c/d15f5fb94b631e50cfe6f4e3fc7.html"> BUTLER, Mary </a> </div> <div class="shadow" style="top: 86px; left: 580px;"></div> <div class="bvline" style="top: 113px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 118px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 76px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 81px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol2" style="top: 194px; left: 386px;"> <a class="noThumb" href="../../../ppl/3/c/d15f5fb940b58ef52b9ce85adc3.html"> STEVENS, Elizabeth </a> </div> <div class="shadow" style="top: 199px; left: 390px;"></div> <div class="bvline" style="top: 226px; left: 370px; width: 15px;"></div> <div class="gvline" style="top: 231px; left: 375px; width: 20px;"></div> <div class="bhline" style="top: 151px; left: 370px; height: 75px;"></div> <div class="gvline" style="top: 156px; left: 375px; height: 75px;"></div> <div class="bvline" style="top: 226px; left: 545px; width: 15px"></div> <div class="gvline" style="top: 231px; left: 545px; width: 20px"></div> <div class="boxbg male AncCol3" style="top: 157px; left: 576px;"> <a class="noThumb" href="../../../ppl/7/3/d15f5fde7e7679ecf3079f2dd37.html"> STEVENS, Thomas </a> </div> <div class="shadow" style="top: 162px; left: 580px;"></div> <div class="bvline" style="top: 189px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 194px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 189px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 194px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol3" style="top: 231px; left: 576px;"> <a class="noThumb" href="../../../ppl/2/c/d15f5fde8121285d992e96c3c2.html"> PHILLIPS, Mary </a> </div> <div class="shadow" style="top: 236px; left: 580px;"></div> <div class="bvline" style="top: 263px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 268px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 226px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 231px; left: 565px; height: 37px;"></div> <div class="boxbg female AncCol1" style="top: 419px; left: 196px;"> <a class="noThumb" href="../../../ppl/b/6/d15f5fdfa0c318cef314f61c96b.html"> DYER, Elizabeth </a> </div> <div class="shadow" style="top: 424px; left: 200px;"></div> <div class="bvline" style="top: 451px; left: 180px; width: 15px;"></div> <div class="gvline" style="top: 456px; left: 185px; width: 20px;"></div> <div class="bhline" style="top: 301px; left: 180px; height: 150px;"></div> <div class="gvline" style="top: 306px; left: 185px; height: 150px;"></div> </div> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/9/4/d15f60a23683e37d4ae44106449.html" title="Neroli Ferguson Email 21 November 2007" name ="sref1"> Neroli Ferguson Email 21 November 2007 <span class="grampsid"> [S0409]</span> </a> <ol> <li id="sref1a"> <ul> <li> Confidence: Low </li> </ul> </li> </ol> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:13<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
RossGammon/the-gammons.net
RossFamilyTree/ppl/9/3/d15f5fdfc6f1c1b003779b54739.html
HTML
gpl-3.0
22,047
/***************************************************************************** * Copyright (c) 2014-2020 OpenRCT2 developers * * For a complete list of all authors, please refer to contributors.md * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 * * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ #include "../../common.h" #include "../../interface/Viewport.h" #include "../../paint/Paint.h" #include "../../paint/Supports.h" #include "../../world/Entity.h" #include "../Track.h" #include "../TrackPaint.h" #include "../Vehicle.h" /** rct2: 0x0076E5C9 */ static void paint_twist_structure( paint_session* session, const Ride* ride, uint8_t direction, int8_t xOffset, int8_t yOffset, uint16_t height) { const TileElement* savedTileElement = static_cast<const TileElement*>(session->CurrentlyDrawnItem); rct_ride_entry* rideEntry = get_ride_entry(ride->subtype); Vehicle* vehicle = nullptr; if (rideEntry == nullptr) { return; } height += 7; uint32_t baseImageId = rideEntry->vehicles[0].base_image_id; if (ride->lifecycle_flags & RIDE_LIFECYCLE_ON_TRACK && ride->vehicles[0] != SPRITE_INDEX_NULL) { vehicle = GetEntity<Vehicle>(ride->vehicles[0]); session->InteractionType = ViewportInteractionItem::Entity; session->CurrentlyDrawnItem = vehicle; } uint32_t frameNum = (direction * 88) % 216; if (vehicle != nullptr) { frameNum += (vehicle->sprite_direction >> 3) << 4; frameNum += vehicle->Pitch; frameNum = frameNum % 216; } uint32_t imageColourFlags = session->TrackColours[SCHEME_MISC]; if (imageColourFlags == IMAGE_TYPE_REMAP) { imageColourFlags = SPRITE_ID_PALETTE_COLOUR_2(ride->vehicle_colours[0].Body, ride->vehicle_colours[0].Trim); } uint32_t structureFrameNum = frameNum % 24; uint32_t imageId = (baseImageId + structureFrameNum) | imageColourFlags; PaintAddImageAsParent( session, imageId, { xOffset, yOffset, height }, { 24, 24, 48 }, { xOffset + 16, yOffset + 16, height }); rct_drawpixelinfo* dpi = &session->DPI; if (dpi->zoom_level < 1 && ride->lifecycle_flags & RIDE_LIFECYCLE_ON_TRACK && vehicle != nullptr) { for (int32_t i = 0; i < vehicle->num_peeps; i += 2) { imageColourFlags = SPRITE_ID_PALETTE_COLOUR_2(vehicle->peep_tshirt_colours[i], vehicle->peep_tshirt_colours[i + 1]); uint32_t peepFrameNum = (frameNum + i * 12) % 216; imageId = (baseImageId + 24 + peepFrameNum) | imageColourFlags; PaintAddImageAsChild(session, imageId, xOffset, yOffset, 24, 24, 48, height, xOffset + 16, yOffset + 16, height); } } session->CurrentlyDrawnItem = savedTileElement; session->InteractionType = ViewportInteractionItem::Ride; } /** rct2: 0x0076D858 */ static void paint_twist( paint_session* session, const Ride* ride, uint8_t trackSequence, uint8_t direction, int32_t height, const TrackElement& trackElement) { if (ride == nullptr) return; trackSequence = track_map_3x3[direction][trackSequence]; const uint8_t edges = edges_3x3[trackSequence]; uint32_t imageId; wooden_a_supports_paint_setup(session, (direction & 1), 0, height, session->TrackColours[SCHEME_MISC]); StationObject* stationObject = ride_get_station_object(ride); track_paint_util_paint_floor(session, edges, session->TrackColours[SCHEME_MISC], height, floorSpritesCork, stationObject); switch (trackSequence) { case 7: if (track_paint_util_has_fence(EDGE_SW, session->MapPosition, trackElement, ride, session->CurrentRotation)) { imageId = SPR_FENCE_ROPE_SW | session->TrackColours[SCHEME_MISC]; PaintAddImageAsParent(session, imageId, { 0, 0, height }, { 1, 28, 7 }, { 29, 0, height + 3 }); } if (track_paint_util_has_fence(EDGE_SE, session->MapPosition, trackElement, ride, session->CurrentRotation)) { imageId = SPR_FENCE_ROPE_SE | session->TrackColours[SCHEME_MISC]; PaintAddImageAsParent(session, imageId, { 0, 0, height }, { 28, 1, 7 }, { 0, 29, height + 3 }); } break; default: track_paint_util_paint_fences( session, edges, session->MapPosition, trackElement, ride, session->TrackColours[SCHEME_MISC], height, fenceSpritesRope, session->CurrentRotation); break; } switch (trackSequence) { case 1: paint_twist_structure(session, ride, direction, 32, 32, height); break; case 3: paint_twist_structure(session, ride, direction, 32, -32, height); break; case 5: paint_twist_structure(session, ride, direction, 0, -32, height); break; case 6: paint_twist_structure(session, ride, direction, -32, 32, height); break; case 7: paint_twist_structure(session, ride, direction, -32, -32, height); break; case 8: paint_twist_structure(session, ride, direction, -32, 0, height); break; } int32_t cornerSegments = 0; switch (trackSequence) { case 1: cornerSegments = SEGMENT_B4 | SEGMENT_C8 | SEGMENT_CC; break; case 3: cornerSegments = SEGMENT_CC | SEGMENT_BC | SEGMENT_D4; break; case 6: cornerSegments = SEGMENT_C8 | SEGMENT_B8 | SEGMENT_D0; break; case 7: cornerSegments = SEGMENT_D0 | SEGMENT_C0 | SEGMENT_D4; break; } paint_util_set_segment_support_height(session, cornerSegments, height + 2, 0x20); paint_util_set_segment_support_height(session, SEGMENTS_ALL & ~cornerSegments, 0xFFFF, 0); paint_util_set_general_support_height(session, height + 64, 0x20); } /** * rct2: 0x0076D658 */ TRACK_PAINT_FUNCTION get_track_paint_function_twist(int32_t trackType) { if (trackType != TrackElemType::FlatTrack3x3) { return nullptr; } return paint_twist; }
LRFLEW/OpenRCT2
src/openrct2/ride/thrill/Twist.cpp
C++
gpl-3.0
6,309
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Created by texi2html, http://www.gnu.org/software/texinfo/ --> <head> <title>Singular 2-0-4 Manual: D.5.8.6 is_reg</title> <meta name="description" content="Singular 2-0-4 Manual: D.5.8.6 is_reg"> <meta name="keywords" content="Singular 2-0-4 Manual: D.5.8.6 is_reg"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="texi2html"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> <!-- @import "sing_tex4ht_tex.css"; a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} pre.display {font-family: serif} pre.format {font-family: serif} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: serif; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: serif; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:pre} span.nolinebreak {white-space:pre} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} --> </style> </head> <body lang="en" background="../singular_images/Mybg.png"> <a name="is_005freg"></a> <table border="0" cellpadding="0" cellspacing="0"> <tr valign="top"> <td align="left"> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr valign="top" align="left"> <td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/singular-icon-transparent.png" width="50" border="0" alt="Top"></a> </td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="is_005fis.html#is_005fis" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.5.8.5 is_is" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="is_005fregs.html#is_005fregs" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.5.8.7 is_regs" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_005flib.html#sing_005flib" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.5.8 sing_lib" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr> </table> </td> <td align="left"> <a name="is_005freg-1"></a> <h4 class="subsubsection">D.5.8.6 is_reg</h4> <a name="index-is_005freg"></a> <p>Procedure from library <code>sing.lib</code> (see <a href="sing_005flib.html#sing_005flib">sing_lib</a>). </p> <dl compact="compact"> <dt><strong>Usage:</strong></dt> <dd><p>is_reg(f,id); f poly, id ideal or module </p> </dd> <dt><strong>Return:</strong></dt> <dd><p>1 if multiplication with f is injective modulo id, 0 otherwise </p> </dd> <dt><strong>Note:</strong></dt> <dd><p>let R be the basering and id a submodule of R^n. The procedure checks injectivity of multiplication with f on R^n/id. The basering may be a quotient ring </p> </dd> </dl> <p><strong>Example:</strong> </p><div class="smallexample"> <pre class="smallexample">LIB &quot;sing.lib&quot;; ring r = 32003,(x,y),ds; ideal i = x8,y8; ideal j = (x+y)^4; i = intersect(i,j); poly f = xy; is_reg(f,i); &rarr; 0 </pre></div> </td> </tr> </table> <hr> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/singular-icon-transparent.png" width="50" border="0" alt="Top"></a> </td> <td valign="middle" align="left"><a href="is_005fis.html#is_005fis" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.5.8.5 is_is" align="middle"></a></td> <td valign="middle" align="left"><a href="is_005fregs.html#is_005fregs" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.5.8.7 is_regs" align="middle"></a></td> <td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td> <td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_005flib.html#sing_005flib" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.5.8 sing_lib" align="middle"></a></td> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr></table> <font size="-1"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; User manual for <a href="http://www.singular.uni-kl.de/"><i>Singular</i></a> version 2-0-4, October 2002, generated by <a href="http://www.gnu.org/software/texinfo/"><i>texi2html</i></a>. </font> </body> </html>
cgwalters/texinfo-git-mirror
texi2html/test/singular_manual/res/singular_httex/is_005freg.html
HTML
gpl-3.0
7,548
use vars qw(%result_texis %result_texts %result_trees %result_errors %result_indices %result_sectioning %result_nodes %result_menus %result_floats %result_converted %result_converted_errors %result_elements %result_directions_text); use utf8; $result_trees{'top_node_normalization'} = { 'contents' => [ { 'contents' => [], 'parent' => {}, 'type' => 'text_root' }, { 'args' => [ { 'contents' => [ { 'extra' => { 'command' => {} }, 'parent' => {}, 'text' => ' ', 'type' => 'empty_spaces_after_command' }, { 'parent' => {}, 'text' => 'ToP' }, { 'parent' => {}, 'text' => ' ', 'type' => 'spaces_at_end' } ], 'parent' => {}, 'type' => 'misc_line_arg' } ], 'cmdname' => 'node', 'contents' => [ { 'parent' => {}, 'text' => ' ', 'type' => 'empty_line' }, { 'contents' => [ { 'args' => [ { 'contents' => [ { 'parent' => {}, 'text' => 'TOP' } ], 'parent' => {}, 'type' => 'brace_command_arg' } ], 'cmdname' => 'xref', 'contents' => [], 'extra' => { 'brace_command_contents' => [ [ {} ] ], 'label' => {}, 'node_argument' => { 'node_content' => [ {} ], 'normalized' => 'Top' } }, 'line_nr' => { 'file_name' => '', 'line_nr' => 3, 'macro' => '' }, 'parent' => {} }, { 'parent' => {}, 'text' => '. ' }, { 'args' => [ { 'contents' => [ { 'parent' => {}, 'text' => 'tOP' } ], 'parent' => {}, 'type' => 'brace_command_arg' } ], 'cmdname' => 'xref', 'contents' => [], 'extra' => { 'brace_command_contents' => [ [ {} ] ], 'label' => {}, 'node_argument' => { 'node_content' => [ {} ], 'normalized' => 'Top' } }, 'line_nr' => {}, 'parent' => {} }, { 'parent' => {}, 'text' => '. ' } ], 'parent' => {}, 'type' => 'paragraph' }, { 'parent' => {}, 'text' => ' ', 'type' => 'empty_line' }, { 'cmdname' => 'menu', 'contents' => [ { 'extra' => { 'command' => {} }, 'parent' => {}, 'text' => ' ', 'type' => 'empty_line_after_command' }, { 'args' => [ { 'parent' => {}, 'text' => '* ', 'type' => 'menu_entry_leading_text' }, { 'contents' => [ { 'parent' => {}, 'text' => 'tOP' } ], 'parent' => {}, 'type' => 'menu_entry_node' }, { 'parent' => {}, 'text' => '::', 'type' => 'menu_entry_separator' }, { 'contents' => [ { 'contents' => [ { 'parent' => {}, 'text' => ' ' } ], 'parent' => {}, 'type' => 'preformatted' } ], 'parent' => {}, 'type' => 'menu_entry_description' } ], 'extra' => { 'menu_entry_description' => {}, 'menu_entry_node' => { 'node_content' => [ {} ], 'normalized' => 'Top' } }, 'line_nr' => { 'file_name' => '', 'line_nr' => 6, 'macro' => '' }, 'parent' => {}, 'type' => 'menu_entry' }, { 'args' => [ { 'contents' => [ { 'extra' => { 'command' => {} }, 'parent' => {}, 'text' => ' ', 'type' => 'empty_spaces_after_command' }, { 'parent' => {}, 'text' => 'menu' }, { 'parent' => {}, 'text' => ' ', 'type' => 'spaces_at_end' } ], 'parent' => {}, 'type' => 'misc_line_arg' } ], 'cmdname' => 'end', 'extra' => { 'command' => {}, 'command_argument' => 'menu', 'text_arg' => 'menu' }, 'line_nr' => { 'file_name' => '', 'line_nr' => 7, 'macro' => '' }, 'parent' => {} } ], 'extra' => { 'end_command' => {} }, 'line_nr' => { 'file_name' => '', 'line_nr' => 5, 'macro' => '' }, 'parent' => {} } ], 'extra' => { 'node_content' => [ {} ], 'nodes_manuals' => [ { 'node_content' => [], 'normalized' => 'Top' } ], 'normalized' => 'Top' }, 'line_nr' => { 'file_name' => '', 'line_nr' => 1, 'macro' => '' }, 'parent' => {} } ], 'type' => 'document_root' }; $result_trees{'top_node_normalization'}{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}; $result_trees{'top_node_normalization'}{'contents'}[1]{'args'}[0]{'contents'}[0]{'extra'}{'command'} = $result_trees{'top_node_normalization'}{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'args'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'args'}[0]{'contents'}[1]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'args'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'args'}[0]{'contents'}[2]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'args'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'args'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'args'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'args'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'extra'}{'brace_command_contents'}[0][0] = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'args'}[0]{'contents'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'extra'}{'label'} = $result_trees{'top_node_normalization'}{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'extra'}{'node_argument'}{'node_content'}[0] = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'args'}[0]{'contents'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[1]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'args'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'args'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'extra'}{'brace_command_contents'}[0][0] = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'args'}[0]{'contents'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'extra'}{'label'} = $result_trees{'top_node_normalization'}{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'extra'}{'node_argument'}{'node_content'}[0] = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'args'}[0]{'contents'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'line_nr'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'line_nr'}; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'contents'}[3]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[1]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[2]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[0]{'extra'}{'command'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[1]{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[1]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[2]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]{'contents'}[0]{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]{'contents'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'extra'}{'menu_entry_description'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'extra'}{'menu_entry_node'}{'node_content'}[0] = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[1]{'contents'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]{'contents'}[0]{'extra'}{'command'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]{'contents'}[1]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]{'contents'}[2]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'extra'}{'command'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'extra'}{'end_command'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'contents'}[2]; $result_trees{'top_node_normalization'}{'contents'}[1]{'contents'}[3]{'parent'} = $result_trees{'top_node_normalization'}{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'extra'}{'node_content'}[0] = $result_trees{'top_node_normalization'}{'contents'}[1]{'args'}[0]{'contents'}[1]; $result_trees{'top_node_normalization'}{'contents'}[1]{'extra'}{'nodes_manuals'}[0]{'node_content'} = $result_trees{'top_node_normalization'}{'contents'}[1]{'extra'}{'node_content'}; $result_trees{'top_node_normalization'}{'contents'}[1]{'parent'} = $result_trees{'top_node_normalization'}; $result_texis{'top_node_normalization'} = '@node ToP @xref{TOP}. @xref{tOP}. @menu * tOP:: @end menu '; $result_texts{'top_node_normalization'} = ' . . * tOP:: '; $result_sectioning{'top_node_normalization'} = {}; $result_nodes{'top_node_normalization'} = { 'cmdname' => 'node', 'extra' => { 'normalized' => 'Top' }, 'menu_child' => {}, 'menus' => [ { 'cmdname' => 'menu', 'extra' => { 'end_command' => { 'cmdname' => 'end', 'extra' => { 'command' => {}, 'command_argument' => 'menu', 'text_arg' => 'menu' } } } } ], 'node_next' => {}, 'node_prev' => {}, 'node_up' => { 'extra' => { 'manual_content' => [ { 'text' => 'dir' } ], 'top_node_up' => {} }, 'type' => 'top_node_up' } }; $result_nodes{'top_node_normalization'}{'menu_child'} = $result_nodes{'top_node_normalization'}; $result_nodes{'top_node_normalization'}{'menus'}[0]{'extra'}{'end_command'}{'extra'}{'command'} = $result_nodes{'top_node_normalization'}{'menus'}[0]; $result_nodes{'top_node_normalization'}{'node_next'} = $result_nodes{'top_node_normalization'}; $result_nodes{'top_node_normalization'}{'node_prev'} = $result_nodes{'top_node_normalization'}; $result_nodes{'top_node_normalization'}{'node_up'}{'extra'}{'top_node_up'} = $result_nodes{'top_node_normalization'}; $result_menus{'top_node_normalization'} = { 'cmdname' => 'node', 'extra' => { 'normalized' => 'Top' }, 'menu_child' => {}, 'menu_up' => {}, 'menu_up_hash' => { 'Top' => 1 } }; $result_menus{'top_node_normalization'}{'menu_child'} = $result_menus{'top_node_normalization'}; $result_menus{'top_node_normalization'}{'menu_up'} = $result_menus{'top_node_normalization'}; $result_errors{'top_node_normalization'} = [ { 'error_line' => ':1: warning: For `ToP\', up in menu `ToP\' and up `(dir)\' don\'t match ', 'file_name' => '', 'line_nr' => 1, 'macro' => '', 'text' => 'For `ToP\', up in menu `ToP\' and up `(dir)\' don\'t match', 'type' => 'warning' } ]; $result_converted{'info'}->{'top_node_normalization'} = 'This is , produced by tp version from .  File: , Node: Top, Next: Top, Prev: Top, Up: (dir) *Note ToP::. *Note ToP::. * Menu: * tOP::  Tag Table: Node: Top41  End Tag Table '; 1;
cgwalters/texinfo-git-mirror
tp/t/results/info_tests/top_node_normalization.pl
Perl
gpl-3.0
18,493
/* xoreos-tools - Tools to help with xoreos development * * xoreos-tools is the legal property of its developers, whose names * can be found in the AUTHORS file distributed with this source * distribution. * * xoreos-tools 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. * * xoreos-tools is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with xoreos-tools. If not, see <http://www.gnu.org/licenses/>. */ /** @file * Low-level detection of architecture/system properties. */ /* Based on ScummVM (<http://scummvm.org>) code, which is released * under the terms of version 2 or later of the GNU General Public * License. * * The original copyright note in ScummVM reads as follows: * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef COMMON_SYSTEM_H #define COMMON_SYSTEM_H #if defined(HAVE_CONFIG_H) #include "config.h" #endif #include "src/common/noreturn.h" #include "src/common/fallthrough.h" #if defined(_MSC_VER) #include <cstdarg> #include <cstdio> #include <cstdlib> #define FORCEINLINE __forceinline #define PLUGIN_EXPORT __declspec(dllexport) #if _MSC_VER < 1900 #define snprintf c99_snprintf #define vsnprintf c99_vsnprintf static FORCEINLINE int c99_vsnprintf(char *str, size_t size, const char *format, va_list ap) { int count = -1; if (size != 0) count = _vsnprintf_s(str, size, _TRUNCATE, format, ap); if (count == -1) count = _vscprintf(format, ap); return count; } static FORCEINLINE int c99_snprintf(char *str, size_t size, const char *format, ...) { int count; va_list ap; va_start(ap, format); count = c99_vsnprintf(str, size, format, ap); va_end(ap); return count; } #endif #ifndef HAVE_STRTOLL #define strtoll _strtoi64 #define HAVE_STRTOLL 1 #endif #ifndef HAVE_STRTOULL #define strtoull _strtoui64 #define HAVE_STRTOULL 1 #endif #if !defined(XOREOS_LITTLE_ENDIAN) && !defined(XOREOS_BIG_ENDIAN) #define XOREOS_LITTLE_ENDIAN 1 #endif #ifndef WIN32 #define WIN32 #endif #define IGNORE_UNUSED_VARIABLES __pragma(warning(disable : 4101)) #elif defined(__MINGW32__) #if !defined(XOREOS_LITTLE_ENDIAN) && !defined(XOREOS_BIG_ENDIAN) #define XOREOS_LITTLE_ENDIAN 1 #endif #define PLUGIN_EXPORT __declspec(dllexport) #ifndef WIN32 #define WIN32 #endif #elif defined(UNIX) #if !defined(XOREOS_LITTLE_ENDIAN) && !defined(XOREOS_BIG_ENDIAN) #if defined(HAVE_CONFIG_H) #if defined(WORDS_BIGENDIAN) #define XOREOS_BIG_ENDIAN 1 #else #define XOREOS_LITTLE_ENDIAN 1 #endif #endif #endif #else #error No system type defined #endif // // GCC specific stuff // #if defined(__GNUC__) #define PACKED_STRUCT __attribute__((__packed__)) #define GCC_PRINTF(x,y) __attribute__((__format__(printf, x, y))) #if (__GNUC__ >= 3) // Macro to ignore several "unused variable" warnings produced by GCC #define IGNORE_UNUSED_VARIABLES _Pragma("GCC diagnostic ignored \"-Wunused-variable\"") \ _Pragma("GCC diagnostic ignored \"-Wunused-but-set-variable\"") #endif #if !defined(FORCEINLINE) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) #define FORCEINLINE inline __attribute__((__always_inline__)) #endif #else #define PACKED_STRUCT #define GCC_PRINTF(x,y) #endif #if defined(__cplusplus) #define UNUSED(x) #else #if defined(__GNUC__) #define UNUSED(x) UNUSED_ ## x __attribute__((__unused__)) #else #define UNUSED(x) UNUSED_ ## x #endif #endif #if defined(__clang__) // clang does not know the "unused-but-set-variable" (but claims to be GCC) #undef IGNORE_UNUSED_VARIABLES #define IGNORE_UNUSED_VARIABLES _Pragma("GCC diagnostic ignored \"-Wunused-variable\"") #endif // // Fallbacks for various functions // #ifndef HAVE_STRTOF #define strtof c99_strtof static FORCEINLINE float c99_strtof(const char *nptr, char **endptr) { return (float) strtod(nptr, endptr); } #define HAVE_STRTOF 1 #endif #ifndef HAVE_STRTOLL #define strtoll c99_strtoll #include <cctype> #include <cerrno> #include <climits> #ifndef LLONG_MAX #define LLONG_MAX 0x7FFFFFFFFFFFFFFFlL #endif #ifndef LLONG_MIN #define LLONG_MIN (-0x7FFFFFFFFFFFFFFFLL-1) #endif /** Convert a string to a long long. * * Based on OpenBSD's strtoll() function, released under the terms of * the 3-clause BSD license. * * Ignores 'locale' stuff. Assumes that the upper and lower case * alphabets and digits are each contiguous. */ static long long c99_strtoll(const char *nptr, char **endptr, int base) { const char *s; long long acc, cutoff; int c; int neg, any, cutlim; /* * Skip white space and pick up leading +/- sign if any. * If base is 0, allow 0x for hex and 0 for octal, else * assume decimal; if base is already 16, allow 0x. */ s = nptr; do { c = (unsigned char) *s++; } while (isspace(c)); if (c == '-') { neg = 1; c = *s++; } else { neg = 0; if (c == '+') c = *s++; } if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } if (base == 0) base = c == '0' ? 8 : 10; /* * Compute the cutoff value between legal numbers and illegal * numbers. That is the largest legal value, divided by the * base. An input number that is greater than this value, if * followed by a legal input character, is too big. One that * is equal to this value may be valid or not; the limit * between valid and invalid numbers is then based on the last * digit. For instance, if the range for long longs is * [-9223372036854775808..9223372036854775807] and the input base * is 10, cutoff will be set to 922337203685477580 and cutlim to * either 7 (neg==0) or 8 (neg==1), meaning that if we have * accumulated a value > 922337203685477580, or equal but the * next digit is > 7 (or 8), the number is too big, and we will * return a range error. * * Set any if any `digits' consumed; make it negative to indicate * overflow. */ cutoff = neg ? LLONG_MIN : LLONG_MAX; cutlim = cutoff % base; cutoff /= base; if (neg) { if (cutlim > 0) { cutlim -= base; cutoff += 1; } cutlim = -cutlim; } for (acc = 0, any = 0;; c = (unsigned char) *s++) { if (isdigit(c)) c -= '0'; else if (isalpha(c)) c -= isupper(c) ? 'A' - 10 : 'a' - 10; else break; if (c >= base) break; if (any < 0) continue; if (neg) { if (acc < cutoff || (acc == cutoff && c > cutlim)) { any = -1; acc = LLONG_MIN; errno = ERANGE; } else { any = 1; acc *= base; acc -= c; } } else { if (acc > cutoff || (acc == cutoff && c > cutlim)) { any = -1; acc = LLONG_MAX; errno = ERANGE; } else { any = 1; acc *= base; acc += c; } } } if (endptr != 0) *endptr = any ? const_cast<char *>(s - 1) : const_cast<char *>(nptr); return (acc); } #define HAVE_STRTOLL 1 #endif #ifndef HAVE_STRTOULL #define strtoull c99_strtoull #include <cctype> #include <cerrno> #include <climits> #ifndef ULLONG_MAX #define ULLONG_MAX 0xFFFFFFFFFFFFFFFFULL #endif /** Convert a string to an unsigned long long. * * Based on OpenBSD's strtoull() function, released under the terms of * the 3-clause BSD license. * * Ignores 'locale' stuff. Assumes that the upper and lower case * alphabets and digits are each contiguous. */ static unsigned long long c99_strtoull(const char *nptr, char **endptr, int base) { const char *s; unsigned long long acc, cutoff; int c; int neg, any, cutlim; /* * See c99_strtoll() for comments as to the logic used. */ s = nptr; do { c = (unsigned char) *s++; } while (isspace(c)); if (c == '-') { neg = 1; c = *s++; } else { neg = 0; if (c == '+') c = *s++; } if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } if (base == 0) base = c == '0' ? 8 : 10; cutoff = ULLONG_MAX / (unsigned long long)base; cutlim = ULLONG_MAX % (unsigned long long)base; for (acc = 0, any = 0;; c = (unsigned char) *s++) { if (isdigit(c)) c -= '0'; else if (isalpha(c)) c -= isupper(c) ? 'A' - 10 : 'a' - 10; else break; if (c >= base) break; if (any < 0) continue; if (acc > cutoff || (acc == cutoff && c > cutlim)) { any = -1; acc = ULLONG_MAX; errno = ERANGE; } else { any = 1; acc *= static_cast<unsigned long long>(base); acc += c; } } if (neg && any > 0) acc = -acc; if (endptr != 0) *endptr = any ? const_cast<char *>(s - 1) : const_cast<char *>(nptr); return (acc); } #define HAVE_STRTOULL 1 #endif // Compatibility macro for dealing with the explicit bool cast problem. #if __cplusplus < 201103L #define XOREOS_EXPLICIT_OPERATOR_CONV #else #define XOREOS_EXPLICIT_OPERATOR_CONV explicit #endif // // Fallbacks / default values for various special macros // #ifndef FORCEINLINE #define FORCEINLINE inline #endif #ifndef STRINGBUFLEN #define STRINGBUFLEN 1024 #endif #ifndef MAXPATHLEN #define MAXPATHLEN 256 #endif #ifndef IGNORE_UNUSED_VARIABLES #define IGNORE_UNUSED_VARIABLES #endif #endif // COMMON_SYSTEM_H
farmboy0/xoreos-tools
src/common/system.h
C
gpl-3.0
10,584
/* * dmfs - http://dmfs.org/ * * Copyright (C) 2012 Marten Gajda <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package org.dmfs.xmlserializer; import java.io.IOException; import java.io.Writer; /** * An abstract XML node. * * @author Marten Gajda <[email protected]> */ public abstract class XmlAbstractNode { /** * State for new nodes. */ final static int STATE_NEW = 0; /** * State indicating the node has been opened and the start tag has been opened. */ final static int STATE_START_TAG_OPEN = 1; /** * State indication the node has been opened and the start tag has been closed, but the end tag is not written yet. */ final static int STATE_START_TAG_CLOSED = 2; /** * State indication the node has been closed (i.e. the end tag has been written). */ final static int STATE_CLOSED = 3; /** * The state of a node, initialized with {@link STATE_NEW}. */ int state = STATE_NEW; /** * The depth at which this node is located in the XML tree. Until this node has been added to a tree it is considered to be the root element. */ private int mDepth = 0; /** * Set the depth of this node (i.e. at which level it is located in the XML node tree). * * @param depth * The depth. */ void setDepth(int depth) { mDepth = depth; } /** * Get the depth of this node (i.e. at which level it is located in the XML node tree). * * @return The depth. */ final int getDepth() { return mDepth; } /** * Assign the {@link XmlNamespaceRegistry} that belongs to this XML tree. * * @param namespaceRegistry * The {@link XmlNamespaceRegistry} of this XMl tree. * @throws InvalidValueException */ abstract void setNamespaceRegistry(XmlNamespaceRegistry namespaceRegistry) throws InvalidValueException; /** * Open this node for writing to a {@link Writer} * * @param out * The {@link Writer} to write to. * @throws IOException * @throws InvalidStateException * @throws InvalidValueException */ abstract void open(Writer out) throws IOException, InvalidStateException, InvalidValueException; /** * Close this node, flushing out all unwritten content. * * @throws IOException * @throws InvalidStateException * @throws InvalidValueException */ abstract void close() throws IOException, InvalidStateException, InvalidValueException; }
dmfs/xml-serializer
src/org/dmfs/xmlserializer/XmlAbstractNode.java
Java
gpl-3.0
3,072
<? include('global.php'); ?> <? // asp2php (vbscript) converted on Sat Apr 25 20:59:49 2015 $CODEPAGE="1252";?> <? require("Connections/connrumbo.php"); ?> <? $Siniestros__DDcia="%"; if (($_POST["Cia"]!="")) { $Siniestros__DDcia=$_POST["Cia"]; } ?> <? // $Siniestros is of type "ADODB.Recordset" echo $MM_connrumbo_STRING; echo "SELECT Abonados.Nombre, Abonados.Apellido1, Abonados.Apellido2, Siniestro.Compañia as cpropia, Contrarios.Compañia as cia, Siniestro.Fase, Fases.Texto, Siniestro.Id, Siniestro.[Fecha Siniestro] FROM Fases INNER JOIN ((Abonados INNER JOIN Siniestro ON Abonados.Id = Siniestro.Abonado) INNER JOIN Contrarios ON Siniestro.Id = Contrarios.Siniestro) ON Fases.Id = Siniestro.Fase WHERE (((Contrarios.Compañia)like '%"+str_replace("'","''",$Siniestros__DDcia)+"%') AND ((Siniestro.Fase)<70)) ORDER BY Siniestro.Fase"; echo 0; echo 2; echo 1; $rs=mysql_query(); $Siniestros_numRows=0; ?> <? $Repeat1__numRows=-1; $Repeat1__index=0; $Siniestros_numRows=$Siniestros_numRows+$Repeat1__numRows; ?> <html> <head> <title>Listado por Cia. Contraria</title> </head> <body bgcolor="#FFFFFF" background="Imagenes/fondo.gif" bgproperties="fixed" text="#000000" topmargin="30"> <script language="JavaScript" src="menu.js"></script> <table width="100%" border="1" cellspacing="0" bordercolor="#000000"> <tr bgcolor="#CCCCCC"> <td>Nombre</td> <td>Fecha de siniestro </td> <td>Compa&ntilde;ia</td> <td>Fase</td> </tr> <? while((($Repeat1__numRows!=0) && (!($Siniestros==0)))) { ?> <tr> <td><a href="Siniestro.asp?Id=<? echo (->$Item["Id"]->$Value);?>"><? echo (->$Item["Nombre"]->$Value);?>&nbsp;<? echo (->$Item["Apellido1"]->$Value);?>&nbsp;<? echo (->$Item["Apellido2"]->$Value);?></a></td> <td><? echo (->$Item["Fecha Siniestro"]->$Value);?></td> <td><? echo (->$Item["cia"]->$Value);?></td> <td><? echo (->$Item["Texto"]->$Value);?></td> </tr> <? $Repeat1__index=$Repeat1__index+1; $Repeat1__numRows=$Repeat1__numRows-1; $Siniestros=mysql_fetch_array($Siniestros_query); $Siniestros_BOF=0; } ?> </table> </body> </html> <? $Siniestros=null; ?>
loro102/rumbo2
ListadoCiaContrariaSalida.php
PHP
gpl-3.0
2,150
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html > <head><title>1.1.1.0 node_activity_vectors.py</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="TeX4ht (http://www.cse.ohio-state.edu/~gurari/TeX4ht/)"> <meta name="originator" content="TeX4ht (http://www.cse.ohio-state.edu/~gurari/TeX4ht/)"> <!-- html,index=2,3,4,5,next --> <meta name="src" content="mammult_doc.tex"> <meta name="date" content="2015-10-19 17:14:00"> <link rel="stylesheet" type="text/css" href="mammult_doc.css"> </head><body > <!--l. 3--><div class="crosslinks"><p class="noindent">[<a href="mammult_docsu5.html" >next</a>] [<a href="mammult_docsu3.html" >prev</a>] [<a href="mammult_docsu3.html#tailmammult_docsu3.html" >prev-tail</a>] [<a href="#tailmammult_docsu4.html">tail</a>] [<a href="mammult_docsu1.html#mammult_docsu4.html" >up</a>] </p></div> <h5 class="subsubsectionHead"><a id="x8-70001.1.1"></a><span class="cmtt-10x-x-109">node</span><span class="cmtt-10x-x-109">_activity</span><span class="cmtt-10x-x-109">_vectors.py</span></h5> <!--l. 3--><p class="noindent" ><span class="cmbx-10x-x-109">NAME</span> <!--l. 3--><p class="indent" > <span class="cmbx-10x-x-109">node</span><span class="cmbx-10x-x-109">_activity</span><span class="cmbx-10x-x-109">_vectors.py </span>- compute the activity vectors of all the nodes of a multiplex. <!--l. 3--><p class="noindent" ><span class="cmbx-10x-x-109">SYNOPSYS</span> <!--l. 3--><p class="indent" > <span class="cmbx-10x-x-109">node</span><span class="cmbx-10x-x-109">_activity</span><span class="cmbx-10x-x-109">_vectors.py </span><span class="cmmi-10x-x-109">&#x003C;</span><span class="cmitt-10x-x-109">layer1</span><span class="cmmi-10x-x-109">&#x003E; </span><span class="cmitt-10x-x-109">[</span><span class="cmmi-10x-x-109">&#x003C;</span><span class="cmitt-10x-x-109">layer2</span><span class="cmmi-10x-x-109">&#x003E; </span><span class="cmitt-10x-x-109">...]</span> <!--l. 15--><p class="noindent" ><span class="cmbx-10x-x-109">DESCRIPTION</span> <!--l. 15--><p class="indent" > Compute and print on output the activity vectors of the nodes of a multiplex network, whose layers are given as input in the files <span class="cmti-10x-x-109">layer1</span>, <span class="cmti-10x-x-109">layer2</span>, etc. <!--l. 15--><p class="indent" > Each input file contains the (undirected) edge list of a layer, and each line is in the format: <!--l. 15--><p class="indent" > &#x00A0; <span class="cmti-10x-x-109">src</span><span class="cmti-10x-x-109">_ID dest</span><span class="cmti-10x-x-109">_ID</span> <!--l. 15--><p class="indent" > where <span class="cmti-10x-x-109">src</span><span class="cmti-10x-x-109">_ID </span>and <span class="cmti-10x-x-109">dest</span><span class="cmti-10x-x-109">_ID </span>are the IDs of the two endpoints of an edge. <!--l. 26--><p class="noindent" ><span class="cmbx-10x-x-109">OUTPUT</span> <!--l. 26--><p class="indent" > The program prints on <span class="cmtt-10x-x-109">stdout </span>a list of lines, where the n-th line contains the activity vector of the n-th node, i.e. a bit-string where each bit is set to &#8220;1&#8221; if the node is active on the corresponding layer, and to &#8220;0&#8221; otherwise. <!--l. 26--><p class="noindent" >As usual, node IDs start from zero and proceed sequentially, without gaps, i.e., if a node ID is not present in any of the layer files given as input, the program considers it as being isolated on all the layers, and will print on output a bit-string of zeros. <!--l. 28--><p class="noindent" ><span class="cmbx-10x-x-109">REFERENCE</span> <!--l. 28--><p class="indent" > V. Nicosia, V. Latora, &#8220;Measuring and modeling correlations in multiplex networks&#8221;, <span class="cmti-10x-x-109">Phys. Rev. E </span><span class="cmbx-10x-x-109">92</span>, 032805 (2015). <!--l. 28--><p class="indent" > Link to paper: <a href="http://journals.aps.org/pre/abstract/10.1103/PhysRevE.92.032805" class="url" ><span class="cmtt-10x-x-109">http://journals.aps.org/pre/abstract/10.1103/PhysRevE.92.032805</span></a> <!--l. 3--><div class="crosslinks"><p class="noindent">[<a href="mammult_docsu5.html" >next</a>] [<a href="mammult_docsu3.html" >prev</a>] [<a href="mammult_docsu3.html#tailmammult_docsu3.html" >prev-tail</a>] [<a href="mammult_docsu4.html" >front</a>] [<a href="mammult_docsu1.html#mammult_docsu4.html" >up</a>] </p></div> <!--l. 3--><p class="indent" > <a id="tailmammult_docsu4.html"></a> </body></html>
KatolaZ/mammult
doc/html/mammult_docsu4.html
HTML
gpl-3.0
4,795
/* Copyright (C) 2012 Statoil ASA, Norway. The file 'config_content_node.h' is part of ERT - Ensemble based Reservoir Tool. ERT 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. ERT 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 at <http://www.gnu.org/licenses/gpl.html> for more details. */ #ifndef __CONFIG_CONTENT_NODE_H__ #define __CONFIG_CONTENT_NODE_H__ #ifdef __cplusplus define extern "C" { #endif #include <ert/util/hash.h> #include <ert/config/config_schema_item.h> #include <ert/config/config_path_elm.h> typedef struct config_content_node_struct config_content_node_type; config_content_node_type * config_content_node_alloc( const config_schema_item_type * schema , const config_path_elm_type * cwd); void config_content_node_add_value(config_content_node_type * node , const char * value); void config_content_node_set(config_content_node_type * node , const stringlist_type * token_list); char * config_content_node_alloc_joined_string(const config_content_node_type * node, const char * sep); void config_content_node_free(config_content_node_type * node); void config_content_node_free__(void * arg); const char * config_content_node_get_full_string( config_content_node_type * node , const char * sep ); const char * config_content_node_iget(const config_content_node_type * node , int index); bool config_content_node_iget_as_bool(const config_content_node_type * node , int index); int config_content_node_iget_as_int(const config_content_node_type * node , int index); double config_content_node_iget_as_double(const config_content_node_type * node , int index); const char * config_content_node_iget_as_path(config_content_node_type * node , int index); const char * config_content_node_iget_as_abspath( config_content_node_type * node , int index); const char * config_content_node_iget_as_relpath( config_content_node_type * node , int index); const stringlist_type * config_content_node_get_stringlist( const config_content_node_type * node ); const char * config_content_node_safe_iget(const config_content_node_type * node , int index); int config_content_node_get_size( const config_content_node_type * node ); const char * config_content_node_get_kw( const config_content_node_type * node ); void config_content_node_assert_key_value( const config_content_node_type * node ); const config_path_elm_type * config_content_node_get_path_elm( const config_content_node_type * node ); void config_content_node_init_opt_hash( const config_content_node_type * node , hash_type * opt_hash , int elm_offset); void config_content_node_fprintf( const config_content_node_type * node , FILE * stream ); #ifdef __cplusplus } #endif #endif
iLoop2/ResInsight
ThirdParty/Ert/devel/libconfig/include/ert/config/config_content_node.h
C
gpl-3.0
3,666
package beseenium.controller.ActionFactory; /** Copyright(C) 2015 Jan P.C. Hanson & BeSeen Marketing Ltd * * 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/>. */ import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import beseenium.controller.ActionDataFactory.ActionDataFactory; import beseenium.controller.ActionFactory.elementActions.MakeClear; import beseenium.controller.ActionFactory.elementActions.MakeClick; import beseenium.controller.ActionFactory.elementActions.MakeGetAttribute; import beseenium.controller.ActionFactory.elementActions.MakeGetCssValue; import beseenium.controller.ActionFactory.elementActions.MakeGetLocation; import beseenium.controller.ActionFactory.elementActions.MakeGetSize; import beseenium.controller.ActionFactory.elementActions.MakeGetTagName; import beseenium.controller.ActionFactory.elementActions.MakeGetText; import beseenium.controller.ActionFactory.elementActions.MakeIsDisplayed; import beseenium.controller.ActionFactory.elementActions.MakeIsEnabled; import beseenium.controller.ActionFactory.elementActions.MakeIsSelected; import beseenium.controller.ActionFactory.elementActions.MakeSendKeys; import beseenium.controller.ActionFactory.elementActions.MakeSubmit; import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByClass; import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByCss; import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsById; import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByLinkTxt; import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByName; import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByPartialLinkTxt; import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByTagName; import beseenium.controller.ActionFactory.findElementsBy.MakeFindElementsByXpath; import beseenium.controller.ActionFactory.navigateActions.MakeNavigateBack; import beseenium.controller.ActionFactory.navigateActions.MakeNavigateForward; import beseenium.controller.ActionFactory.navigateActions.MakeRefreshPage; import beseenium.controller.ActionFactory.pageActions.MakeBrowserQuit; import beseenium.controller.ActionFactory.pageActions.MakeGetPageSrc; import beseenium.controller.ActionFactory.pageActions.MakeGetTitle; import beseenium.controller.ActionFactory.pageActions.MakeGetURL; import beseenium.controller.ActionFactory.pageActions.MakePageClose; import beseenium.controller.ActionFactory.pageActions.MakePageGet; import beseenium.exceptions.actionDataExceptions.ActionDataFactoryException; import beseenium.exceptions.actionExceptions.ActionFactoryException; import beseenium.model.action.AbstractAction; /** * this class is a factory for creating actions, it uses a factory method * style pattern and a map implementation. * @author JPC Hanson * */ public class ActionFactory { /** the map to store the actions in **/ private Map<String, MakeAction> actionMap; /** internal ActionDataFactory reference **/ private ActionDataFactory actionDataFactory; /** * default constructor creates and populates internal map * @param actionDataFactory * @throws ActionDataFactoryException * @throws MalformedURLException * */ public ActionFactory(ActionDataFactory actionDataFactory) throws ActionDataFactoryException, MalformedURLException { super(); this.actionDataFactory = actionDataFactory; this.actionMap = new HashMap<String, MakeAction>(); this.populateActionMap(); } /** * creates an Action * @return AbstractAction * @throws ActionFactoryException * @throws ActionDataFactoryException */ public AbstractAction makeAction(String actionKey) throws ActionFactoryException { if(this.actionMap.containsKey(actionKey)) {return this.actionMap.get(actionKey).makeAction();} else {throw new ActionFactoryException("you cannot instanciate this type of Action '" +actionKey+ "' Check your spelling, or refer to documentation");} } /** * creates all possible actions and populates the map with them. * @throws ActionDataFactoryException * */ private void populateActionMap() throws ActionDataFactoryException { // //Page Actions this.actionMap.put( "PageGet", new MakePageGet(actionDataFactory)); this.actionMap.put( "GetPageSrc", new MakeGetPageSrc(actionDataFactory)); this.actionMap.put( "BrowserQuit", new MakeBrowserQuit(actionDataFactory)); this.actionMap.put( "GetTitle", new MakeGetTitle(actionDataFactory)); this.actionMap.put( "GetURL", new MakeGetURL(actionDataFactory)); this.actionMap.put( "PageClose", new MakePageClose(actionDataFactory)); // //Navigation Actions this.actionMap.put( "NavigateBack", new MakeNavigateBack(actionDataFactory)); this.actionMap.put( "NavigateForward", new MakeNavigateForward(actionDataFactory)); this.actionMap.put( "RefreshPage", new MakeRefreshPage(actionDataFactory)); // //Find Element Actions this.actionMap.put( "FindElementsByClass", new MakeFindElementsByClass(actionDataFactory)); this.actionMap.put( "FindElementsByCss", new MakeFindElementsByCss(actionDataFactory)); this.actionMap.put( "FindElementsById", new MakeFindElementsById(actionDataFactory)); this.actionMap.put( "FindElementsByLinkTxt", new MakeFindElementsByLinkTxt(actionDataFactory)); this.actionMap.put( "FindElementsByName", new MakeFindElementsByName(actionDataFactory)); this.actionMap.put( "FindElementsByPartialLinkTxt", new MakeFindElementsByPartialLinkTxt(actionDataFactory)); this.actionMap.put( "FindElementsByTagName", new MakeFindElementsByTagName(actionDataFactory)); this.actionMap.put( "FindElementsByXpath", new MakeFindElementsByXpath(actionDataFactory)); // //Element Actions this.actionMap.put( "Clear", new MakeClear(actionDataFactory)); this.actionMap.put( "Click", new MakeClick(actionDataFactory)); this.actionMap.put( "GetAttribute", new MakeGetAttribute(actionDataFactory)); this.actionMap.put( "GetCssValue", new MakeGetCssValue(actionDataFactory)); this.actionMap.put( "GetLocation", new MakeGetLocation(actionDataFactory)); this.actionMap.put( "GetSize", new MakeGetSize(actionDataFactory)); this.actionMap.put( "GetTagName", new MakeGetTagName(actionDataFactory)); this.actionMap.put( "GetText", new MakeGetText(actionDataFactory)); this.actionMap.put( "IsDisplayed", new MakeIsDisplayed(actionDataFactory)); this.actionMap.put( "IsEnabled", new MakeIsEnabled(actionDataFactory)); this.actionMap.put( "IsSelected", new MakeIsSelected(actionDataFactory)); this.actionMap.put( "SendKeys", new MakeSendKeys(actionDataFactory)); this.actionMap.put( "Submit", new MakeSubmit(actionDataFactory)); } }
jpchanson/BeSeenium
src/beseenium/controller/ActionFactory/ActionFactory.java
Java
gpl-3.0
7,333
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package proyectomio.controlador.operaciones; import proyectomio.accesoDatos.Controlador_BD; import proyectomio.modelo.Consulta; /** * * @author root */ public class Controlador_Conductor { private final Controlador_BD CONTROLADOR_BD = new Controlador_BD(); public Consulta consultar_buses_asignados(int id_conductor) { if (id_conductor != 0) { Consulta consulta = new Consulta(); consulta = CONTROLADOR_BD.consultarBD("SELECT * FROM bus_empleado inner join bus on bus_empleado.placa_bus = bus.placa inner join ruta on ruta.id_ruta = bus.id_ruta where bus_empleado.id_empleado = " + id_conductor); return consulta; } else{ Consulta consulta = new Consulta(); consulta = CONTROLADOR_BD.consultarBD("SELECT * FROM (bus_empleado inner join bus on bus_empleado.placa_bus = bus.placa) inner join ruta on ruta.id_ruta = bus.id_ruta;"); return consulta; } } }
luchoman08/Proyecto-MIO
src/java/proyectomio/controlador/operaciones/Controlador_Conductor.java
Java
gpl-3.0
1,169
#include <cstdio> #include <vector> #include <utility> #include <algorithm> using namespace std; pair<int, int> computeGreedyLongestPath(const vector<vector<int> > & adjList, int startV, const vector<int> & weightOfVertex); int main(void) { int T, numV, numE, u, v, caseId; vector<vector<int> > adjList; vector<int> emptyList, weightOfVertex; scanf("%d", &T); pair<int, int> maxLearnAndDest; caseId = 1; while(caseId <= T) { scanf("%d %d", &numV, &numE); adjList.assign(numV, emptyList); weightOfVertex.assign(numV, 0); for(v = 0; v < numV; v++) scanf("%d", &weightOfVertex[v]); for(int e = 0; e < numE; e++) { scanf("%d %d", &u, &v); adjList[u].push_back(v); } maxLearnAndDest = computeGreedyLongestPath(adjList, 0, weightOfVertex); printf("Case %d: %d %d\n", caseId, maxLearnAndDest.first, maxLearnAndDest.second); caseId++; } return 0; } pair<int, int> computeGreedyLongestPath(const vector<vector<int> > & adjList, int startV, const vector<int> & weightOfVertex) { int v = startV, totalWeight, maxNeighborInd; totalWeight = weightOfVertex[startV]; while(adjList[v].size() > 0) { maxNeighborInd = 0; for(int ind = 1; ind < (int) adjList[v].size(); ind++) if(weightOfVertex[adjList[v][ind]] > weightOfVertex[adjList[v][maxNeighborInd]]) maxNeighborInd = ind; totalWeight += weightOfVertex[adjList[v][maxNeighborInd]]; v = adjList[v][maxNeighborInd]; } return make_pair(totalWeight, v); }
shakil113/Uva-onlineJudge-solve
UVA12376.cpp
C++
gpl-3.0
1,472
<?php // Copyright (c) Aura development team - Licensed under GNU GPL // For more information, see licence.txt in the main folder // // This is a simple page to create accounts. // Due to the need of reading conf files this script has to be located // inside the Aura web folder, or you have to adjust some paths. // -------------------------------------------------------------------------- include '../shared/Conf.class.php'; include '../shared/MabiDb.class.php'; $conf = new Conf(); $conf->load('../../conf/database.conf'); $db = new MabiDb(); $db->init($conf->get('database.host'), $conf->get('database.user'), $conf->get('database.pass'), $conf->get('database.db')); $succs = false; $error = ''; $user = ''; $pass = ''; $pass2 = ''; if(isset($_POST['register'])) { $user = $_POST['user']; $pass = $_POST['pass']; $pass2 = $_POST['pass2']; if(!preg_match('~^[a-z0-9]{4,20}$~i', $user)) $error = 'Invalid username (4-20 characters).'; else if($pass !== $pass2) $error = 'Passwords don\'t match.'; else if(!preg_match('~^[a-z0-9]{6,24}$~i', $pass)) $error = 'Invalid password (6-24 characters).'; else if($db->accountExists($user)) $error = 'Username already exists.'; else { $db->createAccount($user, $pass); $succs = true; } } ?> <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Register - Aura</title> <link rel="stylesheet" href="../shared/css/reset.css" media="all" /> <link rel="stylesheet" href="style.css" media="all" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <!--[if IE]> <script src="../shared/js/ie.js"></script> <![endif]--> </head> <body> <a href="<?php echo basename(__FILE__) ?>"><img src="../shared/images/logo_white.png" alt="Aura"/></a> <?php if(!$succs): ?> <?php if(!empty($error)): ?> <div class="notice"> <?php echo $error ?> </div> <?php endif; ?> <form method="post" action="<?php echo basename(__FILE__) ?>"> <table> <tr> <td class="desc">Username</td> <td class="inpt"><input type="text" name="user" value="<?php echo $user ?>"/></td> </tr> <tr> <td class="desc">Password</td> <td class="inpt"><input type="password" name="pass" value="<?php echo $pass ?>"/></td> </tr> <tr> <td class="desc">Password Repeat</td> <td class="inpt"><input type="password" name="pass2" value="<?php echo $pass2 ?>"/></td> </tr> <tr> <td class="desc"></td> <td class="inpt"><input type="submit" name="register" value="Register"/></td> </tr> </table> </form> <?php else: ?> <div class="notice"> <?php echo 'Account created successfully!' ?> </div> <?php endif; ?> </body> </html>
AlexFiFi/aura
web/register/index.php
PHP
gpl-3.0
2,763
<!DOCTYPE html> <html lang="fr"> <html> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="./assets/css/mail.css"/> </head> <body bgcolor="#E6E6FA"> <?php include 'back-submit-mail.php';?> <h1 class="first">&nbsp;</h1> <?php // define variables and set to empty values $fnameErr = $lnameErr = $emailErr = $websiteErr = ""; $fname = $lname = $email = $subject = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["fname"])) { $fnameErr = "Firts name is required"; } else { $fname = test_input($_POST["fname"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$fname)) { $fnameErr = "Only letters and white space allowed"; } } if (empty($_POST["lname"])) { $lnameErr = "Last name is required"; } else { $lname = test_input($_POST["lname"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$lname)) { $lnameErr = "Only letters and white space allowed"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } if (empty($_POST["subject"])) { $subject = ""; } else { $subject = test_input($_POST["subject"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <!-- Form content --> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <span class="error">*<?php echo $fnameErr;?></span> <label for="fname">Prénom</label> <input type="text" id="fname" name="fname" placeholder="Votre prénom..."> <span class="error">*<?php echo $lnameErr;?></span> <label for="lname">Nom</label> <input type="text" id="lname" name="lname" placeholder="Votre nom..."> <span class="error">*<?php echo $emailErr;?></span> <label for="mail">Email</label> <input type="text" id="mail" name="email" placeholder="Votre email..."> <label for="country">Pays</label> <select id="country" name="country"> <option value="australia">Belgium</option> <option value="usa">USA</option> <option value="canada">Canada</option> </select> <label for="subject">Sujet</label> <textarea id="subject" name="subject" placeholder="Ecrivez quelque chose..." style="height:200px"></textarea> </form> <?php echo $fname; echo "<br>"; echo $lname; echo "<br>"; echo $email; echo "<br>"; echo $subject; echo "<br>"; ?> </body> </html>
WillemHeremans/CV
mail.php
PHP
gpl-3.0
2,850
<!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <!-- =========================================================================================== Instituto Municipal de Planeación y Competitividad de Torreón. Al usar, estudiar y copiar está aceptando los términos de uso de la información y del sitio web: http://www.trcimplan.gob.mx/terminos/terminos-informacion.html http://www.trcimplan.gob.mx/terminos/terminos-sitio.html El software que lo construye está bajo la licencia GPL versión 3. © 2014, 2015, 2016. Una copia está contenida en el archivo LICENCE al bajar desde GitHub. Plataforma de Conocimiento https://github.com/guivaloz/PlataformaDeConocimiento Agradecemos y compartimos las tecnologías abiertas y gratuitas sobre las que se basa: Morris.js https://morrisjs.github.io/morris.js/ PHP http://php.net StartBootStrap http://startbootstrap.com Twitter Bootstrap http://getbootstrap.com Descargue, aprenda y colabore con este Software Libre: GitHub IMPLAN Torreón https://github.com/TRCIMPLAN/trcimplan.github.io =========================================================================================== --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Superficie territorial medida en hectáreas."> <meta name="author" content="Dirección de Investigación Estratégica"> <meta name="keywords" content="IMPLAN, Matamoros, Recursos Naturales"> <title>Superficie en Matamoros - IMPLAN Torreón</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-XdYbMnZ/QjLh6iI4ogqCTaIjrFk87ip+ekIjefZch0Y+PvJ8CDYtEs1ipDmPorQ+" crossorigin="anonymous"> <link href="../imagenes/favicon.png" rel="shortcut icon" type="image/x-icon"> <link href="../rss.xml" rel="alternate" type="application/rss+xml" title="IMPLAN Torreón"> <link href="../css/morris.css" rel="stylesheet"> <link href="../css/plugins/metisMenu/metisMenu.min.css" rel="stylesheet"> <link href="../css/sb-admin-2.css" rel="stylesheet"> <link href="../css/plataforma-de-conocimiento.css" rel="stylesheet"> <link href="../css/trcimplan.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Questrial|Roboto+Condensed:400,700" rel="stylesheet" type="text/css"> </head> <body> <div id="wrapper"> <nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"><img class="navbar-brand-img" src="../imagenes/implan-barra-logo-chico-gris.png" alt="IMPLAN Torreón"></a> </div> <div class="navbar-default sidebar" role="navigation"> <div class="sidebar-nav navbar-collapse"> <ul class="nav" id="side-menu"> <li class="sidebar-search"> <form method="get" id="searchbox_015475140351266618625:04hulmghdys" action="http://www.trcimplan.gob.mx/buscador-resultados.html"> <input type="hidden" value="015475140351266618625:04hulmghdys" name="cx"> <input type="hidden" value="FORID:11" name="cof"> <div class="input-group custom-search-form"> <input type="text" class="form-control" placeholder="Buscar..." value="" name="s" id="s"> <span class="input-group-btn"> <button class="btn btn-default" type="submit" id="searchsubmit"><i class="fa fa-search"></i></button> </span> </div> </form> </li> <li><a href="../blog/index.html"><span class="navegacion-icono"><i class="fa fa-lightbulb-o"></i></span> Análisis Publicados</a></li> <li class="active"> <a href="#"><span class="navegacion-icono"><i class="fa fa-area-chart"></i></span> Indicadores<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li><a href="../smi/introduccion.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Introducción al S.M.I.</a></li> <li><a href="../indicadores-categorias/index.html"><span class="navegacion-icono"><i class="fa fa-th-list"></i></span> Indicadores por Categoría</a></li> <li><a href="../smi/por-region.html"><span class="navegacion-icono"><i class="fa fa-table"></i></span> Indicadores por Región</a></li> <li><a href="../smi-georreferenciados/index.html"><span class="navegacion-icono"><i class="fa fa-map-marker"></i></span> Georreferenciados</a></li> <li><a href="../smi/datos-abiertos.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Datos Abiertos</a></li> </ul> </li> <li> <a href="#"><span class="navegacion-icono"><i class="fa fa-puzzle-piece"></i></span> IBC Torreón<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li><a href="../#"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Introducción</a></li> <li><a href="../ibc-torreon/index.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Listado de Colonias</a></li> <li><a href="../#"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Mapa de Colonias</a></li> <li><a href="../#"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Datos Abiertos</a></li> </ul> </li> <li> <a href="#"><span class="navegacion-icono"><i class="fa fa-map-marker"></i></span> Información Geográfica<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li><a href="../sig/introduccion.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Introducción al S.I.G.</a></li> <li><a href="../sig-planes/index.html"><span class="navegacion-icono"><i class="fa fa-server"></i></span> Planes</a></li> <li><a href="../sig-mapas-torreon/index.html"><span class="navegacion-icono"><i class="fa fa-map-marker"></i></span> S.I.G. de Torreón</a></li> <li><a href="../sig-mapas-torreon/zonificacion-secundaria.html"><span class="navegacion-icono"><i class="fa fa-map-marker"></i></span> Zonificación Secundaria</a></li> </ul> </li> <li> <a href="#"><span class="navegacion-icono"><i class="fa fa-sun-o"></i></span> Plan Estratégico Metropolitano<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li><a href="../plan-estrategico-metropolitano/introduccion.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Qué es el P.E.M.</a></li> <li><a href="../plan-estrategico-metropolitano/metodologia.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Metodología</a></li> <li><a href="../plan-estrategico-metropolitano/descripcion-del-proceso.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Descripción del Proceso</a></li> </ul> </li> <li> <a href="#"><span class="navegacion-icono"><i class="fa fa-check-square"></i></span> Banco de Proyectos<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li><a href="../proyectos/proyectos-por-ejes.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Proyectos por Ejes</a></li> <li><a href="../proyectos/cartera-pem.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Cartera P.E.M.</a></li> <li><a href="../proyectos/planes-y-programas.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Planes y Programas</a></li> </ul> </li> <li><a href="../investigaciones/index.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Investigaciones</a></li> <li> <a href="#"><span class="navegacion-icono"><i class="fa fa-building-o"></i></span> Institucional<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li><a href="../institucional/vision-mision.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Visión / Misión</a></li> <li><a href="../institucional/mensaje-director.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Mensaje del Director</a></li> <li><a href="../autores/index.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Quienes Somos</a></li> <li><a href="../institucional/estructura-organica.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Estructura Orgánica</a></li> <li><a href="../institucional/modelo-operativo-universal.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Modelo Operativo Univ.</a></li> <li><a href="../institucional/reglamentos.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Reglamentos</a></li> <li><a href="../institucional/informacion-financiera.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Información Financiera</a></li> <li><a href="http://www.icai.org.mx:8282/ipo/dependencia.php?dep=178" target="_blank"><span class="navegacion-icono"><i class="fa fa-external-link"></i></span> Transparencia</a></li> </ul> </li> <li><a href="../consejo-directivo/integrantes.html"><span class="navegacion-icono"><i class="fa fa-users"></i></span> Consejo Directivo</a></li> <li><a href="../sala-prensa/index.html"><span class="navegacion-icono"><i class="fa fa-comments"></i></span> Sala de Prensa</a></li> <li><a href="../preguntas-frecuentes/preguntas-frecuentes.html"><span class="navegacion-icono"><i class="fa fa-question"></i></span> Preguntas Frecuentes</a></li> <li> <a href="#"><span class="navegacion-icono"><i class="fa fa-files-o"></i></span> Términos de Uso<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li><a href="../terminos/terminos-informacion.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> De la información</a></li> <li><a href="../terminos/terminos-sitio.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Del sitio web</a></li> <li><a href="../terminos/privacidad.html"><span class="navegacion-icono"><i class="fa fa-file-text-o"></i></span> Aviso de Privacidad</a></li> </ul> </li> <li> <a href="#"><span class="navegacion-icono"><i class="fa fa-phone"></i></span> Contacto<span class="fa arrow"></span></a> <ul class="nav nav-second-level"> <li><a href="../contacto/contacto.html"><span class="navegacion-icono"><i class="fa fa-phone"></i></span> Medios de contacto</a></li> <li><a href="../#"><span class="navegacion-icono"><i class="fa fa-external-link"></i></span> Comentarios y Sugerencias</a></li> </ul> </li> </ul> </div> </div> </nav> <div id="page-wrapper"> <div class="cuerpo"> <article><div itemscope itemtype="http://schema.org/Article"> <div class="encabezado" style="background-color:#CA198A;"> <h1 itemprop="name">Superficie en Matamoros</h1> <div class="encabezado-descripcion" itemprop="description">Superficie territorial medida en hectáreas.</div> <div class="encabezado-autor-fecha"> Por <span itemprop="author">Dirección de Investigación Estratégica</span> - <meta itemprop="datePublished" content="2016-03-09T10:53">09/03/2016 10:53 </div> </div> <meta itemprop="image" alt="Superficie en Matamoros" src="../smi/introduccion/imagen.jpg"> <div itemprop="articleBody"> <ul class="nav nav-tabs lenguetas" id="smi-indicador"> <li><a href="#smi-indicador-datos" data-toggle="tab">Datos</a></li> <li><a href="#smi-indicador-otras_regiones" data-toggle="tab">Otras regiones</a></li> </ul> <div class="tab-content lengueta-contenido"> <div class="tab-pane" id="smi-indicador-datos"> <h3>Información recopilada</h3> <table class="table table-hover table-bordered matriz"> <thead> <tr> <th>Fecha</th> <th>Dato</th> <th>Fuente</th> <th>Notas</th> </tr> </thead> <tbody> <tr> <td>31/12/2010</td> <td>82,163.7300</td> <td>INEGI</td> <td></td> </tr> </tbody> </table> <p><b>Unidad:</b> Hectáreas.</p> </div> <div class="tab-pane" id="smi-indicador-otras_regiones"> <h3>Gráfica con los últimos datos de Superficie</h3> <div id="graficaOtrasRegiones" class="grafica"></div> <h3>Últimos datos de Superficie</h3> <table class="table table-hover table-bordered matriz"> <thead> <tr> <th>Región</th> <th>Fecha</th> <th>Dato</th> <th>Fuente</th> <th>Notas</th> </tr> </thead> <tbody> <tr> <td>Torreón</td> <td>2010-12-31</td> <td>124,199.7500</td> <td>INEGI</td> <td></td> </tr> <tr> <td>Gómez Palacio</td> <td>2010-12-31</td> <td>84,546.5800</td> <td>INEGI</td> <td></td> </tr> <tr> <td>Lerdo</td> <td>2010-12-31</td> <td>211,889.3200</td> <td>INEGI</td> <td></td> </tr> <tr> <td>Matamoros</td> <td>2010-12-31</td> <td>82,163.7300</td> <td>INEGI</td> <td></td> </tr> <tr> <td>La Laguna</td> <td>2010-12-31</td> <td>502,799.3800</td> <td>INEGI</td> <td>El indicador hace referencia a los cuatro municipios que conforman la Zona Metropolitana de la Laguna: Torreón, Matamoros, Gómez Palacio y Lerdo.</td> </tr> </tbody> </table> </div> </div> </div> <article><div itemprop="contentLocation" itemscope itemtype="http://schema.org/Place""> <article><div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress""> <div class="direccion"> <span itemprop="addressLocality">Matamoros</span>, <span itemprop="addressRegion">Coahuila de Zaragoza</span>. <meta itemprop="addressCountry" content="MX">México. </div> </div></article> </div></article> </div></article> <div class="contenido-social"> <h5>Compartir en Redes Sociales</h5> <a href="https://twitter.com/share" class="twitter-share-button" data-via="trcimplan" data-lang="es">Twittear</a> <iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.trcimplan.gob.mx%2Findicadores-matamoros%2Fsustentabilidad-superficie.html&amp;width=300&amp;layout=button_count&amp;action=like&amp;show_faces=true&amp;share=false&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:300px; height:21px;" allowTransparency="true"></iframe> </div> </div> <div class="mapa-inferior"> <div class="row"> <div class="col-md-8"> <a href="../index.html"><img class="img-responsive mapa-inferior-logo" src="../imagenes/implan-transparente-gris.png" alt="IMPLAN Torreón"></a> </div> <div class="col-md-4"> <div class="pull-right redes-sociales"> <a class="fa fa-twitter-square" href="http://www.twitter.com/trcimplan" target="_blank"></a> <a class="fa fa-facebook-square" href="https://facebook.com/trcimplan" target="_blank"></a> <a class="fa fa-google-plus-square" href="https://plus.google.com/106220426241750550649" target="_blank"></a> <a class="fa fa-github-square" href="https://github.com/TRCIMPLAN" target="_blank"></a> <a class="fa fa-rss-square" href="../rss.xml"></a> </div> </div> </div> </div> </div> </div> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script src="../js/raphael-min.js"></script> <script src="../js/morris.min.js"></script> <script src="../js/plugins/metisMenu/metisMenu.min.js"></script> <script src="../js/sb-admin-2.js"></script> <script> // LENGUETA smi-indicador-otras_regiones $('#smi-indicador a[href="#smi-indicador-otras_regiones"]').on('shown.bs.tab', function(e){ // Gráfica if (typeof vargraficaOtrasRegiones === 'undefined') { vargraficaOtrasRegiones = Morris.Bar({ element: 'graficaOtrasRegiones', data: [{ region: 'Torreón', dato: 124199.7500 },{ region: 'Gómez Palacio', dato: 84546.5800 },{ region: 'Lerdo', dato: 211889.3200 },{ region: 'Matamoros', dato: 82163.7300 },{ region: 'La Laguna', dato: 502799.3800 }], xkey: 'region', ykeys: ['dato'], labels: ['Dato'], barColors: ['#FF5B02'] }); } }); // TWITTER BOOTSTRAP TABS, ESTABLECER QUE LA LENGÜETA ACTIVA ES smi-indicador-datos $(document).ready(function(){ $('#smi-indicador a[href="#smi-indicador-datos"]').tab('show') }); </script> <script> // Twitter !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); </script> <script> // Google Analytics (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-58290501-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
TRCIMPLAN/beta
indicadores-matamoros/sustentabilidad-superficie.html
HTML
gpl-3.0
19,496
# Daemonizable Commands for Symfony [![Build Status of Master](https://travis-ci.org/mac-cain13/daemonizable-command.png?branch=master)](https://travis-ci.org/mac-cain13/daemonizable-command) **A small bundle to create endless running commands with Symfony.** These endless running commands are very easy to daemonize with something like Upstart or systemd. ## Why do I need this? Because you want to create long running PHP/Symfony processes! For example to send mails with large attachment, process (delayed) payments or generate large PDF reports. They query the database or read from a message queue and do their job. This bundle makes it very easy to create such processes as Symfony commands. ## How to install? Use composer to include it into your Symfony project: `composer require wrep/daemonizable-command` ### What version to use? Symfony did make some breaking changes, so you should make sure to use a compatible bundle version: * Version 2.1.* for Symfony 4.0 and higher * Version 2.0.* for Symfony 3.0 - 3.4 * Version 1.3.* for Symfony 2.8 When upgrading, please consult the [changelog](Changelog.md) to see what could break your code. ## How to use? Just create a Symfony command that extends from `EndlessCommand` and off you go. Here is a minimal example: ```php namespace Acme\DemoBundle\Command; use Wrep\Daemonizable\Command\EndlessCommand; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputInterface; class MinimalDemoCommand extends EndlessCommand { // This is just a normal Command::configure() method protected function configure() { $this->setName('acme:minimaldemo') ->setDescription('An EndlessCommand implementation example'); } // Execute will be called in a endless loop protected function execute(InputInterface $input, OutputInterface $output) { // Tell the user what we're going to do. // This will be a NullOutput if the user doesn't want any output at all, // so you don't have to do any checks, just always write to the output. $output->write('Updating timestamp... '); // Do some work file_put_contents( '/tmp/acme-timestamp.txt', time() ); // Tell the user we're done $output->writeln('done'); } } ``` Run it with `php app/console acme:minimaldemo`. An [example with all the bells and whistles](examples/ExampleCommand.php) is also available and gives a good overview of best practices and how to do some basic things. ## How to daemonize? Alright, now we have an endless running command *in the foreground*. Usefull for debugging, useless in production! So how do we make this thing a real daemon? You should use [systemd](http://www.freedesktop.org/wiki/Software/systemd) to daemonize the command. They provide very robust daemonization, start your daemon on a reboot and also monitor the process so it will try to restart it in the case of a crash. If you can't use Upstart or systemd, you can use `.lock` file with [LockHandler](http://symfony.com/doc/current/components/filesystem/lock_handler.html) with [crontab](https://wikipedia.org/wiki/Cron) wich start script every minute. An [example Upstart script](examples/example-daemon.conf) is available, place your script in `/etc/init/` and start the daemon with `start example-daemon`. The name of the `.conf`-file will be the name of the daemon. A systemd example is not yet available, but it shouldn't be that hard to [figure out](http://patrakov.blogspot.nl/2011/01/writing-systemd-service-files.html). ## Command line switches A few switches are available by default to make life somewhat easier: * Use `-q` to suppress all output * Use `--run-once` to only run the command once, usefull for debugging * Use `--detect-leaks` to print a memory usage report after each run, read more in the next section ## Memory usage and leaks Memory usage is very important for long running processes. Symfony is not the smallest framework around and if you leak some memory in your execute method your daemon will crash! The `EndlessCommand` classes have been checked for memory leaks, but you should also check your own code. ### How to prevent leaks? Always start your command with the `-e prod --no-debug` flags. This disables all debugging features of Symfony that will eat up more and more memory. Do not use Monolog in Symfony 2.2 and lower, there is a [bug in the MonologBundle](https://github.com/symfony/MonologBundle/issues/37) that starts the debughandler even though you disable the profiler. This eats up your memory. Note that this is [fixed](https://github.com/symfony/MonologBundle/commit/1fc0864a9344b15a04ed90612a91cf8e5b8fb305) in Symfony 2.3 and up. Make sure you cleanup in the `execute`-method, make sure you're not appending data to an array every iteration or leave sockets/file handles open for example. In case you are using the fingers-crossed handler in Monolog, this will also be a source of memory leaks. The idea of this handler is to keep all below-threshold log entries in memory and only flush those in case of an above-threshold entry. You can still use the fingers-crossed handler as long as you manually flush it at the end of the `execute`-method: ``` foreach ($this->getContainer()->get('logger')->getHandlers() as $handler) { if ($handler instanceof FingersCrossedHandler) { $handler->clear(); } } ``` ### Detecting memory leaks Run your command with the `--detect-leaks` flag. Remember that debug mode will eat memory so you'll need to run with `-e prod --no-debug --detect-leaks` for accurate reports. After each iteration a memory report like this is printed on your console: ``` == MEMORY USAGE == Peak: 30038.86 KByte stable (0.000 %) Cur.: 29856.46 KByte stable (0.000 %) ``` The first 3 iterations may be unstable in terms of memory usage, but after that it should be stable. *Even a slight increase of memory usage will crash your daemon over time!* If you see an increase/stable/decrease loop you're probably save. It could be the garabage collector not cleaning up, you can fix this by using unset on variables to cleanup the memory yourself. ### Busting some myths Calling `gc_collect_cycles()` will not help to resolve leaks. PHP will cleanup memory right in time all by itself, calling this method may slow down leaking memory, but will not solve it. Also it makes spotting leaks harder, so just don't use it. If you run Symfony in production and non-debug mode it will not leak memory and you do not have to disable any SQL loggers. The only leak I runned into is the one in the MonologBundle mentioned above. ### Working with Doctrine For reasons EndlessContainerAwareCommand clears after each Iteration Doctrine's EntityManager. Be aware of that. You can override finishIteration() to avoid this behaviour but you have to handle the EM on your own then.
FreePBX/framework
amp_conf/htdocs/admin/libraries/Composer/vendor/wrep/daemonizable-command/README.md
Markdown
gpl-3.0
6,822
{-# LANGUAGE ScopedTypeVariables #-} import Bench import Bench.Triangulations main = print (qVertexSolBench trs)
DanielSchuessler/hstri
scratch6.hs
Haskell
gpl-3.0
115
// // Copyleft RIME Developers // License: GPLv3 // // 2013-04-18 GONG Chen <[email protected]> // #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <rime/dict/table_db.h> #include <rime/dict/user_db.h> // Rime table entry format: // phrase <Tab> code [ <Tab> weight ] // for multi-syllable phrase, code is a space-separated list of syllables // weight is a double precision float, defaulting to 0.0 namespace rime { static bool rime_table_entry_parser(const Tsv& row, std::string* key, std::string* value) { if (row.size() < 2 || row[0].empty() || row[1].empty()) { return false; } std::string code(row[1]); boost::algorithm::trim(code); *key = code + " \t" + row[0]; UserDbValue v; if (row.size() >= 3 && !row[2].empty()) { try { v.commits = boost::lexical_cast<int>(row[2]); const double kS = 1e8; v.dee = (v.commits + 1) / kS; } catch (...) { } } *value = v.Pack(); return true; } static bool rime_table_entry_formatter(const std::string& key, const std::string& value, Tsv* tsv) { Tsv& row(*tsv); // key ::= code <space> <Tab> phrase boost::algorithm::split(row, key, boost::algorithm::is_any_of("\t")); if (row.size() != 2 || row[0].empty() || row[1].empty()) return false; UserDbValue v(value); if (v.commits < 0) // deleted entry return false; boost::algorithm::trim(row[0]); // remove trailing space row[0].swap(row[1]); row.push_back(boost::lexical_cast<std::string>(v.commits)); return true; } const TextFormat TableDb::format = { rime_table_entry_parser, rime_table_entry_formatter, "Rime table", }; TableDb::TableDb(const std::string& name) : TextDb(name + ".txt", "tabledb", TableDb::format) { } // StableDb StableDb::StableDb(const std::string& name) : TableDb(name) {} bool StableDb::Open() { if (loaded()) return false; if (!Exists()) { LOG(INFO) << "stabledb '" << name() << "' does not exist."; return false; } return TableDb::OpenReadOnly(); } } // namespace rime
jinntrance/librime
src/dict/table_db.cc
C++
gpl-3.0
2,233