code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/*#include "StdAfx.h"*/ #include "Sqlite3Ex.h" #include <string.h> Sqlite3Ex::Sqlite3Ex(void) :m_pSqlite(NULL) { memset(m_szErrMsg, 0x00, ERRMSG_LENGTH); } Sqlite3Ex::~Sqlite3Ex(void) { } bool Sqlite3Ex::Open(const wchar_t* szDbPath) { int nRet = sqlite3_open16(szDbPath, &m_pSqlite); if (SQLITE_OK != nRet) { SetErrMsg(sqlite3_errmsg(m_pSqlite)); return false; } return true; } bool Sqlite3Ex::Close() { bool bRet = false; if (SQLITE_OK == sqlite3_close(m_pSqlite)) { bRet = true; m_pSqlite = NULL; } return bRet; } bool Sqlite3Ex::CreateTable(const char* szTableName, int nColNum, Sqlite3ExColumnAttrib emColAttrib, ...) { if (NULL == szTableName || 0 == strlen(szTableName) || 0 >= nColNum) { SetErrMsg("Parameter is invalid."); return false; } std::string strSql("CREATE TABLE "); strSql += szTableName; strSql += "("; va_list ap; va_start(ap, nColNum); char szTmp[SQLITE3EX_COLSTRFORPARAM_LEN]; for (int i = 0; i != nColNum; ++i) { ::memset(szTmp, 0x00, SQLITE3EX_COLSTRFORPARAM_LEN); Sqlite3ExColumnAttrib & ta = va_arg(ap, Sqlite3ExColumnAttrib); ta.GetStringForSQL(szTmp); strSql += szTmp; strSql += ","; } va_end(ap); *(strSql.end() - 1) = ')'; return Sqlite3Ex_ExecuteNonQuery(strSql.c_str()); } bool Sqlite3Ex::BegTransAction() { return Sqlite3Ex_ExecuteNonQuery("BEGIN TRANSACTION"); } bool Sqlite3Ex::EndTransAction() { return Sqlite3Ex_ExecuteNonQuery("END TRANSACTION"); } bool Sqlite3Ex::Sqlite3Ex_Exec(const char* szQuery, LPEXEC_CALLBACK callback, void* pFirstParam) { char* szErrMsg = NULL; int nRet = sqlite3_exec(m_pSqlite, szQuery, callback, pFirstParam, &szErrMsg); if (SQLITE_OK != nRet) { SetErrMsg(szErrMsg); sqlite3_free(szErrMsg); return false; } return true; } bool Sqlite3Ex::GetTableNames(std::vector<std::string> & vecTableNames) { char* szErrMsg = NULL; char** pRetData = NULL; int nRow, nCol; int nRet = sqlite3_get_table(m_pSqlite, "SELECT name FROM sqlite_master WHERE type='table'", &pRetData, &nRow, &nCol, &szErrMsg); if (SQLITE_OK != nRet) { SetErrMsg(szErrMsg); sqlite3_free(szErrMsg); return false; } vecTableNames.resize(nRow); for (int i = 1; i <= nRow; ++i) //i´Ó1¿ªÊ¼,ÒÔΪË÷Òý0´¦µÄ¹Ì¶¨ÖµÊÇ"name" vecTableNames[i - 1] = pRetData[i]; sqlite3_free_table(pRetData); return true; } ////////////////////////////////////////////////////////////////////////// int Sqlite3Ex::ExecuteReader_CallBack(void* pFirstParam, int iColNum, char** pRecordArr, char** pColNameArr) { if (iColNum <= 0) return 0; Sqlite3Ex_Reader* pReader = (Sqlite3Ex_Reader*)pFirstParam; if (NULL == pReader) return 0; std::vector<std::string>* pVecLine = new std::vector<std::string>; pVecLine->resize(iColNum); for (int i = 0; i != iColNum; ++i) (*pVecLine)[i] = pRecordArr[i]; pReader->m_vecResult.push_back(pVecLine); return 0; } bool Sqlite3Ex::Sqlite3Ex_ExecuteReader(const char* szQuery, Sqlite3Ex_Reader* pReader) { char* szErrMsg = NULL; if (SQLITE_OK == sqlite3_exec(m_pSqlite, szQuery, ExecuteReader_CallBack, (void*)pReader, &szErrMsg)) return true; SetErrMsg(szErrMsg); sqlite3_free(szErrMsg); return false; } bool Sqlite3Ex::Sqlite3Ex_ExecuteNonQuery(const char* szQuery) { char* szErrMsg = NULL; if (SQLITE_OK == sqlite3_exec(m_pSqlite, szQuery, NULL, NULL, &szErrMsg)) return true; SetErrMsg(szErrMsg); sqlite3_free(szErrMsg); return false; } bool Sqlite3Ex::IsOpen() { if (!m_pSqlite) return false; return true; } //////////////////////////////////////////////////////////////////////////
CUCKOO0615/CUCKOO0615_Utils
CUCKOO0615_Utils/Sqlite3Ex.cpp
C++
lgpl-3.0
4,082
<?php /** * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0 * @copyright Aimeos (aimeos.org), 2018-2022 */ namespace Aimeos\Admin\JQAdm\Type\Media\Property; class StandardTest extends \PHPUnit\Framework\TestCase { private $context; private $object; private $view; protected function setUp() : void { $this->view = \TestHelper::view(); $this->context = \TestHelper::context(); $this->object = new \Aimeos\Admin\JQAdm\Type\Media\Property\Standard( $this->context ); $this->object = new \Aimeos\Admin\JQAdm\Common\Decorator\Page( $this->object, $this->context ); $this->object->setAimeos( \TestHelper::getAimeos() ); $this->object->setView( $this->view ); } protected function tearDown() : void { unset( $this->object, $this->view, $this->context ); } public function testCreate() { $result = $this->object->create(); $this->assertStringContainsString( 'media/property', $result ); $this->assertEmpty( $this->view->get( 'errors' ) ); } public function testCreateException() { $object = $this->getMockBuilder( \Aimeos\Admin\JQAdm\Type\Media\Property\Standard::class ) ->setConstructorArgs( array( $this->context, \TestHelper::getTemplatePaths() ) ) ->setMethods( array( 'getSubClients' ) ) ->getMock(); $object->expects( $this->once() )->method( 'getSubClients' ) ->will( $this->throwException( new \RuntimeException() ) ); $object->setView( $this->getViewNoRender() ); $object->create(); } public function testCopy() { $manager = \Aimeos\MShop::create( $this->context, 'media/property/type' ); $param = ['type' => 'unittest', 'id' => $manager->find( 'size', [], 'media' )->getId()]; $helper = new \Aimeos\MW\View\Helper\Param\Standard( $this->view, $param ); $this->view->addHelper( 'param', $helper ); $result = $this->object->copy(); $this->assertStringContainsString( 'size', $result ); } public function testCopyException() { $object = $this->getMockBuilder( \Aimeos\Admin\JQAdm\Type\Media\Property\Standard::class ) ->setConstructorArgs( array( $this->context, \TestHelper::getTemplatePaths() ) ) ->setMethods( array( 'getSubClients' ) ) ->getMock(); $object->expects( $this->once() )->method( 'getSubClients' ) ->will( $this->throwException( new \RuntimeException() ) ); $object->setView( $this->getViewNoRender() ); $object->copy(); } public function testDelete() { $this->assertNull( $this->getClientMock( ['redirect'], false )->delete() ); } public function testDeleteException() { $object = $this->getClientMock( ['getSubClients', 'search'] ); $object->expects( $this->once() )->method( 'getSubClients' ) ->will( $this->throwException( new \RuntimeException() ) ); $object->expects( $this->once() )->method( 'search' ); $object->delete(); } public function testGet() { $manager = \Aimeos\MShop::create( $this->context, 'media/property/type' ); $param = ['type' => 'unittest', 'id' => $manager->find( 'size', [], 'media' )->getId()]; $helper = new \Aimeos\MW\View\Helper\Param\Standard( $this->view, $param ); $this->view->addHelper( 'param', $helper ); $result = $this->object->get(); $this->assertStringContainsString( 'size', $result ); } public function testGetException() { $object = $this->getMockBuilder( \Aimeos\Admin\JQAdm\Type\Media\Property\Standard::class ) ->setConstructorArgs( array( $this->context, \TestHelper::getTemplatePaths() ) ) ->setMethods( array( 'getSubClients' ) ) ->getMock(); $object->expects( $this->once() )->method( 'getSubClients' ) ->will( $this->throwException( new \RuntimeException() ) ); $object->setView( $this->getViewNoRender() ); $object->get(); } public function testSave() { $manager = \Aimeos\MShop::create( $this->context, 'media/property/type' ); $param = array( 'type' => 'unittest', 'item' => array( 'media.property.type.id' => '', 'media.property.type.status' => '1', 'media.property.type.domain' => 'product', 'media.property.type.code' => 'jqadm@test', 'media.property.type.label' => 'jqadm test', ), ); $helper = new \Aimeos\MW\View\Helper\Param\Standard( $this->view, $param ); $this->view->addHelper( 'param', $helper ); $result = $this->object->save(); $manager->delete( $manager->find( 'jqadm@test', [], 'product' )->getId() ); $this->assertEmpty( $this->view->get( 'errors' ) ); $this->assertNull( $result ); } public function testSaveException() { $object = $this->getMockBuilder( \Aimeos\Admin\JQAdm\Type\Media\Property\Standard::class ) ->setConstructorArgs( array( $this->context, \TestHelper::getTemplatePaths() ) ) ->setMethods( array( 'fromArray' ) ) ->getMock(); $object->expects( $this->once() )->method( 'fromArray' ) ->will( $this->throwException( new \RuntimeException() ) ); $object->setView( $this->getViewNoRender() ); $object->save(); } public function testSearch() { $param = array( 'type' => 'unittest', 'locale' => 'de', 'filter' => array( 'key' => array( 0 => 'media.property.type.code' ), 'op' => array( 0 => '==' ), 'val' => array( 0 => 'size' ), ), 'sort' => array( '-media.property.type.id' ), ); $helper = new \Aimeos\MW\View\Helper\Param\Standard( $this->view, $param ); $this->view->addHelper( 'param', $helper ); $result = $this->object->search(); $this->assertStringContainsString( '>size<', $result ); } public function testSearchException() { $object = $this->getMockBuilder( \Aimeos\Admin\JQAdm\Type\Media\Property\Standard::class ) ->setConstructorArgs( array( $this->context, \TestHelper::getTemplatePaths() ) ) ->setMethods( array( 'initCriteria' ) ) ->getMock(); $object->expects( $this->once() )->method( 'initCriteria' ) ->will( $this->throwException( new \RuntimeException() ) ); $object->setView( $this->getViewNoRender() ); $object->search(); } public function testGetSubClientInvalid() { $this->expectException( \Aimeos\Admin\JQAdm\Exception::class ); $this->object->getSubClient( '$unknown$' ); } public function testGetSubClientUnknown() { $this->expectException( \Aimeos\Admin\JQAdm\Exception::class ); $this->object->getSubClient( 'unknown' ); } public function getClientMock( $methods, $real = true ) { $object = $this->getMockBuilder( \Aimeos\Admin\JQAdm\Type\Media\Property\Standard::class ) ->setConstructorArgs( array( $this->context, \TestHelper::getTemplatePaths() ) ) ->setMethods( (array) $methods ) ->getMock(); $object->setAimeos( \TestHelper::getAimeos() ); $object->setView( $this->getViewNoRender( $real ) ); return $object; } protected function getViewNoRender( $real = true ) { $view = $this->getMockBuilder( \Aimeos\MW\View\Standard::class ) ->setConstructorArgs( array( [] ) ) ->setMethods( array( 'render' ) ) ->getMock(); $manager = \Aimeos\MShop::create( $this->context, 'media/property/type' ); $param = ['site' => 'unittest', 'id' => $real ? $manager->find( 'size', [], 'media' )->getId() : -1]; $helper = new \Aimeos\MW\View\Helper\Param\Standard( $view, $param ); $view->addHelper( 'param', $helper ); $helper = new \Aimeos\MW\View\Helper\Config\Standard( $view, $this->context->config() ); $view->addHelper( 'config', $helper ); $helper = new \Aimeos\MW\View\Helper\Access\Standard( $view, [] ); $view->addHelper( 'access', $helper ); return $view; } }
aimeos/ai-admin-jqadm
tests/Admin/JQAdm/Type/Media/Property/StandardTest.php
PHP
lgpl-3.0
7,433
package repack.org.bouncycastle.crypto.agreement; import repack.org.bouncycastle.crypto.BasicAgreement; import repack.org.bouncycastle.crypto.CipherParameters; import repack.org.bouncycastle.crypto.params.ECDomainParameters; import repack.org.bouncycastle.crypto.params.ECPrivateKeyParameters; import repack.org.bouncycastle.crypto.params.ECPublicKeyParameters; import repack.org.bouncycastle.crypto.params.MQVPrivateParameters; import repack.org.bouncycastle.crypto.params.MQVPublicParameters; import repack.org.bouncycastle.math.ec.ECAlgorithms; import repack.org.bouncycastle.math.ec.ECConstants; import repack.org.bouncycastle.math.ec.ECPoint; import java.math.BigInteger; public class ECMQVBasicAgreement implements BasicAgreement { MQVPrivateParameters privParams; public void init( CipherParameters key) { this.privParams = (MQVPrivateParameters) key; } public BigInteger calculateAgreement(CipherParameters pubKey) { MQVPublicParameters pubParams = (MQVPublicParameters) pubKey; ECPrivateKeyParameters staticPrivateKey = privParams.getStaticPrivateKey(); ECPoint agreement = calculateMqvAgreement(staticPrivateKey.getParameters(), staticPrivateKey, privParams.getEphemeralPrivateKey(), privParams.getEphemeralPublicKey(), pubParams.getStaticPublicKey(), pubParams.getEphemeralPublicKey()); return agreement.getX().toBigInteger(); } // The ECMQV Primitive as described in SEC-1, 3.4 private ECPoint calculateMqvAgreement( ECDomainParameters parameters, ECPrivateKeyParameters d1U, ECPrivateKeyParameters d2U, ECPublicKeyParameters Q2U, ECPublicKeyParameters Q1V, ECPublicKeyParameters Q2V) { BigInteger n = parameters.getN(); int e = (n.bitLength() + 1) / 2; BigInteger powE = ECConstants.ONE.shiftLeft(e); // The Q2U public key is optional ECPoint q; if(Q2U == null) { q = parameters.getG().multiply(d2U.getD()); } else { q = Q2U.getQ(); } BigInteger x = q.getX().toBigInteger(); BigInteger xBar = x.mod(powE); BigInteger Q2UBar = xBar.setBit(e); BigInteger s = d1U.getD().multiply(Q2UBar).mod(n).add(d2U.getD()).mod(n); BigInteger xPrime = Q2V.getQ().getX().toBigInteger(); BigInteger xPrimeBar = xPrime.mod(powE); BigInteger Q2VBar = xPrimeBar.setBit(e); BigInteger hs = parameters.getH().multiply(s).mod(n); // ECPoint p = Q1V.getQ().multiply(Q2VBar).add(Q2V.getQ()).multiply(hs); ECPoint p = ECAlgorithms.sumOfTwoMultiplies( Q1V.getQ(), Q2VBar.multiply(hs).mod(n), Q2V.getQ(), hs); if(p.isInfinity()) { throw new IllegalStateException("Infinity is not a valid agreement value for MQV"); } return p; } }
SafetyCulture/DroidText
app/src/main/java/bouncycastle/repack/org/bouncycastle/crypto/agreement/ECMQVBasicAgreement.java
Java
lgpl-3.0
2,651
/** * Copyright (C) 2015 Łukasz Tomczak <lksztmczk@gmail.com>. * * This file is part of OpenInTerminal plugin. * * OpenInTerminal plugin 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. * * OpenInTerminal plugin 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 OpenInTerminal plugin. If not, see <http://www.gnu.org/licenses/>. */ package settings; /** * @author Łukasz Tomczak <lksztmczk@gmail.com> */ public class OpenInTerminalSettingsState { private String terminalCommand; private String terminalCommandOptions; public OpenInTerminalSettingsState() { } public OpenInTerminalSettingsState(String terminalCommand, String terminalCommandOptions) { this.terminalCommand = terminalCommand; this.terminalCommandOptions = terminalCommandOptions; } public String getTerminalCommand() { return terminalCommand; } public void setTerminalCommand(String terminalCommand) { this.terminalCommand = terminalCommand; } public String getTerminalCommandOptions() { return terminalCommandOptions; } public void setTerminalCommandOptions(String terminalCommandOptions) { this.terminalCommandOptions = terminalCommandOptions; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OpenInTerminalSettingsState that = (OpenInTerminalSettingsState) o; if (!terminalCommand.equals(that.terminalCommand)) return false; return terminalCommandOptions.equals(that.terminalCommandOptions); } @Override public int hashCode() { int result = terminalCommand.hashCode(); result = 31 * result + terminalCommandOptions.hashCode(); return result; } }
luktom/OpenInTerminal
src/main/java/settings/OpenInTerminalSettingsState.java
Java
lgpl-3.0
2,288
<?php namespace pocketmine\item; class Melon extends Food{ public function __construct($meta = 0, $count = 1){ parent::__construct(self::MELON, $meta, $count, "Melon"); } public function getFoodRestore(){ return 2; } public function getSaturationRestore(){ return 1.2; } }
ClearSkyTeam/ClearSky
src/pocketmine/item/Melon.php
PHP
lgpl-3.0
289
require 'support/matchers/type'
ehannes/fortnox-api
spec/support/matchers.rb
Ruby
lgpl-3.0
32
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AlterUsersTable2 extends Migration { /** * Run the migrations. * * Here, we are adding a new column to the users table called "age_range" * * They types of values we store in here will be: * - under_18 * - 18_24 * - etc. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('age_range')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn(['age_range']); }); } }
travishathaway/canopy-story
database/migrations/2017_07_24_011059_alter_users_table_2.php
PHP
lgpl-3.0
843
package org.ocbc.utils; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; public class request { public static JSONObject get(String url, HashMap<String, String> headers) { BufferedReader in = null; StringBuffer response = null; try { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); for (String key : headers.keySet()) { con.setRequestProperty(key, headers.get(key)); } in = new BufferedReader(new InputStreamReader(con.getInputStream())); response = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch(Exception exception) { System.out.println(exception); return null; } return new JSONObject(response.toString()); } }
connect2ocbc/jocbc
src/main/java/org/ocbc/utils/request.java
Java
lgpl-3.0
1,151
<?php /** * * Copyright (c) 2014 gfg-development * * @link http://www.gfg-development.de * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL */ $GLOBALS['TL_LANG']['tl_linkslist_list']['title_legend'] = 'Titel'; $GLOBALS['TL_LANG']['tl_linkslist_list']['config_legend'] = 'Einstellungen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['name'][0] = 'Titel'; $GLOBALS['TL_LANG']['tl_linkslist_list']['name'][1] = 'Geben Sie hier den Linklist Titel ein.'; $GLOBALS['TL_LANG']['tl_linkslist_list']['new'][0] = 'Neue Linkliste'; $GLOBALS['TL_LANG']['tl_linkslist_list']['new'][1] = 'Eine neue Linkliste anlegen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['edit'][0] = 'Linkliste bearbeiten'; $GLOBALS['TL_LANG']['tl_linkslist_list']['edit'][1] = 'Linkliste ID %s bearbeiten'; $GLOBALS['TL_LANG']['tl_linkslist_list']['delete'][0] = 'Linkliste löschen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['delete'][1] = 'Linkliste ID %s löchen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['show'][0] = 'Linklistendetails'; $GLOBALS['TL_LANG']['tl_linkslist_list']['show'][1] = 'Details der Linkliste ID %s anzeigen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['target'][0] = 'Links in neuem Fenster öffnen'; $GLOBALS['TL_LANG']['tl_linkslist_list']['target'][1] = 'Bitte wählen sie aus, ob die Links in einem neuen Fenster geöffnet werden sollen (target="_blank").'; ?>
gfg-development/linkslist
languages/de/tl_linkslist_list.php
PHP
lgpl-3.0
1,409
namespace MoCap.Manager { class Dispatcher : IComMsg { } }
christiansax/MoCap
PlexByte.App.MoCap.Manager/Manager/Dispatcher.cs
C#
lgpl-3.0
74
/********************************************************************** * Copyright (c) 2010, j. montgomery * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * + Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * + Redistributions in binary form must reproduce the above copyright* * notice, this list of conditions and the following disclaimer * * in the documentation and/or other materials provided with the * * distribution. * * * * + Neither the name of j. montgomery's employer nor the names of * * its contributors may be used to endorse or promote products * * derived from this software without specific prior written * * permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS* * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,* * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,* * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED* * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ using System; using System.IO; using System.Net; using System.Net.Sockets; using DnDns.Records; using DnDns.Enums; namespace DnDns.Query { /// <summary> /// Summary description for DnsQueryResponse. /// </summary> public class DnsQueryResponse : DnsQueryBase { #region Fields private DnsQueryRequest _queryRequest = new DnsQueryRequest(); private IDnsRecord[] _answers; private IDnsRecord[] _authoritiveNameServers; private IDnsRecord[] _additionalRecords; private int _bytesReceived = 0; #endregion Fields #region properties public DnsQueryRequest QueryRequest { get { return _queryRequest; } } public IDnsRecord[] Answers { get { return _answers; } } public IDnsRecord[] AuthoritiveNameServers { get { return _authoritiveNameServers; } } public IDnsRecord[] AdditionalRecords { get { return _additionalRecords; } } public int BytesReceived { get { return _bytesReceived; } } #endregion /// <summary> /// /// </summary> public DnsQueryResponse() { } private DnsQueryRequest ParseQuery(ref MemoryStream ms) { DnsQueryRequest queryRequest = new DnsQueryRequest(); // Read name queryRequest.Name = DnsRecordBase.ParseName(ref ms); return queryRequest; } internal void ParseResponse(byte[] recvBytes, ProtocolType protocol) { MemoryStream ms = new MemoryStream(recvBytes); byte[] flagBytes = new byte[2]; byte[] transactionId = new byte[2]; byte[] questions = new byte[2]; byte[] answerRRs = new byte[2]; byte[] authorityRRs = new byte[2]; byte[] additionalRRs = new byte[2]; byte[] nsType = new byte[2]; byte[] nsClass = new byte[2]; this._bytesReceived = recvBytes.Length; // Parse DNS Response ms.Read(transactionId, 0, 2); ms.Read(flagBytes, 0, 2); ms.Read(questions, 0, 2); ms.Read(answerRRs, 0, 2); ms.Read(authorityRRs, 0, 2); ms.Read(additionalRRs ,0, 2); // Parse Header _transactionId = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(transactionId, 0)); _flags = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(flagBytes, 0)); _queryResponse = (QueryResponse)(_flags & (ushort)FlagMasks.QueryResponseMask); _opCode = (OpCode)(_flags & (ushort)FlagMasks.OpCodeMask); _nsFlags = (NsFlags)(_flags & (ushort)FlagMasks.NsFlagMask); _rCode = (RCode)(_flags & (ushort)FlagMasks.RCodeMask); // Parse Questions Section _questions = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(questions, 0)); _answerRRs = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(answerRRs, 0)); _authorityRRs = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(authorityRRs, 0)); _additionalRRs = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(additionalRRs, 0)); _additionalRecords = new DnsRecordBase[_additionalRRs]; _answers = new DnsRecordBase[_answerRRs]; _authoritiveNameServers = new DnsRecordBase[_authorityRRs]; // Parse Queries _queryRequest = this.ParseQuery(ref ms); // Read dnsType ms.Read(nsType, 0, 2); // Read dnsClass ms.Read(nsClass, 0, 2); _nsType = (NsType)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(nsType, 0)); _nsClass = (NsClass)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(nsClass, 0)); // Read in Answer Blocks for (int i=0; i < _answerRRs; i++) { _answers[i] = RecordFactory.Create(ref ms); } // Parse Authority Records for (int i=0; i < _authorityRRs; i++) { _authoritiveNameServers[i] = RecordFactory.Create(ref ms); } // Parse Additional Records for (int i=0; i < _additionalRRs; i++) { _additionalRecords[i] = RecordFactory.Create(ref ms); } } } }
RELOAD-NET/RELOAD.NET
DnDns/Query/DnsQueryResponse.cs
C#
lgpl-3.0
6,689
<?php /** * This file is part of contao-community-alliance/dc-general. * * (c) 2013-2019 Contao Community Alliance. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * This project is provided in good faith and hope to be usable by anyone. * * @package contao-community-alliance/dc-general * @author Christian Schiffler <c.schiffler@cyberspectrum.de> * @author Tristan Lins <tristan.lins@bit3.de> * @author Sven Baumann <baumann.sv@gmail.com> * @copyright 2013-2019 Contao Community Alliance. * @license https://github.com/contao-community-alliance/dc-general/blob/master/LICENSE LGPL-3.0-or-later * @filesource */ namespace ContaoCommunityAlliance\DcGeneral\Contao\View\Contao2BackendView\Event; /** * Class GetGlobalButtonEvent. * * This event gets issued when the top level buttons in the listing view are being retrieved. * * These buttons include, but are not limited to, the "back" button and the "edit multiple" button. */ class GetGlobalButtonEvent extends BaseButtonEvent { public const NAME = 'dc-general.view.contao2backend.get-global-button'; /** * The hotkey for the button. * * @var string */ protected $accessKey; /** * The css class to use. * * @var string */ protected $class; /** * The href to use. * * @var string */ protected $href; /** * Set the hotkey for the button. * * @param string $accessKey The hotkey for the button. * * @return $this */ public function setAccessKey($accessKey) { $this->accessKey = $accessKey; return $this; } /** * Get the hotkey for the button. * * @return string */ public function getAccessKey() { return $this->accessKey; } /** * Set the css class for this button. * * @param string $class The css class. * * @return $this */ public function setClass($class) { $this->class = $class; return $this; } /** * Get the css class for this button. * * @return string */ public function getClass() { return $this->class; } /** * Set the href for this button. * * @param string $href The href. * * @return $this */ public function setHref($href) { $this->href = $href; return $this; } /** * Get the href for this button. * * @return string */ public function getHref() { return $this->href; } }
contao-community-alliance/dc-general
src/Contao/View/Contao2BackendView/Event/GetGlobalButtonEvent.php
PHP
lgpl-3.0
2,680
/* * Copyright 2016 - 2021 Marcin Matula * * This file is part of Oap. * * Oap 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. * * Oap 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 Oap. If not, see <http://www.gnu.org/licenses/>. */ #include "gtest/gtest.h" #include "oapHostMemoryApi.h" class OapMemoryApiTests : public testing::Test { public: virtual void SetUp() {} virtual void TearDown() {} }; TEST_F(OapMemoryApiTests, Test_1) { oap::Memory memory = oap::host::NewMemory ({1, 1}); oap::Memory memory1 = oap::host::ReuseMemory (memory); oap::Memory memory2 = oap::host::ReuseMemory (memory); oap::host::DeleteMemory (memory); oap::host::DeleteMemory (memory1); oap::host::DeleteMemory (memory2); } TEST_F(OapMemoryApiTests, Test_2) { oap::Memory memory = oap::host::NewMemoryWithValues ({2, 1}, 2.f); oap::host::DeleteMemory (memory); }
Mamatu/oap
oapHostTests/oapMemoryApiTests.cpp
C++
lgpl-3.0
1,337
package org.openbase.bco.device.openhab.communication; /*- * #%L * BCO Openhab Device Manager * %% * Copyright (C) 2015 - 2021 openbase.org * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import com.google.gson.*; import org.eclipse.smarthome.core.internal.service.CommandDescriptionServiceImpl; import org.eclipse.smarthome.core.internal.types.CommandDescriptionImpl; import org.eclipse.smarthome.core.types.CommandDescription; import org.eclipse.smarthome.core.types.CommandDescriptionBuilder; import org.eclipse.smarthome.core.types.CommandOption; import org.openbase.bco.device.openhab.jp.JPOpenHABURI; import org.openbase.jps.core.JPService; import org.openbase.jps.exception.JPNotAvailableException; import org.openbase.jul.exception.InstantiationException; import org.openbase.jul.exception.*; import org.openbase.jul.exception.printer.ExceptionPrinter; import org.openbase.jul.exception.printer.LogLevel; import org.openbase.jul.iface.Shutdownable; import org.openbase.jul.pattern.Observable; import org.openbase.jul.pattern.ObservableImpl; import org.openbase.jul.pattern.Observer; import org.openbase.jul.schedule.GlobalScheduledExecutorService; import org.openbase.jul.schedule.SyncObject; import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState; import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.sse.InboundSseEvent; import javax.ws.rs.sse.SseEventSource; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public abstract class OpenHABRestConnection implements Shutdownable { public static final String SEPARATOR = "/"; public static final String REST_TARGET = "rest"; public static final String APPROVE_TARGET = "approve"; public static final String EVENTS_TARGET = "events"; public static final String TOPIC_KEY = "topic"; public static final String TOPIC_SEPARATOR = SEPARATOR; private static final Logger LOGGER = LoggerFactory.getLogger(OpenHABRestConnection.class); private final SyncObject topicObservableMapLock = new SyncObject("topicObservableMapLock"); private final SyncObject connectionStateSyncLock = new SyncObject("connectionStateSyncLock"); private final Map<String, ObservableImpl<Object, JsonObject>> topicObservableMap; private final Client restClient; private final WebTarget restTarget; private SseEventSource sseSource; private boolean shutdownInitiated = false; protected final JsonParser jsonParser; protected final Gson gson; private ScheduledFuture<?> connectionTask; protected ConnectionState.State openhabConnectionState = State.DISCONNECTED; public OpenHABRestConnection() throws InstantiationException { try { this.topicObservableMap = new HashMap<>(); this.gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return false; } @Override public boolean shouldSkipClass(Class<?> aClass) { // ignore Command Description because its an interface and can not be serialized without any instance creator. if(aClass.equals(CommandDescription.class)) { return true; } return false; } }).create(); this.jsonParser = new JsonParser(); this.restClient = ClientBuilder.newClient(); this.restTarget = restClient.target(JPService.getProperty(JPOpenHABURI.class).getValue().resolve(SEPARATOR + REST_TARGET)); this.setConnectState(State.CONNECTING); } catch (JPNotAvailableException ex) { throw new InstantiationException(this, ex); } } private boolean isTargetReachable() { try { testConnection(); } catch (CouldNotPerformException e) { if (e.getCause() instanceof ProcessingException) { return false; } } return true; } protected abstract void testConnection() throws CouldNotPerformException; public void waitForConnectionState(final ConnectionState.State connectionState, final long timeout, final TimeUnit timeUnit) throws InterruptedException { synchronized (connectionStateSyncLock) { while (getOpenhabConnectionState() != connectionState) { connectionStateSyncLock.wait(timeUnit.toMillis(timeout)); } } } public void waitForConnectionState(final ConnectionState.State connectionState) throws InterruptedException { synchronized (connectionStateSyncLock) { while (getOpenhabConnectionState() != connectionState) { connectionStateSyncLock.wait(); } } } private void setConnectState(final ConnectionState.State connectState) { synchronized (connectionStateSyncLock) { // filter non changing states if (connectState == this.openhabConnectionState) { return; } LOGGER.trace("Openhab Connection State changed to: "+connectState); // update state this.openhabConnectionState = connectState; // handle state change switch (connectState) { case CONNECTING: LOGGER.info("Wait for openHAB..."); try { connectionTask = GlobalScheduledExecutorService.scheduleWithFixedDelay(() -> { if (isTargetReachable()) { // set connected setConnectState(State.CONNECTED); // cleanup own task connectionTask.cancel(false); } }, 0, 15, TimeUnit.SECONDS); } catch (NotAvailableException | RejectedExecutionException ex) { // if global executor service is not available we have no chance to connect. LOGGER.warn("Wait for openHAB...", ex); setConnectState(State.DISCONNECTED); } break; case CONNECTED: LOGGER.info("Connection to OpenHAB established."); initSSE(); break; case RECONNECTING: LOGGER.warn("Connection to OpenHAB lost!"); resetConnection(); setConnectState(State.CONNECTING); break; case DISCONNECTED: LOGGER.info("Connection to OpenHAB closed."); resetConnection(); break; } // notify state change connectionStateSyncLock.notifyAll(); // apply next state if required switch (connectState) { case RECONNECTING: setConnectState(State.CONNECTING); break; } } } private void initSSE() { // activate sse source if not already done if (sseSource != null) { LOGGER.warn("SSE already initialized!"); return; } final WebTarget webTarget = restTarget.path(EVENTS_TARGET); sseSource = SseEventSource.target(webTarget).reconnectingEvery(15, TimeUnit.SECONDS).build(); sseSource.open(); final Consumer<InboundSseEvent> evenConsumer = inboundSseEvent -> { // dispatch event try { final JsonObject payload = jsonParser.parse(inboundSseEvent.readData()).getAsJsonObject(); for (Entry<String, ObservableImpl<Object, JsonObject>> topicObserverEntry : topicObservableMap.entrySet()) { try { if (payload.get(TOPIC_KEY).getAsString().matches(topicObserverEntry.getKey())) { topicObserverEntry.getValue().notifyObservers(payload); } } catch (Exception ex) { ExceptionPrinter.printHistory(new CouldNotPerformException("Could not notify listeners on topic[" + topicObserverEntry.getKey() + "]", ex), LOGGER); } } } catch (Exception ex) { ExceptionPrinter.printHistory(new CouldNotPerformException("Could not handle SSE payload!", ex), LOGGER); } }; final Consumer<Throwable> errorHandler = ex -> { ExceptionPrinter.printHistory("Openhab connection error detected!", ex, LOGGER, LogLevel.DEBUG); checkConnectionState(); }; final Runnable reconnectHandler = () -> { checkConnectionState(); }; sseSource.register(evenConsumer, errorHandler, reconnectHandler); } public State getOpenhabConnectionState() { return openhabConnectionState; } public void checkConnectionState() { synchronized (connectionStateSyncLock) { // only validate if connected if (!isConnected()) { return; } // if not reachable init a reconnect if (!isTargetReachable()) { setConnectState(State.RECONNECTING); } } } public boolean isConnected() { return getOpenhabConnectionState() == State.CONNECTED; } public void addSSEObserver(Observer<Object, JsonObject> observer) { addSSEObserver(observer, ""); } public void addSSEObserver(final Observer<Object, JsonObject> observer, final String topicRegex) { synchronized (topicObservableMapLock) { if (topicObservableMap.containsKey(topicRegex)) { topicObservableMap.get(topicRegex).addObserver(observer); return; } final ObservableImpl<Object, JsonObject> observable = new ObservableImpl<>(this); observable.addObserver(observer); topicObservableMap.put(topicRegex, observable); } } public void removeSSEObserver(Observer<Object, JsonObject> observer) { removeSSEObserver(observer, ""); } public void removeSSEObserver(Observer<Object, JsonObject> observer, final String topicFilter) { synchronized (topicObservableMapLock) { if (topicObservableMap.containsKey(topicFilter)) { topicObservableMap.get(topicFilter).removeObserver(observer); } } } private void resetConnection() { // cancel ongoing connection task if (!connectionTask.isDone()) { connectionTask.cancel(false); } // close sse if (sseSource != null) { sseSource.close(); sseSource = null; } } public void validateConnection() throws CouldNotPerformException { if (!isConnected()) { throw new InvalidStateException("Openhab not reachable yet!"); } } private String validateResponse(final Response response) throws CouldNotPerformException, ProcessingException { return validateResponse(response, false); } private String validateResponse(final Response response, final boolean skipConnectionValidation) throws CouldNotPerformException, ProcessingException { final String result = response.readEntity(String.class); if (response.getStatus() == 200 || response.getStatus() == 201 || response.getStatus() == 202) { return result; } else if (response.getStatus() == 404) { if (!skipConnectionValidation) { checkConnectionState(); } throw new NotAvailableException("URL"); } else if (response.getStatus() == 503) { if (!skipConnectionValidation) { checkConnectionState(); } // throw a processing exception to indicate that openHAB is still not fully started, this is used to wait for openHAB throw new ProcessingException("OpenHAB server not ready"); } else { throw new CouldNotPerformException("Response returned with ErrorCode[" + response.getStatus() + "], Result[" + result + "] and ErrorMessage[" + response.getStatusInfo().getReasonPhrase() + "]"); } } protected String get(final String target) throws CouldNotPerformException { return get(target, false); } protected String get(final String target, final boolean skipValidation) throws CouldNotPerformException { try { // handle validation if (!skipValidation) { validateConnection(); } final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().get(); return validateResponse(response, skipValidation); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not get sub-URL[" + target + "]", ex); } } protected String delete(final String target) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().delete(); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not delete sub-URL[" + target + "]", ex); } } protected String putJson(final String target, final Object value) throws CouldNotPerformException { return put(target, gson.toJson(value), MediaType.APPLICATION_JSON_TYPE); } protected String put(final String target, final String value, final MediaType mediaType) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().put(Entity.entity(value, mediaType)); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not put value[" + value + "] on sub-URL[" + target + "]", ex); } } protected String postJson(final String target, final Object value) throws CouldNotPerformException { return post(target, gson.toJson(value), MediaType.APPLICATION_JSON_TYPE); } protected String post(final String target, final String value, final MediaType mediaType) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().post(Entity.entity(value, mediaType)); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not post Value[" + value + "] of MediaType[" + mediaType + "] on sub-URL[" + target + "]", ex); } } public boolean isShutdownInitiated() { return shutdownInitiated; } @Override public void shutdown() { // prepare shutdown shutdownInitiated = true; setConnectState(State.DISCONNECTED); // stop rest service restClient.close(); // stop sse service synchronized (topicObservableMapLock) { for (final Observable<Object, JsonObject> jsonObjectObservable : topicObservableMap.values()) { jsonObjectObservable.shutdown(); } topicObservableMap.clear(); resetConnection(); } } }
DivineCooperation/bco.core-manager
openhab/src/main/java/org/openbase/bco/device/openhab/communication/OpenHABRestConnection.java
Java
lgpl-3.0
17,838
#include "gitrepository.h" #include <qtcacheexception.h> #include <git2.h> inline void git_eval(int err){ if (err) { const git_error* err = giterr_last(); throw QtC::QtCacheException(err->message); } } template<typename T> class git_auto { public: git_auto(T* object = NULL) : ref(object) {} ~git_auto(); operator T*() const { return ref; } T** operator &() {return &ref; } private: T* ref; }; git_auto<git_repository>::~git_auto() { git_repository_free(this->ref); } git_auto<git_signature>::~git_auto() { git_signature_free(this->ref); } git_auto<git_index>::~git_auto() { git_index_free(this->ref); } git_auto<git_tree>::~git_auto() { git_tree_free(this->ref); } git_auto<git_reference>::~git_auto() { git_reference_free(this->ref); } git_auto<git_commit>::~git_auto() { git_commit_free(this->ref); } git_auto<git_status_list>::~git_auto() { git_status_list_free(this->ref); } git_auto<git_remote>::~git_auto() { if (this->ref && git_remote_connected(this->ref)) { git_remote_disconnect(this->ref); } git_remote_free(this->ref); } GitRepository::GitRepository(const QString &localDirPath) : m_local_dir_path(localDirPath), m_repo(NULL), m_signature(NULL) { git_libgit2_init(); } GitRepository::~GitRepository() { if (NULL != m_signature) { git_signature_free(m_signature); } if (NULL != m_repo) { git_repository_free(m_repo); } git_libgit2_shutdown(); } bool GitRepository::isOpen() { return NULL != m_repo; } void GitRepository::setRepository(git_repository* repo) { if (NULL != m_repo){ git_repository_free(m_repo); } m_repo = repo; } git_repository* GitRepository::repository() { if (NULL == m_repo){ try{ open(); }catch(...){ try{ init(); }catch(...){ throw; } } } return m_repo; } void GitRepository::open() { git_repository* repo = NULL; git_eval(git_repository_open(&repo, m_local_dir_path.absolutePath().toLocal8Bit())); setRepository(repo); } void GitRepository::init() { git_repository* repo = NULL; git_repository_init_options initopts = GIT_REPOSITORY_INIT_OPTIONS_INIT; initopts.flags = GIT_REPOSITORY_INIT_MKPATH; git_eval(git_repository_init_ext(&repo, m_local_dir_path.absolutePath().toLocal8Bit(), &initopts)); git_auto<git_index> index; git_eval(git_repository_index(&index, repo)); git_oid tree_id; git_eval(git_index_write_tree(&tree_id, index)); git_auto<git_tree> tree; git_eval(git_tree_lookup(&tree, repo, &tree_id)); git_oid commit_id; git_eval(git_commit_create_v(&commit_id, repo, "HEAD", signature(), signature(), NULL, "Initial commit", tree, 0)); setRepository(repo); } void GitRepository::branch(const QString& name) { git_repository* repo = repository(); git_auto<git_reference> branch; int err = git_branch_lookup(&branch, repo, name.toLatin1(), GIT_BRANCH_LOCAL); if (err == GIT_ENOTFOUND){ git_oid parent_id; git_auto<git_commit> parent; git_eval(git_reference_name_to_id(&parent_id, repo, "HEAD")); git_eval(git_commit_lookup(&parent, repo, &parent_id)); git_eval(git_branch_create(&branch, repo, name.toLocal8Bit(), parent, 1)); }else{ git_eval(err); } git_eval(git_repository_set_head(repo, git_reference_name(branch))); git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT; opts.checkout_strategy = GIT_CHECKOUT_FORCE; git_eval(git_checkout_head(repo, &opts)); } void GitRepository::add(const QString& filepath) { git_repository* repo = repository(); git_auto<git_index> index; git_eval(git_repository_index(&index, repo)); git_eval(git_index_add_bypath(index, filepath.toLatin1())); git_index_write(index); git_index_free(index); } void GitRepository::commit(const QString& message) { git_repository* repo = repository(); { git_auto<git_status_list> changes; git_eval(git_status_list_new(&changes, repo, NULL)); if (git_status_list_entrycount(changes) == 0) { return; } } git_auto<git_index> index; git_eval(git_repository_index(&index, repo)); git_oid tree_id; git_eval(git_index_write_tree(&tree_id, index)); git_auto<git_tree> tree; git_eval(git_tree_lookup(&tree, repo, &tree_id)); git_oid parent_id; git_eval(git_reference_name_to_id(&parent_id, repo, "HEAD")); git_auto<git_commit> parent; git_eval(git_commit_lookup(&parent, repo, &parent_id)); git_oid commit_id; git_signature* sig = signature(); git_eval(git_commit_create_v(&commit_id, repo, "HEAD", sig, sig, NULL, message.toLocal8Bit(), tree, 1, parent)); } void GitRepository::clone(const QString& url) { git_repository* repo = NULL; git_clone_options opts = GIT_CLONE_OPTIONS_INIT; opts.checkout_branch = "master"; git_eval(git_clone(&repo, url.toLatin1(), m_local_dir_path.absolutePath().toLocal8Bit(), &opts)); setRepository(repo); } void GitRepository::push() { git_repository* repo = repository(); const char* remote_name = "origin"; git_auto<git_remote> remote; git_eval(git_remote_lookup(&remote, repo, remote_name)); git_eval(git_remote_connect(remote, GIT_DIRECTION_PUSH, NULL, NULL)); git_auto<git_reference> head; git_eval(git_repository_head(&head, repo)); QString refname = QString("+%1:%1").arg(git_reference_name(head)); git_eval(git_remote_add_push(repo, remote_name, refname.toLatin1())); git_eval(git_remote_upload(remote, NULL, NULL)); } void GitRepository::fetch() { git_repository* repo = repository(); const char* remote_name = "origin"; git_auto<git_remote> remote; git_eval(git_remote_lookup(&remote, repo, remote_name)); git_eval(git_remote_connect(remote, GIT_DIRECTION_FETCH, NULL, NULL)); git_eval(git_remote_fetch(remote, NULL, NULL, NULL)); } void GitRepository::setSignature(const QString& authorName, const QString& authorEmail) { git_signature* sig = m_signature; if (sig) { git_signature_free(sig); } git_eval(git_signature_now(&sig, authorName.toLocal8Bit(), authorEmail.toLocal8Bit())); m_signature = sig; } git_signature* GitRepository::signature() { if (!m_signature) { setSignature(); } return m_signature; }
entwickler42/QtCache
QtCacheGitPlugin/gitrepository.cpp
C++
lgpl-3.0
6,672
/* * SonarLint for Visual Studio * Copyright (C) 2016-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using SonarLint.VisualStudio.Progress.Controller; namespace SonarLint.VisualStudio.Progress.UnitTests { /// <summary> /// Partial class implementation of <see cref="IProgressStepExecutionEvents"/> /// </summary> public partial class ConfigurableProgressController : IProgressStepExecutionEvents { void IProgressStepExecutionEvents.ProgressChanged(string progressDetailText, double progress) { this.progressChanges.Add(Tuple.Create(progressDetailText, progress)); } } }
duncanpMS/sonarlint-visualstudio
src/Progress.TestFramework/ConfigurableProgressController.IProgressStepExecutionEvents.cs
C#
lgpl-3.0
1,405
<?php /** * @copyright Copyright (c) Metaways Infosystems GmbH, 2011 * @license LGPLv3, http://www.arcavias.com/en/license * @package MShop * @subpackage Common */ /** * Common interface for items that carry sorting informations. * * @package MShop * @subpackage Common */ interface MShop_Common_Item_Position_Interface { /** * Returns the position of the item in the list. * * @return integer Position of the item in the list */ public function getPosition(); /** * Sets the new position of the item in the list. * * @param integer $pos position of the item in the list * @return void */ public function setPosition( $pos ); }
Arcavias/arcavias-core
lib/mshoplib/src/MShop/Common/Item/Position/Interface.php
PHP
lgpl-3.0
664
#include "StructuralInterface.h" StructuralInterface::StructuralInterface (StructuralEntity *parent) : StructuralEntity (parent) { setCategory (Structural::Interface); setStructuralType (Structural::NoType); setResizable (false); setTop (0); setLeft (0); setWidth (ST_DEFAULT_INTERFACE_W); setHeight (ST_DEFAULT_INTERFACE_H); if (!ST_OPT_SHOW_INTERFACES) setHidden (true); } void StructuralInterface::adjust (bool collision, bool recursion) { StructuralEntity::adjust (collision, recursion); // Adjusting position... StructuralEntity *parent = structuralParent (); if (parent || !ST_OPT_WITH_BODY) { if (!collision) { // Tries (10x) to find a position where there is no collision with others // relatives for (int i = 0; i < 10; i++) { bool colliding = false; for (StructuralEntity *ent : StructuralUtil::neighbors (this)) { if (ent != this) { int n = 0, max = 1000; qreal current = 0.0; ent->setSelectable (false); while (collidesWithItem (ent, Qt::IntersectsItemBoundingRect)) { QLineF line = QLineF (left () + width () / 2, top () + height () / 2, ent->width () / 2, ent->height () / 2); line.setAngle (qrand () % 360); current += (double)(qrand () % 100) / 1000.0; setTop (top () + line.pointAt (current / 2).y () - line.p1 ().y ()); setLeft (left () + line.pointAt (current / 2).x () - line.p1 ().x ()); if (++n > max) break; } constrain (); ent->setSelectable (true); } } for (StructuralEntity *ent : StructuralUtil::neighbors (this)) if (collidesWithItem (ent, Qt::IntersectsItemBoundingRect)) colliding = true; if (!colliding) break; } } constrain (); StructuralUtil::adjustEdges (this); } } void StructuralInterface::constrain () { StructuralEntity *parent = structuralParent (); if (parent != nullptr) { QPointF tail (parent->width () / 2, parent->height () / 2); QPointF head (left () + width () / 2, top () + height () / 2); if (tail == head) { head.setX (tail.x ()); head.setY (tail.y () - 10); } QPointF p = head; QLineF line (tail, head); bool status = true; qreal current = 1.0; qreal step = 0.01; if (!parent->contains (p)) { step = -0.01; status = false; } do { current += step; p = line.pointAt (current); } while (parent->contains (p) == status); if (QLineF (p, head).length () > 7) { setTop (p.y () - height () / 2); setLeft (p.x () - width () / 2); } } } void StructuralInterface::draw (QPainter *painter) { int x = ST_DEFAULT_ENTITY_PADDING + ST_DEFAULT_INTERFACE_PADDING; int y = ST_DEFAULT_ENTITY_PADDING + ST_DEFAULT_INTERFACE_PADDING; int w = width () - 2 * ST_DEFAULT_INTERFACE_PADDING; int h = height () - 2 * ST_DEFAULT_INTERFACE_PADDING; painter->drawPixmap (x, y, w, h, QPixmap (StructuralUtil::icon (structuralType ()))); if (!ST_OPT_WITH_BODY && !ST_OPT_USE_FLOATING_INTERFACES) { if (property (ST_ATTR_ENT_AUTOSTART) == ST_VALUE_TRUE) { painter->setPen (QPen (QBrush (QColor (76, 76, 76)), 2)); painter->drawRect (x, y, w, h); } } if (!error ().isEmpty () || !warning ().isEmpty ()) { QString icon; if (!error ().isEmpty ()) icon = QString (ST_DEFAULT_ALERT_ERROR_ICON); else icon = QString (ST_DEFAULT_ALERT_WARNING_ICON); painter->drawPixmap (x + w / 2 - (ST_DEFAULT_ALERT_ICON_W - 3) / 2, y + h / 2 - (ST_DEFAULT_ALERT_ICON_H - 3) / 2, ST_DEFAULT_ALERT_ICON_W - 3, ST_DEFAULT_ALERT_ICON_H - 3, QPixmap (icon)); } if (isMoving ()) { painter->setBrush (QBrush (Qt::NoBrush)); painter->setPen (QPen (QBrush (Qt::black), 0)); int moveX = x + moveLeft () - left (); int moveY = y + moveTop () - top (); int moveW = w; int moveH = h; painter->drawRect (moveX, moveY, moveW, moveH); } }
TeleMidia/nclcomposer
src/plugins/ncl-structural-view/view/StructuralInterface.cpp
C++
lgpl-3.0
4,376
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.server.authentication; import javax.annotation.concurrent.Immutable; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang.StringUtils.isNotBlank; /** * Display information provided by the Identity Provider to be displayed into the login form. * * @since 5.4 */ @Immutable public final class Display { private final String iconPath; private final String backgroundColor; private Display(Builder builder) { this.iconPath = builder.iconPath; this.backgroundColor = builder.backgroundColor; } /** * URL path to the provider icon, as deployed at runtime, for example "/static/authgithub/github.svg" (in this * case "authgithub" is the plugin key. Source file is "src/main/resources/static/github.svg"). * It can also be an external URL, for example "http://www.mydomain/myincon.png". * * Must not be blank. * <br> * The recommended format is SVG with a size of 24x24 pixels. * Other supported format is PNG, with a size of 40x40 pixels. */ public String getIconPath() { return iconPath; } /** * Background color for the provider button displayed in the login form. * It's a Hexadecimal value, for instance #205081. * <br> * If not provided, the default value is #236a97 */ public String getBackgroundColor() { return backgroundColor; } public static Builder builder() { return new Builder(); } public static class Builder { private String iconPath; private String backgroundColor = "#236a97"; private Builder() { } /** * @see Display#getIconPath() */ public Builder setIconPath(String iconPath) { this.iconPath = iconPath; return this; } /** * @see Display#getBackgroundColor() */ public Builder setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; return this; } public Display build() { checkArgument(isNotBlank(iconPath), "Icon path must not be blank"); validateBackgroundColor(); return new Display(this); } private void validateBackgroundColor() { checkArgument(isNotBlank(backgroundColor), "Background color must not be blank"); checkArgument(backgroundColor.length() == 7 && backgroundColor.indexOf('#') == 0, "Background color must begin with a sharp followed by 6 characters"); } } }
Builders-SonarSource/sonarqube-bis
sonar-plugin-api/src/main/java/org/sonar/api/server/authentication/Display.java
Java
lgpl-3.0
3,286
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program 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. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\thread; use pocketmine\scheduler\AsyncTask; use const PTHREADS_INHERIT_NONE; /** * Specialized Worker class for PocketMine-MP-related use cases. It handles setting up autoloading and error handling. * * Workers are a special type of thread which execute tasks passed to them during their lifetime. Since creating a new * thread has a high resource cost, workers can be kept around and reused for lots of short-lived tasks. * * As a plugin developer, you'll rarely (if ever) actually need to use this class directly. * If you want to run tasks on other CPU cores, check out AsyncTask first. * @see AsyncTask */ abstract class Worker extends \Worker{ use CommonThreadPartsTrait; public function start(int $options = PTHREADS_INHERIT_NONE) : bool{ //this is intentionally not traitified ThreadManager::getInstance()->add($this); if($this->getClassLoaders() === null){ $this->setClassLoaders(); } return parent::start($options); } /** * Stops the thread using the best way possible. Try to stop it yourself before calling this. */ public function quit() : void{ $this->isKilled = true; if(!$this->isShutdown()){ while($this->unstack() !== null); $this->notify(); $this->shutdown(); } ThreadManager::getInstance()->remove($this); } }
pmmp/PocketMine-MP
src/thread/Worker.php
PHP
lgpl-3.0
2,040
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.computation.step; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.codec.digest.DigestUtils; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import org.sonar.api.utils.System2; import org.sonar.batch.protocol.output.BatchReport; import org.sonar.core.persistence.DbSession; import org.sonar.core.persistence.MyBatis; import org.sonar.core.source.db.FileSourceDto; import org.sonar.core.source.db.FileSourceDto.Type; import org.sonar.server.computation.batch.BatchReportReader; import org.sonar.server.computation.component.Component; import org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor; import org.sonar.server.computation.component.TreeRootHolder; import org.sonar.server.computation.source.ComputeFileSourceData; import org.sonar.server.computation.source.CoverageLineReader; import org.sonar.server.computation.source.DuplicationLineReader; import org.sonar.server.computation.source.HighlightingLineReader; import org.sonar.server.computation.source.LineReader; import org.sonar.server.computation.source.ScmLineReader; import org.sonar.server.computation.source.SymbolsLineReader; import org.sonar.server.db.DbClient; import org.sonar.server.source.db.FileSourceDb; import org.sonar.server.util.CloseableIterator; import static org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor.Order.PRE_ORDER; public class PersistFileSourcesStep implements ComputationStep { private final DbClient dbClient; private final System2 system2; private final TreeRootHolder treeRootHolder; private final BatchReportReader reportReader; public PersistFileSourcesStep(DbClient dbClient, System2 system2, TreeRootHolder treeRootHolder, BatchReportReader reportReader) { this.dbClient = dbClient; this.system2 = system2; this.treeRootHolder = treeRootHolder; this.reportReader = reportReader; } @Override public void execute() { // Don't use batch insert for file_sources since keeping all data in memory can produce OOM for big files DbSession session = dbClient.openSession(false); try { new FileSourceVisitor(session).visit(treeRootHolder.getRoot()); } finally { MyBatis.closeQuietly(session); } } private class FileSourceVisitor extends DepthTraversalTypeAwareVisitor { private final DbSession session; private Map<String, FileSourceDto> previousFileSourcesByUuid = new HashMap<>(); private String projectUuid; private FileSourceVisitor(DbSession session) { super(Component.Type.FILE, PRE_ORDER); this.session = session; } @Override public void visitProject(Component project) { this.projectUuid = project.getUuid(); session.select("org.sonar.core.source.db.FileSourceMapper.selectHashesForProject", ImmutableMap.of("projectUuid", projectUuid, "dataType", Type.SOURCE), new ResultHandler() { @Override public void handleResult(ResultContext context) { FileSourceDto dto = (FileSourceDto) context.getResultObject(); previousFileSourcesByUuid.put(dto.getFileUuid(), dto); } }); } @Override public void visitFile(Component file) { int fileRef = file.getRef(); BatchReport.Component component = reportReader.readComponent(fileRef); CloseableIterator<String> linesIterator = reportReader.readFileSource(fileRef); LineReaders lineReaders = new LineReaders(reportReader, fileRef); try { ComputeFileSourceData computeFileSourceData = new ComputeFileSourceData(linesIterator, lineReaders.readers(), component.getLines()); ComputeFileSourceData.Data fileSourceData = computeFileSourceData.compute(); persistSource(fileSourceData, file.getUuid()); } catch (Exception e) { throw new IllegalStateException(String.format("Cannot persist sources of %s", file.getKey()), e); } finally { linesIterator.close(); lineReaders.close(); } } private void persistSource(ComputeFileSourceData.Data fileSourceData, String componentUuid) { FileSourceDb.Data fileData = fileSourceData.getFileSourceData(); byte[] data = FileSourceDto.encodeSourceData(fileData); String dataHash = DigestUtils.md5Hex(data); String srcHash = fileSourceData.getSrcHash(); String lineHashes = fileSourceData.getLineHashes(); FileSourceDto previousDto = previousFileSourcesByUuid.get(componentUuid); if (previousDto == null) { FileSourceDto dto = new FileSourceDto() .setProjectUuid(projectUuid) .setFileUuid(componentUuid) .setDataType(Type.SOURCE) .setBinaryData(data) .setSrcHash(srcHash) .setDataHash(dataHash) .setLineHashes(lineHashes) .setCreatedAt(system2.now()) .setUpdatedAt(system2.now()); dbClient.fileSourceDao().insert(session, dto); session.commit(); } else { // Update only if data_hash has changed or if src_hash is missing (progressive migration) boolean binaryDataUpdated = !dataHash.equals(previousDto.getDataHash()); boolean srcHashUpdated = !srcHash.equals(previousDto.getSrcHash()); if (binaryDataUpdated || srcHashUpdated) { previousDto .setBinaryData(data) .setDataHash(dataHash) .setSrcHash(srcHash) .setLineHashes(lineHashes); // Optimization only change updated at when updating binary data to avoid unnecessary indexation by E/S if (binaryDataUpdated) { previousDto.setUpdatedAt(system2.now()); } dbClient.fileSourceDao().update(previousDto); session.commit(); } } } } private static class LineReaders { private final List<LineReader> readers = new ArrayList<>(); private final List<CloseableIterator<?>> iterators = new ArrayList<>(); LineReaders(BatchReportReader reportReader, int componentRef) { CloseableIterator<BatchReport.Coverage> coverageReportIterator = reportReader.readComponentCoverage(componentRef); BatchReport.Changesets scmReport = reportReader.readChangesets(componentRef); CloseableIterator<BatchReport.SyntaxHighlighting> highlightingIterator = reportReader.readComponentSyntaxHighlighting(componentRef); List<BatchReport.Symbols.Symbol> symbols = reportReader.readComponentSymbols(componentRef); List<BatchReport.Duplication> duplications = reportReader.readComponentDuplications(componentRef); if (coverageReportIterator != null) { iterators.add(coverageReportIterator); readers.add(new CoverageLineReader(coverageReportIterator)); } if (scmReport != null) { readers.add(new ScmLineReader(scmReport)); } if (highlightingIterator != null) { iterators.add(highlightingIterator); readers.add(new HighlightingLineReader(highlightingIterator)); } if (!duplications.isEmpty()) { readers.add(new DuplicationLineReader(duplications)); } if (!symbols.isEmpty()) { readers.add(new SymbolsLineReader(symbols)); } } List<LineReader> readers() { return readers; } void close() { for (CloseableIterator<?> reportIterator : iterators) { reportIterator.close(); } } } @Override public String getDescription() { return "Persist file sources"; } }
jblievremont/sonarqube
server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistFileSourcesStep.java
Java
lgpl-3.0
8,521
package com.wangdaye.common.base.fragment; import com.wangdaye.common.base.activity.LoadableActivity; import java.util.List; /** * Loadable fragment. * */ public abstract class LoadableFragment<T> extends MysplashFragment { /** * {@link LoadableActivity#loadMoreData(List, int, boolean)}. * */ public abstract List<T> loadMoreData(List<T> list, int headIndex, boolean headDirection); }
WangDaYeeeeee/Mysplash
common/src/main/java/com/wangdaye/common/base/fragment/LoadableFragment.java
Java
lgpl-3.0
411
<?php if (!defined('TL_ROOT')) die('You can not access this file directly!'); /** * Contao Open Source CMS * Copyright (C) 2005-2012 Leo Feyer * * Formerly known as TYPOlight Open Source CMS. * * This program 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, please visit the Free * Software Foundation website at <http://www.gnu.org/licenses/>. * * PHP version 5 * @copyright Roger Pau 2009 * @copyright Patricio F. Hamann 2010 * @copyright Juan José Olivera 2010 * @copyright Klaus Bogotz 2010 * @copyright Rogelio Jacinto 2011 * @copyright Jasmin S. 2012 * @author Patricio F. Hamann <hamannz@gmail.com> * @author Juan José Olivera <jota.jota.or@gmail.com> * @author Klaus Bogotz 2010 <klbogotz@gr7.org> * @author Rogelio Jacinto <rogelio.jacinto@gmail.com> * @author Jasmin S. <jasmin@faasmedia.com> * @package Spanish * @license LGPL * @filesource */ $GLOBALS['TL_LANG']['tl_newsletter_channel']['title'] = array('Título', 'Por favor introduce el título del canal'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['jumpTo'] = array('Saltar a página', 'Por favor seleccion la página a la que los visitantes serán redirigidos cuando seleccionen una newsletter.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['useSMTP'] = array('Servidor SMTP personalizado', 'Utilizar un servidor SMTP específico para enviar boletines.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtpHost'] = array('Nombre de servidor SMTP', 'Indique el nombre del servidor SMTP.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtpUser'] = array('Nombre de usuario SMTP', 'Permite indicar el nombre de usuario para identificarse con el servidor SMTP.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtpPass'] = array('Contraseña SMTP', 'Permite indicar la contraseña para identificarse con el servidor SMTP.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtpEnc'] = array('Cifrado SMTP', 'Aqui puedes seleccionar un método de cifrado (SSL o TLS).'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtpPort'] = array('Número de puerto SMTP', 'Indique el número de puerto del servidor SMTP.'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['tstamp'] = array('Fecha de revisión', 'Fecha y hora de la última revisión'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['title_legend'] = 'Título y redirección'; $GLOBALS['TL_LANG']['tl_newsletter_channel']['smtp_legend'] = 'Configuación SMTP'; $GLOBALS['TL_LANG']['tl_newsletter_channel']['new'] = array('Nuevo canal', 'Crear un canal nuevo'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['show'] = array('Detalles de canal', 'Mostrar los detalles del canal con ID %s'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['edit'] = array('Editar canal', 'Editar canal con ID %s'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['editheader'] = array('Editar ajustes de canal', 'Editar los ajsutes del canal con ID %s'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['copy'] = array('Copiar canal', 'Copiar canal con ID %s'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['delete'] = array('Eliminar canal', 'Eliminar cana con ID %s'); $GLOBALS['TL_LANG']['tl_newsletter_channel']['recipients'] = array('Editar receptores', 'Editar los receptores del canal con ID %s'); ?>
kikmedia/contao-spanish
system/modules/newsletter/languages/es/tl_newsletter_channel.php
PHP
lgpl-3.0
3,823
/*--- iGeo - http://igeo.jp Copyright (c) 2002-2013 Satoru Sugihara This file is part of iGeo. iGeo is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3. iGeo 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 iGeo. If not, see <http://www.gnu.org/licenses/>. ---*/ package igeo; import java.awt.*; import igeo.gui.*; /** Class of point object. @author Satoru Sugihara */ public class IPoint extends IGeometry implements IVecI{ //public IVecI pos; public IVec pos; public IPoint(){ pos = new IVec(); initPoint(null); } public IPoint(IVec v){ pos = v; initPoint(null); } public IPoint(IVecI v){ pos = v.get(); initPoint(null); } public IPoint(double x, double y, double z){ pos = new IVec(x,y,z); initPoint(null); } public IPoint(double x, double y){ pos = new IVec(x,y); initPoint(null); } public IPoint(IServerI s){ super(s); pos = new IVec(0,0,0); initPoint(s); } public IPoint(IServerI s, IVec v){ super(s); pos = v; initPoint(s); } public IPoint(IServerI s, IVecI v){ super(s); pos = v.get(); initPoint(s); } public IPoint(IServerI s, double x, double y, double z){ super(s); pos = new IVec(x,y,z); initPoint(s); } public IPoint(IServerI s, double x, double y){ super(s); pos = new IVec(x,y); initPoint(s); } public IPoint(IPoint p){ super(p); pos = p.pos.dup(); initPoint(p.server); //setColor(p.getColor()); } public IPoint(IServerI s, IPoint p){ super(s,p); pos = p.pos.dup(); initPoint(s); //setColor(p.getColor()); } public /*protected*/ void initPoint(IServerI s){ if(pos==null){ IOut.err("null value is set in IPoint"); // return; } // // costly to use instanceof? //if(pos instanceof IVec) parameter = (IVec)pos; //else if(pos instanceof IVecR) parameter = (IVecR)pos; //else if(pos instanceof IVec4) parameter = (IVec4)pos; //else if(pos instanceof IVec4R) parameter = (IVec4R)pos; //addGraphic(new IPointGraphic(this)); if(graphics==null) initGraphic(s); // not init when using copy constructor } public IGraphicObject createGraphic(IGraphicMode m){ if(m.isNone()) return null; return new IPointGraphic(this); } synchronized public double x(){ return pos.x(); } synchronized public double y(){ return pos.y(); } synchronized public double z(){ return pos.z(); } synchronized public IPoint x(double vx){ pos.x(vx); return this; } synchronized public IPoint y(double vy){ pos.y(vy); return this; } synchronized public IPoint z(double vz){ pos.z(vz); return this; } synchronized public IPoint x(IDoubleI vx){ pos.x(vx); return this; } synchronized public IPoint y(IDoubleI vy){ pos.y(vy); return this; } synchronized public IPoint z(IDoubleI vz){ pos.z(vz); return this; } synchronized public IPoint x(IVecI vx){ pos.x(vx); return this; } synchronized public IPoint y(IVecI vy){ pos.y(vy); return this; } synchronized public IPoint z(IVecI vz){ pos.z(vz); return this; } synchronized public IPoint x(IVec2I vx){ pos.x(vx); return this; } synchronized public IPoint y(IVec2I vy){ pos.y(vy); return this; } synchronized public double x(ISwitchE e){ return pos.x(e); } synchronized public double y(ISwitchE e){ return pos.y(e); } synchronized public double z(ISwitchE e){ return pos.z(e); } synchronized public IDouble x(ISwitchR r){ return pos.x(r); } synchronized public IDouble y(ISwitchR r){ return pos.y(r); } synchronized public IDouble z(ISwitchR r){ return pos.z(r); } //synchronized public IVec get(){ return pos.get(); } // when pos is IVecI synchronized public IVec get(){ return pos; } /** passing position field */ synchronized public IVec pos(){ return pos; } /** center is same with position */ synchronized public IVec center(){ return pos(); } synchronized public IPoint dup(){ return new IPoint(this); } synchronized public IVec2 to2d(){ return pos.to2d(); } synchronized public IVec2 to2d(IVecI projectionDir){ return pos.to2d(projectionDir); } synchronized public IVec2 to2d(IVecI xaxis, IVecI yaxis){ return pos.to2d(xaxis,yaxis); } synchronized public IVec2 to2d(IVecI xaxis, IVecI yaxis, IVecI origin){ return pos.to2d(xaxis,yaxis,origin); } synchronized public IVec4 to4d(){ return pos.to4d(); } synchronized public IVec4 to4d(double w){ return pos.to4d(w); } synchronized public IVec4 to4d(IDoubleI w){ return pos.to4d(w); } synchronized public IDouble getX(){ return pos.getX(); } synchronized public IDouble getY(){ return pos.getY(); } synchronized public IDouble getZ(){ return pos.getZ(); } synchronized public IPoint set(IVecI v){ pos.set(v); return this; } synchronized public IPoint set(double x, double y, double z){ pos.set(x,y,z); return this;} synchronized public IPoint set(IDoubleI x, IDoubleI y, IDoubleI z){ pos.set(x,y,z); return this; } synchronized public IPoint add(double x, double y, double z){ pos.add(x,y,z); return this; } synchronized public IPoint add(IDoubleI x, IDoubleI y, IDoubleI z){ pos.add(x,y,z); return this; } synchronized public IPoint add(IVecI v){ pos.add(v); return this; } synchronized public IPoint sub(double x, double y, double z){ pos.sub(x,y,z); return this; } synchronized public IPoint sub(IDoubleI x, IDoubleI y, IDoubleI z){ pos.sub(x,y,z); return this; } synchronized public IPoint sub(IVecI v){ pos.sub(v); return this; } synchronized public IPoint mul(IDoubleI v){ pos.mul(v); return this; } synchronized public IPoint mul(double v){ pos.mul(v); return this; } synchronized public IPoint div(IDoubleI v){ pos.div(v); return this; } synchronized public IPoint div(double v){ pos.div(v); return this; } synchronized public IPoint neg(){ pos.neg(); return this; } synchronized public IPoint rev(){ return neg(); } synchronized public IPoint flip(){ return neg(); } synchronized public IPoint zero(){ pos.zero(); return this; } /** scale add */ synchronized public IPoint add(IVecI v, double f){ pos.add(v,f); return this; } synchronized public IPoint add(IVecI v, IDoubleI f){ pos.add(v,f); return this; } /** scale add alias */ synchronized public IPoint add(double f, IVecI v){ return add(v,f); } synchronized public IPoint add(IDoubleI f, IVecI v){ return add(v,f); } synchronized public double dot(IVecI v){ return pos.dot(v); } synchronized public double dot(double vx, double vy, double vz){ return pos.dot(vx,vy,vz); } synchronized public double dot(ISwitchE e, IVecI v){ return pos.dot(e,v); } synchronized public IDouble dot(ISwitchR r, IVecI v){ return pos.dot(r,v); } // creating IPoint is too much (in terms of memory occupancy) //synchronized public IPoint cross(IVecI v){ return dup().set(pos.cross(v)); } synchronized public IVec cross(IVecI v){ return pos.cross(v); } synchronized public IVec cross(double vx, double vy, double vz){ return pos.cross(vx,vy,vz); } synchronized public double len(){ return pos.len(); } synchronized public double len(ISwitchE e){ return pos.len(e); } synchronized public IDouble len(ISwitchR r){ return pos.len(r); } synchronized public double len2(){ return pos.len2(); } synchronized public double len2(ISwitchE e){ return pos.len2(e); } synchronized public IDouble len2(ISwitchR r){ return pos.len2(r); } synchronized public IPoint len(IDoubleI l){ pos.len(l); return this; } synchronized public IPoint len(double l){ pos.len(l); return this; } synchronized public IPoint unit(){ pos.unit(); return this; } synchronized public double dist(IVecI v){ return pos.dist(v); } synchronized public double dist(double vx, double vy, double vz){ return pos.dist(vx,vy,vz); } synchronized public double dist(ISwitchE e, IVecI v){ return pos.dist(e,v); } synchronized public IDouble dist(ISwitchR r, IVecI v){ return pos.dist(r,v); } synchronized public double dist2(IVecI v){ return pos.dist2(v); } synchronized public double dist2(double vx, double vy, double vz){ return pos.dist2(vx,vy,vz); } synchronized public double dist2(ISwitchE e, IVecI v){ return pos.dist2(e,v); } synchronized public IDouble dist2(ISwitchR r, IVecI v){ return pos.dist2(r,v); } synchronized public boolean eq(IVecI v){ return pos.eq(v); } synchronized public boolean eq(double vx, double vy, double vz){ return pos.eq(vx,vy,vz); } synchronized public boolean eq(ISwitchE e, IVecI v){ return pos.eq(e,v); } synchronized public IBool eq(ISwitchR r, IVecI v){ return pos.eq(r,v); } synchronized public boolean eq(IVecI v, double tolerance){ return pos.eq(v,tolerance); } synchronized public boolean eq(double vx, double vy, double vz, double tolerance){ return pos.eq(vx,vy,vz,tolerance); } synchronized public boolean eq(ISwitchE e, IVecI v, double tolerance){ return pos.eq(e,v,tolerance); } synchronized public IBool eq(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eq(r,v,tolerance); } synchronized public boolean eqX(IVecI v){ return pos.eqX(v); } synchronized public boolean eqY(IVecI v){ return pos.eqY(v); } synchronized public boolean eqZ(IVecI v){ return pos.eqZ(v); } synchronized public boolean eqX(double vx){ return pos.eqX(vx); } synchronized public boolean eqY(double vy){ return pos.eqY(vy); } synchronized public boolean eqZ(double vz){ return pos.eqZ(vz); } synchronized public boolean eqX(ISwitchE e, IVecI v){ return pos.eqX(e,v); } synchronized public boolean eqY(ISwitchE e, IVecI v){ return pos.eqY(e,v); } synchronized public boolean eqZ(ISwitchE e, IVecI v){ return pos.eqZ(e,v); } synchronized public IBool eqX(ISwitchR r, IVecI v){ return pos.eqX(r,v); } synchronized public IBool eqY(ISwitchR r, IVecI v){ return pos.eqY(r,v); } synchronized public IBool eqZ(ISwitchR r, IVecI v){ return pos.eqZ(r,v); } synchronized public boolean eqX(IVecI v, double tolerance){ return pos.eqX(v,tolerance); } synchronized public boolean eqY(IVecI v, double tolerance){ return pos.eqY(v,tolerance); } synchronized public boolean eqZ(IVecI v, double tolerance){ return pos.eqZ(v,tolerance); } synchronized public boolean eqX(double vx, double tolerance){ return pos.eqX(vx,tolerance); } synchronized public boolean eqY(double vy, double tolerance){ return pos.eqY(vy,tolerance); } synchronized public boolean eqZ(double vz, double tolerance){ return pos.eqZ(vz,tolerance); } synchronized public boolean eqX(ISwitchE e, IVecI v, double tolerance){ return pos.eqX(e,v,tolerance); } synchronized public boolean eqY(ISwitchE e, IVecI v, double tolerance){ return pos.eqY(e,v,tolerance); } synchronized public boolean eqZ(ISwitchE e, IVecI v, double tolerance){ return pos.eqZ(e,v,tolerance); } synchronized public IBool eqX(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eqX(r,v,tolerance); } synchronized public IBool eqY(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eqY(r,v,tolerance); } synchronized public IBool eqZ(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eqZ(r,v,tolerance); } synchronized public double angle(IVecI v){ return pos.angle(v); } synchronized public double angle(double vx, double vy, double vz){ return pos.angle(vx,vy,vz); } synchronized public double angle(ISwitchE e, IVecI v){ return pos.angle(e,v); } synchronized public IDouble angle(ISwitchR r, IVecI v){ return pos.angle(r,v); } synchronized public double angle(IVecI v, IVecI axis){ return pos.angle(v,axis); } synchronized public double angle(double vx, double vy, double vz, double axisX, double axisY, double axisZ){ return pos.angle(vx,vy,vz,axisX,axisY,axisZ); } synchronized public double angle(ISwitchE e, IVecI v, IVecI axis){ return pos.angle(e,v,axis); } synchronized public IDouble angle(ISwitchR r, IVecI v, IVecI axis){ return pos.angle(r,v,axis); } synchronized public IPoint rot(IDoubleI angle){ pos.rot(angle); return this; } synchronized public IPoint rot(double angle){ pos.rot(angle); return this; } synchronized public IPoint rot(IVecI axis, IDoubleI angle){ pos.rot(axis,angle); return this; } synchronized public IPoint rot(IVecI axis, double angle){ pos.rot(axis,angle); return this; } synchronized public IPoint rot(double axisX, double axisY, double axisZ, double angle){ pos.rot(axisX,axisY,axisZ,angle); return this; } synchronized public IPoint rot(IVecI center, IVecI axis, double angle){ pos.rot(center, axis,angle); return this; } synchronized public IPoint rot(double centerX, double centerY, double centerZ, double axisX, double axisY, double axisZ, double angle){ pos.rot(centerX, centerY, centerZ, axisX, axisY, axisZ, angle); return this; } synchronized public IPoint rot(IVecI center, IVecI axis, IDoubleI angle){ pos.rot(center, axis,angle); return this; } /** Rotate to destination direction vector. */ synchronized public IPoint rot(IVecI axis, IVecI destDir){ pos.rot(axis,destDir); return this; } /** Rotate to destination point location. */ synchronized public IPoint rot(IVecI center, IVecI axis, IVecI destPt){ pos.rot(center,axis,destPt); return this; } synchronized public IPoint rot2(IDoubleI angle){ pos.rot2(angle); return this; } synchronized public IPoint rot2(double angle){ pos.rot2(angle); return this; } synchronized public IPoint rot2(IVecI center, double angle){ pos.rot2(center, angle); return this; } synchronized public IPoint rot2(double centerX, double centerY, double angle){ pos.rot2(centerX, centerY, angle); return this; } synchronized public IPoint rot2(IVecI center, IDoubleI angle){ pos.rot2(center, angle); return this; } /** Rotate to destination direction vector. */ synchronized public IPoint rot2(IVecI destDir){ pos.rot2(destDir); return this; } /** Rotate to destination point location. */ synchronized public IPoint rot2(IVecI center, IVecI destPt){ pos.rot2(center,destPt); return this; } /** alias of mul */ synchronized public IPoint scale(IDoubleI f){ pos.scale(f); return this; } /** alias of mul */ synchronized public IPoint scale(double f){ pos.scale(f); return this; } synchronized public IPoint scale(IVecI center, IDoubleI f){ pos.scale(center,f); return this; } synchronized public IPoint scale(IVecI center, double f){ pos.scale(center,f); return this; } synchronized public IPoint scale(double centerX, double centerY, double centerZ, double f){ pos.scale(centerX, centerY, centerZ, f); return this; } /** scale only in 1 direction */ synchronized public IPoint scale1d(IVecI axis, double f){ pos.scale1d(axis,f); return this; } synchronized public IPoint scale1d(double axisX, double axisY, double axisZ, double f){ pos.scale1d(axisX,axisY,axisZ,f); return this; } synchronized public IPoint scale1d(IVecI axis, IDoubleI f){ pos.scale1d(axis,f); return this; } synchronized public IPoint scale1d(IVecI center, IVecI axis, double f){ pos.scale1d(center,axis,f); return this; } synchronized public IPoint scale1d(double centerX, double centerY, double centerZ, double axisX, double axisY, double axisZ, double f){ pos.scale1d(centerX,centerY,centerZ,axisX,axisY,axisZ,f); return this; } synchronized public IPoint scale1d(IVecI center, IVecI axis, IDoubleI f){ pos.scale1d(center,axis,f); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(IVecI planeDir){ pos.ref(planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(double planeX, double planeY, double planeZ){ pos.ref(planeX,planeY,planeZ); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(IVecI center, IVecI planeDir){ pos.ref(center,planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(double centerX, double centerY, double centerZ, double planeX, double planeY, double planeZ){ pos.ref(centerX,centerY,centerZ,planeX,planeY,planeZ); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(IVecI planeDir){ pos.ref(planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(double planeX, double planeY, double planeZ){ pos.ref(planeX,planeY,planeZ); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(IVecI center, IVecI planeDir){ pos.ref(center,planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(double centerX, double centerY, double centerZ, double planeX, double planeY, double planeZ){ pos.ref(centerX,centerY,centerZ,planeX,planeY,planeZ); return this; } /** shear operation */ synchronized public IPoint shear(double sxy, double syx, double syz, double szy, double szx, double sxz){ pos.shear(sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shear(IDoubleI sxy, IDoubleI syx, IDoubleI syz, IDoubleI szy, IDoubleI szx, IDoubleI sxz){ pos.shear(sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shear(IVecI center, double sxy, double syx, double syz, double szy, double szx, double sxz){ pos.shear(center,sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shear(IVecI center, IDoubleI sxy, IDoubleI syx, IDoubleI syz, IDoubleI szy, IDoubleI szx, IDoubleI sxz){ pos.shear(center,sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shearXY(double sxy, double syx){ pos.shearXY(sxy,syx); return this; } synchronized public IPoint shearXY(IDoubleI sxy, IDoubleI syx){ pos.shearXY(sxy,syx); return this; } synchronized public IPoint shearXY(IVecI center, double sxy, double syx){ pos.shearXY(center,sxy,syx); return this; } synchronized public IPoint shearXY(IVecI center, IDoubleI sxy, IDoubleI syx){ pos.shearXY(center,sxy,syx); return this; } synchronized public IPoint shearYZ(double syz, double szy){ pos.shearYZ(syz,szy); return this; } synchronized public IPoint shearYZ(IDoubleI syz, IDoubleI szy){ pos.shearYZ(syz,szy); return this; } synchronized public IPoint shearYZ(IVecI center, double syz, double szy){ pos.shearYZ(center,syz,szy); return this; } synchronized public IPoint shearYZ(IVecI center, IDoubleI syz, IDoubleI szy){ pos.shearYZ(center,syz,szy); return this; } synchronized public IPoint shearZX(double szx, double sxz){ pos.shearZX(szx,sxz); return this; } synchronized public IPoint shearZX(IDoubleI szx, IDoubleI sxz){ pos.shearZX(szx,sxz); return this; } synchronized public IPoint shearZX(IVecI center, double szx, double sxz){ pos.shearZX(center,szx,sxz); return this; } synchronized public IPoint shearZX(IVecI center, IDoubleI szx, IDoubleI sxz){ pos.shearZX(center,szx,sxz); return this; } /** translate is alias of add() */ synchronized public IPoint translate(double x, double y, double z){ pos.translate(x,y,z); return this; } synchronized public IPoint translate(IDoubleI x, IDoubleI y, IDoubleI z){ pos.translate(x,y,z); return this; } synchronized public IPoint translate(IVecI v){ pos.translate(v); return this; } synchronized public IPoint transform(IMatrix3I mat){ pos.transform(mat); return this; } synchronized public IPoint transform(IMatrix4I mat){ pos.transform(mat); return this; } synchronized public IPoint transform(IVecI xvec, IVecI yvec, IVecI zvec){ pos.transform(xvec,yvec,zvec); return this; } synchronized public IPoint transform(IVecI xvec, IVecI yvec, IVecI zvec, IVecI translate){ pos.transform(xvec,yvec,zvec,translate); return this; } /** mv() is alias of add() */ synchronized public IPoint mv(double x, double y, double z){ return add(x,y,z); } synchronized public IPoint mv(IDoubleI x, IDoubleI y, IDoubleI z){ return add(x,y,z); } synchronized public IPoint mv(IVecI v){ return add(v); } // method name cp() is used as getting control point method in curve and surface but here used also as copy because of the priority of variable fitting of diversed users' mind set over the clarity of the code organization /** cp() is alias of dup() */ synchronized public IPoint cp(){ return dup(); } /** cp() is alias of dup().add() */ synchronized public IPoint cp(double x, double y, double z){ return dup().add(x,y,z); } synchronized public IPoint cp(IDoubleI x, IDoubleI y, IDoubleI z){ return dup().add(x,y,z); } synchronized public IPoint cp(IVecI v){ return dup().add(v); } // methods creating new instance // returns IPoint?, not IVec? // returns IVec, not IPoint (2011/10/12) //synchronized public IPoint diff(IVecI v){ return dup().sub(v); } synchronized public IVec dif(IVecI v){ return pos.dif(v); } synchronized public IVec dif(double vx, double vy, double vz){ return pos.dif(vx,vy,vz); } synchronized public IVec diff(IVecI v){ return dif(v); } synchronized public IVec diff(double vx, double vy, double vz){ return dif(vx,vy,vz); } //synchronized public IPoint mid(IVecI v){ return dup().add(v).div(2); } synchronized public IVec mid(IVecI v){ return pos.mid(v); } synchronized public IVec mid(double vx, double vy, double vz){ return pos.mid(vx,vy,vz); } //synchronized public IPoint sum(IVecI v){ return dup().add(v); } synchronized public IVec sum(IVecI v){ return pos.sum(v); } synchronized public IVec sum(double vx, double vy, double vz){ return pos.sum(vx,vy,vz); } //synchronized public IPoint sum(IVecI... v){ IPoint ret = this.dup(); for(IVecI vi: v) ret.add(vi); return ret; } synchronized public IVec sum(IVecI... v){ return pos.sum(v); } //synchronized public IPoint bisect(IVecI v){ return dup().unit().add(v.dup().unit()); } synchronized public IVec bisect(IVecI v){ return pos.bisect(v); } synchronized public IVec bisect(double vx, double vy, double vz){ return pos.bisect(vx,vy,vz); } /** weighted sum. @return IVec */ //synchronized public IPoint sum(IVecI v2, double w1, double w2){ return dup().mul(w1).add(v2,w2); } synchronized public IVec sum(IVecI v2, double w1, double w2){ return pos.sum(v2,w1,w2); } //synchronized public IPoint sum(IVecI v2, double w2){ return dup().mul(1.0-w2).add(v2,w2); } synchronized public IVec sum(IVecI v2, double w2){ return pos.sum(v2,w2); } //synchronized public IPoint sum(IVecI v2, IDoubleI w1, IDoubleI w2){ return dup().mul(w1).add(v2,w2); } synchronized public IVec sum(IVecI v2, IDoubleI w1, IDoubleI w2){ return sum(v2,w1,w2); } //synchronized public IPoint sum(IVecI v2, IDoubleI w2){ return dup().mul(new IDouble(1.0).sub(w2)).add(v2,w2); } synchronized public IVec sum(IVecI v2, IDoubleI w2){ return sum(v2,w2); } /** alias of cross. (not unitized ... ?) */ //synchronized public IPoint nml(IVecI v){ return cross(v); } synchronized public IVec nml(IVecI v){ return pos.nml(v); } synchronized public IVec nml(double vx, double vy, double vz){ return pos.nml(vx,vy,vz); } /** create normal vector from 3 points of self, pt1 and pt2 */ //synchronized public IPoint nml(IVecI pt1, IVecI pt2){ return this.diff(pt1).cross(this.diff(pt2)).unit(); } synchronized public IVec nml(IVecI pt1, IVecI pt2){ return pos.nml(pt1,pt2); } synchronized public IVec nml(double vx1, double vy1, double vz1, double vx2, double vy2, double vz2){ return pos.nml(vx1,vy1,vz1,vx2,vy2,vz2); } /** checking x, y, and z is valid number (not Infinite, nor NaN). */ synchronized public boolean isValid(){ if(pos==null){ return false; } return pos.isValid(); } synchronized public String toString(){ if(pos==null) return super.toString(); return pos.toString(); } /** default setting in each object class; to be overridden in a child class */ public IAttribute defaultAttribute(){ IAttribute a = new IAttribute(); a.weight = IConfig.pointSize; return a; } /** set size of dot in graphic ; it's just alias of weight() */ synchronized public IPoint setSize(double sz){ return weight(sz); } synchronized public IPoint size(double sz){ return weight(sz); } /* synchronized public IPoint setSize(double sz){ return size(sz); } synchronized public IPoint size(double sz){ for(int i=0; graphics!=null && i<graphics.size(); i++) if(graphics.get(i) instanceof IPointGraphic) ((IPointGraphic)graphics.get(i)).size(sz); return this; } */ synchronized public double getSize(){ return size(); } public double size(){ if(graphics==null){ IOut.err("no graphics is set"); // return -1; } for(int i=0; graphics!=null && i<graphics.size(); i++) if(graphics.get(i) instanceof IPointGraphic) return ((IPointGraphic)graphics.get(i)).size(); return -1; } synchronized public IPoint name(String nm){ super.name(nm); return this; } synchronized public IPoint layer(ILayer l){ super.layer(l); return this; } synchronized public IPoint layer(String l){ super.layer(l); return this; } synchronized public IPoint attr(IAttribute at){ super.attr(at); return this; } synchronized public IPoint hide(){ super.hide(); return this; } synchronized public IPoint show(){ super.show(); return this; } synchronized public IPoint clr(IColor c){ super.clr(c); return this; } synchronized public IPoint clr(IColor c, int alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(IColor c, float alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(IColor c, double alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(IObject o){ super.clr(o); return this; } synchronized public IPoint clr(Color c){ super.clr(c); return this; } synchronized public IPoint clr(Color c, int alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(Color c, float alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(Color c, double alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(int gray){ super.clr(gray); return this; } synchronized public IPoint clr(float fgray){ super.clr(fgray); return this; } synchronized public IPoint clr(double dgray){ super.clr(dgray); return this; } synchronized public IPoint clr(int gray, int alpha){ super.clr(gray,alpha); return this; } synchronized public IPoint clr(float fgray, float falpha){ super.clr(fgray,falpha); return this; } synchronized public IPoint clr(double dgray, double dalpha){ super.clr(dgray,dalpha); return this; } synchronized public IPoint clr(int r, int g, int b){ super.clr(r,g,b); return this; } synchronized public IPoint clr(float fr, float fg, float fb){ super.clr(fr,fg,fb); return this; } synchronized public IPoint clr(double dr, double dg, double db){ super.clr(dr,dg,db); return this; } synchronized public IPoint clr(int r, int g, int b, int a){ super.clr(r,g,b,a); return this; } synchronized public IPoint clr(float fr, float fg, float fb, float fa){ super.clr(fr,fg,fb,fa); return this; } synchronized public IPoint clr(double dr, double dg, double db, double da){ super.clr(dr,dg,db,da); return this; } synchronized public IPoint hsb(float h, float s, float b, float a){ super.hsb(h,s,b,a); return this; } synchronized public IPoint hsb(double h, double s, double b, double a){ super.hsb(h,s,b,a); return this; } synchronized public IPoint hsb(float h, float s, float b){ super.hsb(h,s,b); return this; } synchronized public IPoint hsb(double h, double s, double b){ super.hsb(h,s,b); return this; } synchronized public IPoint setColor(IColor c){ super.setColor(c); return this; } synchronized public IPoint setColor(IColor c, int alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(IColor c, float alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(IColor c, double alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(Color c){ super.setColor(c); return this; } synchronized public IPoint setColor(Color c, int alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(Color c, float alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(Color c, double alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(int gray){ super.setColor(gray); return this; } synchronized public IPoint setColor(float fgray){ super.setColor(fgray); return this; } synchronized public IPoint setColor(double dgray){ super.setColor(dgray); return this; } synchronized public IPoint setColor(int gray, int alpha){ super.setColor(gray,alpha); return this; } synchronized public IPoint setColor(float fgray, float falpha){ super.setColor(fgray,falpha); return this; } synchronized public IPoint setColor(double dgray, double dalpha){ super.setColor(dgray,dalpha); return this; } synchronized public IPoint setColor(int r, int g, int b){ super.setColor(r,g,b); return this; } synchronized public IPoint setColor(float fr, float fg, float fb){ super.setColor(fr,fg,fb); return this; } synchronized public IPoint setColor(double dr, double dg, double db){ super.setColor(dr,dg,db); return this; } synchronized public IPoint setColor(int r, int g, int b, int a){ super.setColor(r,g,b,a); return this; } synchronized public IPoint setColor(float fr, float fg, float fb, float fa){ super.setColor(fr,fg,fb,fa); return this; } synchronized public IPoint setColor(double dr, double dg, double db, double da){ super.setColor(dr,dg,db,da); return this; } synchronized public IPoint setHSBColor(float h, float s, float b, float a){ super.setHSBColor(h,s,b,a); return this; } synchronized public IPoint setHSBColor(double h, double s, double b, double a){ super.setHSBColor(h,s,b,a); return this; } synchronized public IPoint setHSBColor(float h, float s, float b){ super.setHSBColor(h,s,b); return this; } synchronized public IPoint setHSBColor(double h, double s, double b){ super.setHSBColor(h,s,b); return this; } synchronized public IPoint weight(double w){ super.weight(w); return this; } synchronized public IPoint weight(float w){ super.weight(w); return this; } }
sghr/iGeo
IPoint.java
Java
lgpl-3.0
31,733
<?php /** * This file is part of contao-community-alliance/dc-general. * * (c) 2013-2019 Contao Community Alliance. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * This project is provided in good faith and hope to be usable by anyone. * * @package contao-community-alliance/dc-general * @author Christian Schiffler <c.schiffler@cyberspectrum.de> * @author Sven Baumann <baumann.sv@gmail.com> * @copyright 2013-2019 Contao Community Alliance. * @license https://github.com/contao-community-alliance/dc-general/blob/master/LICENSE LGPL-3.0-or-later * @filesource */ namespace ContaoCommunityAlliance\DcGeneral\Data; /** * This class is the base implementation for LanguageInformationCollectionInterface. */ class DefaultLanguageInformationCollection implements LanguageInformationCollectionInterface { /** * The language information stored in this collection. * * @var LanguageInformationInterface[] */ protected $languages = []; /** * {@inheritDoc} */ public function add(LanguageInformationInterface $language) { $this->languages[] = $language; return $this; } /** * Get a iterator for this collection. * * @return \ArrayIterator */ public function getIterator() { return new \ArrayIterator($this->languages); } /** * Count the contained language information. * * @return int */ public function count() { return \count($this->languages); } }
contao-community-alliance/dc-general
src/Data/DefaultLanguageInformationCollection.php
PHP
lgpl-3.0
1,624
/* * PROJECT: NyARToolkitCS * -------------------------------------------------------------------------------- * * The NyARToolkitCS is C# edition NyARToolKit class library. * Copyright (C)2008-2012 Ryo Iizuka * * This work is based on the ARToolKit developed by * Hirokazu Kato * Mark Billinghurst * HITLab, University of Washington, Seattle * http://www.hitl.washington.edu/artoolkit/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as publishe * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * For further information please contact. * http://nyatla.jp/nyatoolkit/ * <airmail(at)ebony.plala.or.jp> or <nyatla(at)nyatla.jp> * */ using System; namespace jp.nyatla.nyartoolkit.cs.core { /** * このクラスは、樽型歪み設定/解除クラスです。 */ public interface INyARCameraDistortionFactor { /** * この関数は、座標点を理想座標系から観察座標系へ変換します。 * @param i_in * 変換元の座標 * @param o_out * 変換後の座標を受け取るオブジェクト */ void ideal2Observ(NyARDoublePoint2d i_in, NyARDoublePoint2d o_out); /** * この関数は、座標点を理想座標系から観察座標系へ変換します。 * @param i_in * 変換元の座標 * @param o_out * 変換後の座標を受け取るオブジェクト */ void ideal2Observ(NyARDoublePoint2d i_in, NyARIntPoint2d o_out); /** * この関数は、座標点を理想座標系から観察座標系へ変換します。 * @param i_in * 変換元の座標 * @param o_out * 変換後の座標を受け取るオブジェクト */ void ideal2Observ(double i_x, double i_y, NyARDoublePoint2d o_out); /** * この関数は、座標点を理想座標系から観察座標系へ変換します。 * @param i_x * 変換元の座標 * @param i_y * 変換元の座標 * @param o_out * 変換後の座標を受け取るオブジェクト */ void ideal2Observ(double i_x, double i_y, NyARIntPoint2d o_out); /** * この関数は、複数の座標点を、一括して理想座標系から観察座標系へ変換します。 * i_inとo_outには、同じインスタンスを指定できます。 * @param i_in * 変換元の座標配列 * @param o_out * 変換後の座標を受け取る配列 * @param i_size * 変換する座標の個数。 */ void ideal2ObservBatch(NyARDoublePoint2d[] i_in, NyARDoublePoint2d[] o_out, int i_size); /** * この関数は、複数の座標点を、一括して理想座標系から観察座標系へ変換します。 * i_inとo_outには、同じインスタンスを指定できます。 * @param i_in * 変換元の座標配列 * @param o_out * 変換後の座標を受け取る配列 * @param i_size * 変換する座標の個数。 */ void ideal2ObservBatch(NyARDoublePoint2d[] i_in, NyARIntPoint2d[] o_out, int i_size); /** * この関数は、座標を観察座標系から理想座標系へ変換します。 * @param ix * 変換元の座標 * @param iy * 変換元の座標 * @param o_point * 変換後の座標を受け取るオブジェクト */ void observ2Ideal(double ix, double iy, NyARDoublePoint2d o_point); /** * {@link #observ2Ideal(double, double, NyARDoublePoint2d)}のラッパーです。 * i_inとo_pointには、同じオブジェクトを指定できます。 * @param i_in * @param o_point */ void observ2Ideal(NyARDoublePoint2d i_in, NyARDoublePoint2d o_point); /** * この関数は、観察座標を理想座標へ変換します。 * 入力できる値範囲は、コンストラクタに設定したスクリーンサイズの範囲内です。 * @param ix * 観察座標の値 * @param iy * 観察座標の値 * @param o_point * 理想座標を受け取るオブジェクト。 */ void observ2Ideal(int ix, int iy, NyARDoublePoint2d o_point); /** * 座標配列全てに対して、{@link #observ2Ideal(double, double, NyARDoublePoint2d)}を適応します。 * @param i_in * @param o_out * @param i_size */ void observ2IdealBatch(NyARDoublePoint2d[] i_in, NyARDoublePoint2d[] o_out, int i_size); void observ2IdealBatch(NyARIntPoint2d[] i_in, NyARDoublePoint2d[] o_out, int i_size); } }
nyatla/NyARToolkitCS
lib/src/cs/core/param/distfactor/INyARCameraDistortionFactor.cs
C#
lgpl-3.0
5,500
package org.yawlfoundation.yawl.worklet.client; import org.yawlfoundation.yawl.editor.ui.specification.SpecificationModel; import org.yawlfoundation.yawl.engine.YSpecificationID; import java.io.IOException; import java.util.Map; /** * @author Michael Adams * @date 18/02/2016 */ public class TaskIDChangeMap { private Map<String, String> _changedIdentifiers; public TaskIDChangeMap(Map<String, String> changeMap) { _changedIdentifiers = changeMap; } public String getID(String oldID) { String newID = _changedIdentifiers.get(oldID); return newID != null ? newID : oldID; } public String getOldID(String newID) { for (String oldID : _changedIdentifiers.keySet()) { if (_changedIdentifiers.get(oldID).equals(newID)) { return oldID; } } return newID; } // called when a user changes a taskID public void add(String oldID, String newID) { // need to handle the case where this id has been updated // more than once between saves _changedIdentifiers.put(getOldID(oldID), newID); } public void saveChanges() { if (! _changedIdentifiers.isEmpty()) { YSpecificationID specID = SpecificationModel.getHandler(). getSpecification().getSpecificationID(); try { if (WorkletClient.getInstance().updateRdrSetTaskIDs(specID, _changedIdentifiers)) { _changedIdentifiers.clear(); } } catch (IOException ignore) { // } } } }
yawlfoundation/editor
source/org/yawlfoundation/yawl/worklet/client/TaskIDChangeMap.java
Java
lgpl-3.0
1,648
/** The GPL License (GPL) Copyright (c) 2012 Andreas Herz 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 **/ /** * @class graphiti.Connection * A Connection is the line between two {@link graphiti.Port}s. * * @inheritable * @author Andreas Herz * @extends graphiti.shape.basic.Line */ graphiti.Connection = graphiti.shape.basic.PolyLine.extend({ NAME : "graphiti.Connection", DEFAULT_ROUTER: new graphiti.layout.connection.DirectRouter(), //DEFAULT_ROUTER: new graphiti.layout.connection.ManhattanConnectionRouter(), //DEFAULT_ROUTER: new graphiti.layout.connection.BezierConnectionRouter(), //DEFAULT_ROUTER: new graphiti.layout.connection.ConnectionRouter(), /** * @constructor * Creates a new figure element which are not assigned to any canvas. */ init: function() { this._super(); this.sourcePort = null; this.targetPort = null; this.oldPoint=null; this.sourceDecorator = null; /*:graphiti.ConnectionDecorator*/ this.targetDecorator = null; /*:graphiti.ConnectionDecorator*/ // decoration of the polyline // this.startDecoSet = null; this.endDecoSet=null; this.regulated = false; this.draggable = false; this.selectable = false; //this.Activator = new g.Buttons.Activate(); //this.Repressor = new g.Buttons.Inhibit(); //this.remove = new g.Buttons.Remove(); //this.addFigure(this.remove, new graphiti.layout.locator.ConnectionLocator()); this.sourceAnchor = new graphiti.ConnectionAnchor(this); this.targetAnchor = new graphiti.ConnectionAnchor(this); this.router = this.DEFAULT_ROUTER; this.setColor("#4cbf2f"); this.setStroke(3); }, /** * @private **/ disconnect : function() { if (this.sourcePort !== null) { this.sourcePort.detachMoveListener(this); this.fireSourcePortRouteEvent(); } if (this.targetPort !== null) { this.targetPort.detachMoveListener(this); this.fireTargetPortRouteEvent(); } }, /** * @private **/ reconnect : function() { if (this.sourcePort !== null) { this.sourcePort.attachMoveListener(this); this.fireSourcePortRouteEvent(); } if (this.targetPort !== null) { this.targetPort.attachMoveListener(this); this.fireTargetPortRouteEvent(); } this.routingRequired =true; this.repaint(); }, /** * You can't drag&drop the resize handles of a connector. * @type boolean **/ isResizeable : function() { return this.isDraggable(); }, /** * @method * Add a child figure to the Connection. The hands over figure doesn't support drag&drop * operations. It's only a decorator for the connection.<br> * Mainly for labels or other fancy decorations :-) * * @param {graphiti.Figure} figure the figure to add as decoration to the connection. * @param {graphiti.layout.locator.ConnectionLocator} locator the locator for the child. **/ addFigure : function(child, locator) { // just to ensure the right interface for the locator. // The base class needs only 'graphiti.layout.locator.Locator'. if(!(locator instanceof graphiti.layout.locator.ConnectionLocator)){ throw "Locator must implement the class graphiti.layout.locator.ConnectionLocator"; } this._super(child, locator); }, /** * @method * Set the ConnectionDecorator for this object. * * @param {graphiti.decoration.connection.Decorator} the new source decorator for the connection **/ setSourceDecorator:function( decorator) { this.sourceDecorator = decorator; this.routingRequired = true; this.repaint(); }, /** * @method * Get the current source ConnectionDecorator for this object. * * @type graphiti.ConnectionDecorator **/ getSourceDecorator:function() { return this.sourceDecorator; }, /** * @method * Set the ConnectionDecorator for this object. * * @param {graphiti.decoration.connection.Decorator} the new target decorator for the connection **/ setTargetDecorator:function( decorator) { this.targetDecorator = decorator; this.routingRequired =true; this.repaint(); }, /** * @method * Get the current target ConnectionDecorator for this object. * * @type graphiti.ConnectionDecorator **/ getTargetDecorator:function() { return this.targetDecorator; }, /** * @method * Set the ConnectionAnchor for this object. An anchor is responsible for the endpoint calculation * of an connection. * * @param {graphiti.ConnectionAnchor} the new source anchor for the connection **/ setSourceAnchor:function(/*:graphiti.ConnectionAnchor*/ anchor) { this.sourceAnchor = anchor; this.sourceAnchor.setOwner(this.sourcePort); this.routingRequired =true; this.repaint(); }, /** * @method * Set the ConnectionAnchor for this object. * * @param {graphiti.ConnectionAnchor} the new target anchor for the connection **/ setTargetAnchor:function(/*:graphiti.ConnectionAnchor*/ anchor) { this.targetAnchor = anchor; this.targetAnchor.setOwner(this.targetPort); this.routingRequired =true; this.repaint(); }, /** * @method * Set the ConnectionRouter. * **/ setRouter:function(/*:graphiti.ConnectionRouter*/ router) { if(router !==null){ this.router = router; } else{ this.router = new graphiti.layout.connection.NullRouter(); } this.routingRequired =true; // repaint the connection with the new router this.repaint(); }, /** * @method * Return the current active router of this connection. * * @type graphiti.ConnectionRouter **/ getRouter:function() { return this.router; }, /** * @method * Calculate the path of the polyline * * @private */ calculatePath: function(){ if(this.sourcePort===null || this.targetPort===null){ return; } this._super(); }, /** * @private **/ repaint:function(attributes) { if(this.repaintBlocked===true || this.shape===null){ return; } if(this.sourcePort===null || this.targetPort===null){ return; } this._super(attributes); // paint the decorator if any exists // if(this.getSource().getParent().isMoving===false && this.getTarget().getParent().isMoving===false ) { if(this.targetDecorator!==null && this.endDecoSet===null){ this.endDecoSet= this.targetDecorator.paint(this.getCanvas().paper); } if(this.sourceDecorator!==null && this.startDecoSet===null){ this.startDecoSet= this.sourceDecorator.paint(this.getCanvas().paper); } } // translate/transform the decorations to the end/start of the connection // and rotate them as well // if(this.startDecoSet!==null){ this.startDecoSet.transform("r"+this.getStartAngle()+"," + this.getStartX() + "," + this.getStartY()+" t" + this.getStartX() + "," + this.getStartY()); } if(this.endDecoSet!==null){ this.endDecoSet.transform("r"+this.getEndAngle()+"," + this.getEndX() + "," + this.getEndY()+" t" + this.getEndX() + "," + this.getEndY()); } }, postProcess: function(postPorcessCache){ this.router.postProcess(this, this.getCanvas(), postPorcessCache); }, /** * @method * Called by the framework during drag&drop operations. * * @param {graphiti.Figure} draggedFigure The figure which is currently dragging * * @return {Boolean} true if this port accepts the dragging port for a drop operation * @template **/ onDragEnter : function( draggedFigure ) { this.setGlow(true); return true; }, /** * @method * Called if the DragDrop object leaving the current hover figure. * * @param {graphiti.Figure} draggedFigure The figure which is currently dragging * @template **/ onDragLeave:function( draggedFigure ) { this.setGlow(false); }, /** * Return the recalculated position of the start point if we have set an anchor. * * @return graphiti.geo.Point **/ getStartPoint:function() { if(this.isMoving===false){ return this.sourceAnchor.getLocation(this.targetAnchor.getReferencePoint()); } else{ return this._super(); } }, /** * Return the recalculated position of the start point if we have set an anchor. * * @return graphiti.geo.Point **/ getEndPoint:function() { if(this.isMoving===false){ return this.targetAnchor.getLocation(this.sourceAnchor.getReferencePoint()); } else{ return this._super(); } }, /** * @method * Set the new source port of this connection. This enforce a repaint of the connection. * * @param {graphiti.Port} port The new source port of this connection. * **/ setSource:function( port) { if(this.sourcePort!==null){ this.sourcePort.detachMoveListener(this); } this.sourcePort = port; if(this.sourcePort===null){ return; } this.routingRequired = true; this.sourceAnchor.setOwner(this.sourcePort); this.fireSourcePortRouteEvent(); this.sourcePort.attachMoveListener(this); this.setStartPoint(port.getAbsoluteX(), port.getAbsoluteY()); }, /** * @method * Returns the source port of this connection. * * @type graphiti.Port **/ getSource:function() { return this.sourcePort; }, /** * @method * Set the target port of this connection. This enforce a repaint of the connection. * * @param {graphiti.Port} port The new target port of this connection **/ setTarget:function( port) { if(this.targetPort!==null){ this.targetPort.detachMoveListener(this); } this.targetPort = port; if(this.targetPort===null){ return; } this.routingRequired = true; this.targetAnchor.setOwner(this.targetPort); this.fireTargetPortRouteEvent(); this.targetPort.attachMoveListener(this); this.setEndPoint(port.getAbsoluteX(), port.getAbsoluteY()); }, /** * @method * Returns the target port of this connection. * * @type graphiti.Port **/ getTarget:function() { return this.targetPort; }, /** * **/ onOtherFigureIsMoving:function(/*:graphiti.Figure*/ figure) { if(figure===this.sourcePort){ this.setStartPoint(this.sourcePort.getAbsoluteX(), this.sourcePort.getAbsoluteY()); } else{ this.setEndPoint(this.targetPort.getAbsoluteX(), this.targetPort.getAbsoluteY()); } this._super(figure); }, /** * Returns the angle of the connection at the output port (source) * **/ getStartAngle:function() { // return a good default value if the connection is not routed at the // moment if( this.lineSegments.getSize()===0){ return 0; } var p1 = this.lineSegments.get(0).start; var p2 = this.lineSegments.get(0).end; // if(this.router instanceof graphiti.layout.connection.BezierConnectionRouter) // { // p2 = this.lineSegments.get(5).end; // } var length = Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); var angle = -(180/Math.PI) *Math.asin((p1.y-p2.y)/length); if(angle<0) { if(p2.x<p1.x){ angle = Math.abs(angle) + 180; } else{ angle = 360- Math.abs(angle); } } else { if(p2.x<p1.x){ angle = 180-angle; } } return angle; }, getEndAngle:function() { // return a good default value if the connection is not routed at the // moment if (this.lineSegments.getSize() === 0) { return 90; } var p1 = this.lineSegments.get(this.lineSegments.getSize()-1).end; var p2 = this.lineSegments.get(this.lineSegments.getSize()-1).start; // if(this.router instanceof graphiti.layout.connection.BezierConnectionRouter) // { // p2 = this.lineSegments.get(this.lineSegments.getSize()-5).end; // } var length = Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)); var angle = -(180/Math.PI) *Math.asin((p1.y-p2.y)/length); if(angle<0) { if(p2.x<p1.x){ angle = Math.abs(angle) + 180; } else{ angle = 360- Math.abs(angle); } } else { if(p2.x<p1.x){ angle = 180-angle; } } return angle; }, /** * @private **/ fireSourcePortRouteEvent:function() { // enforce a repaint of all connections which are related to this port // this is required for a "FanConnectionRouter" or "ShortesPathConnectionRouter" // var connections = this.sourcePort.getConnections(); for(var i=0; i<connections.getSize();i++) { connections.get(i).repaint(); } }, /** * @private **/ fireTargetPortRouteEvent:function() { // enforce a repaint of all connections which are related to this port // this is required for a "FanConnectionRouter" or "ShortesPathConnectionRouter" // var connections = this.targetPort.getConnections(); for(var i=0; i<connections.getSize();i++) { connections.get(i).repaint(); } }, /** * @method * Returns the Command to perform the specified Request or null. * * @param {graphiti.command.CommandType} request describes the Command being requested * @return {graphiti.command.Command} null or a Command **/ createCommand:function( request) { if(request.getPolicy() === graphiti.command.CommandType.MOVE_BASEPOINT) { // DragDrop of a connection doesn't create a undo command at this point. This will be done in // the onDrop method return new graphiti.command.CommandReconnect(this); } return this._super(request); }, /** * @method * Return an objects with all important attributes for XML or JSON serialization * * @returns {Object} */ getPersistentAttributes : function() { var memento = this._super(); delete memento.x; delete memento.y; delete memento.width; delete memento.height; memento.source = { node:this.getSource().getParent().getId(), port: this.getSource().getName() }; memento.target = { node:this.getTarget().getParent().getId(), port:this.getTarget().getName() }; return memento; }, /** * @method * Read all attributes from the serialized properties and transfer them into the shape. * * @param {Object} memento * @returns */ setPersistentAttributes : function(memento) { this._super(memento); // no extra param to read. // Reason: done by the Layoute/Router }, onClick: function() { // wait to be implemented /*$("#right-container").css({right: '0px'}); var hasClassIn = $("#collapseTwo").hasClass('in'); if(!hasClassIn) { $("#collapseOne").toggleClass('in'); $("#collapseOne").css({height: '0'}); $("#collapseTwo").toggleClass('in'); $("#collapseTwo").css({height: "auto"}); } $("#exogenous-factors-config").css({"display": "none"}); $("#protein-config").css({"display": "none"}); $("#component-config").css({"display": "none"}); $("#arrow-config").css({"display": "block"});*/ /*if (this.TYPE == "Activator") { this.TYPE = "Inhibit"; this.setColor(new graphiti.util.Color("#43B967")); } else { this.TYPE = "Activator"; this.setColor(new graphiti.util.Color("#E14545")); }*/ }, /*onDoubleClick: function() { this.getCanvas().removeFigure(this); }*/ });
igemsoftware/SYSU-Software_2014
server/static/js/graphiti/Connection.js
JavaScript
lgpl-3.0
16,767
package idare.imagenode.internal.GUI.DataSetController; import idare.imagenode.ColorManagement.ColorScalePane; import idare.imagenode.Interfaces.DataSets.DataSet; import idare.imagenode.Interfaces.Layout.DataSetLayoutProperties; import idare.imagenode.internal.GUI.DataSetController.DataSetSelectionModel.ColorPaneBox; import idare.imagenode.internal.GUI.DataSetController.DataSetSelectionModel.ComboBoxRenderer; import javax.swing.JTable; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; /** * A DataSetSelectionTable, that is specific to the {@link DataSetSelectionModel}, using its unique renderers and editors. * @author Thomas Pfau * */ public class DataSetSelectionTable extends JTable { DataSetSelectionModel tablemodel; public DataSetSelectionTable(DataSetSelectionModel mod) { super(mod); tablemodel = mod; } /** * Move the selected entry (we assume single selection) down one row. * If the selected row is already the top row, nothing happens. */ public void moveEntryUp() { int row = getSelectedRow(); if(row > 0) { tablemodel.moveRowUp(row); } getSelectionModel().setSelectionInterval(row-1, row-1); } /** * Move the selected entry (we assume single selection) down one row. * If the selected row is already the last row, nothing happens. */ public void moveEntryDown() { int row = getSelectedRow(); if(row >= 0 & row < getRowCount()-1 ) { tablemodel.moveRowDown(row); } getSelectionModel().setSelectionInterval(row+1, row+1); } @Override public TableCellEditor getCellEditor(int row, int column) { Object value = super.getValueAt(row, column); if(value != null) { // we need very specific Editors for ColorScales and Dataset Properties. if(value instanceof DataSetLayoutProperties) { return tablemodel.getPropertiesEditor(row); } if(value instanceof ColorScalePane) { return tablemodel.getColorScaleEditor(row); } if(value instanceof DataSet) { return tablemodel.getDataSetEditor(row); } return getDefaultEditor(value.getClass()); } return super.getCellEditor(row, column); } @Override public TableCellRenderer getCellRenderer(int row, int column) { Object value = super.getValueAt(row, column); if(value != null) { // we need very specific renderers for ColorScales and Dataset Properties. if(value instanceof ComboBoxRenderer || value instanceof DataSetLayoutProperties) { TableCellRenderer current = tablemodel.getPropertiesRenderer(row); if(current != null) return current; else return super.getCellRenderer(row, column); } if(value instanceof ColorPaneBox|| value instanceof ColorScalePane) { TableCellRenderer current = tablemodel.getColorScaleRenderer(row); if(current != null) return current; else return super.getCellRenderer(row, column); } return getDefaultRenderer(value.getClass()); } return super.getCellRenderer(row, column); } }
sysbiolux/IDARE
METANODE-CREATOR/src/main/java/idare/imagenode/internal/GUI/DataSetController/DataSetSelectionTable.java
Java
lgpl-3.0
3,145
// mksysnum_linux.pl /usr/include/asm/unistd_64.h // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build amd64,linux package unix const ( SYS_READ = 0 SYS_WRITE = 1 SYS_OPEN = 2 SYS_CLOSE = 3 SYS_STAT = 4 SYS_FSTAT = 5 SYS_LSTAT = 6 SYS_POLL = 7 SYS_LSEEK = 8 SYS_MMAP = 9 SYS_MPROTECT = 10 SYS_MUNMAP = 11 SYS_BRK = 12 SYS_RT_SIGACTION = 13 SYS_RT_SIGPROCMASK = 14 SYS_RT_SIGRETURN = 15 SYS_IOCTL = 16 SYS_PREAD64 = 17 SYS_PWRITE64 = 18 SYS_READV = 19 SYS_WRITEV = 20 SYS_ACCESS = 21 SYS_PIPE = 22 SYS_SELECT = 23 SYS_SCHED_YIELD = 24 SYS_MREMAP = 25 SYS_MSYNC = 26 SYS_MINCORE = 27 SYS_MADVISE = 28 SYS_SHMGET = 29 SYS_SHMAT = 30 SYS_SHMCTL = 31 SYS_DUP = 32 SYS_DUP2 = 33 SYS_PAUSE = 34 SYS_NANOSLEEP = 35 SYS_GETITIMER = 36 SYS_ALARM = 37 SYS_SETITIMER = 38 SYS_GETPID = 39 SYS_SENDFILE = 40 SYS_SOCKET = 41 SYS_CONNECT = 42 SYS_ACCEPT = 43 SYS_SENDTO = 44 SYS_RECVFROM = 45 SYS_SENDMSG = 46 SYS_RECVMSG = 47 SYS_SHUTDOWN = 48 SYS_BIND = 49 SYS_LISTEN = 50 SYS_GETSOCKNAME = 51 SYS_GETPEERNAME = 52 SYS_SOCKETPAIR = 53 SYS_SETSOCKOPT = 54 SYS_GETSOCKOPT = 55 SYS_CLONE = 56 SYS_FORK = 57 SYS_VFORK = 58 SYS_EXECVE = 59 SYS_EXIT = 60 SYS_WAIT4 = 61 SYS_KILL = 62 SYS_UNAME = 63 SYS_SEMGET = 64 SYS_SEMOP = 65 SYS_SEMCTL = 66 SYS_SHMDT = 67 SYS_MSGGET = 68 SYS_MSGSND = 69 SYS_MSGRCV = 70 SYS_MSGCTL = 71 SYS_FCNTL = 72 SYS_FLOCK = 73 SYS_FSYNC = 74 SYS_FDATASYNC = 75 SYS_TRUNCATE = 76 SYS_FTRUNCATE = 77 SYS_GETDENTS = 78 SYS_GETCWD = 79 SYS_CHDIR = 80 SYS_FCHDIR = 81 SYS_RENAME = 82 SYS_MKDIR = 83 SYS_RMDIR = 84 SYS_CREAT = 85 SYS_LINK = 86 SYS_UNLINK = 87 SYS_SYMLINK = 88 SYS_READLINK = 89 SYS_CHMOD = 90 SYS_FCHMOD = 91 SYS_CHOWN = 92 SYS_FCHOWN = 93 SYS_LCHOWN = 94 SYS_UMASK = 95 SYS_GETTIMEOFDAY = 96 SYS_GETRLIMIT = 97 SYS_GETRUSAGE = 98 SYS_SYSINFO = 99 SYS_TIMES = 100 SYS_PTRACE = 101 SYS_GETUID = 102 SYS_SYSLOG = 103 SYS_GETGID = 104 SYS_SETUID = 105 SYS_SETGID = 106 SYS_GETEUID = 107 SYS_GETEGID = 108 SYS_SETPGID = 109 SYS_GETPPID = 110 SYS_GETPGRP = 111 SYS_SETSID = 112 SYS_SETREUID = 113 SYS_SETREGID = 114 SYS_GETGROUPS = 115 SYS_SETGROUPS = 116 SYS_SETRESUID = 117 SYS_GETRESUID = 118 SYS_SETRESGID = 119 SYS_GETRESGID = 120 SYS_GETPGID = 121 SYS_SETFSUID = 122 SYS_SETFSGID = 123 SYS_GETSID = 124 SYS_CAPGET = 125 SYS_CAPSET = 126 SYS_RT_SIGPENDING = 127 SYS_RT_SIGTIMEDWAIT = 128 SYS_RT_SIGQUEUEINFO = 129 SYS_RT_SIGSUSPEND = 130 SYS_SIGALTSTACK = 131 SYS_UTIME = 132 SYS_MKNOD = 133 SYS_USELIB = 134 SYS_PERSONALITY = 135 SYS_USTAT = 136 SYS_STATFS = 137 SYS_FSTATFS = 138 SYS_SYSFS = 139 SYS_GETPRIORITY = 140 SYS_SETPRIORITY = 141 SYS_SCHED_SETPARAM = 142 SYS_SCHED_GETPARAM = 143 SYS_SCHED_SETSCHEDULER = 144 SYS_SCHED_GETSCHEDULER = 145 SYS_SCHED_GET_PRIORITY_MAX = 146 SYS_SCHED_GET_PRIORITY_MIN = 147 SYS_SCHED_RR_GET_INTERVAL = 148 SYS_MLOCK = 149 SYS_MUNLOCK = 150 SYS_MLOCKALL = 151 SYS_MUNLOCKALL = 152 SYS_VHANGUP = 153 SYS_MODIFY_LDT = 154 SYS_PIVOT_ROOT = 155 SYS__SYSCTL = 156 SYS_PRCTL = 157 SYS_ARCH_PRCTL = 158 SYS_ADJTIMEX = 159 SYS_SETRLIMIT = 160 SYS_CHROOT = 161 SYS_SYNC = 162 SYS_ACCT = 163 SYS_SETTIMEOFDAY = 164 SYS_MOUNT = 165 SYS_UMOUNT2 = 166 SYS_SWAPON = 167 SYS_SWAPOFF = 168 SYS_REBOOT = 169 SYS_SENTRUSTOSTNAME = 170 SYS_SETDOMAINNAME = 171 SYS_IOPL = 172 SYS_IOPERM = 173 SYS_CREATE_MODULE = 174 SYS_INIT_MODULE = 175 SYS_DELETE_MODULE = 176 SYS_GET_KERNEL_SYMS = 177 SYS_QUERY_MODULE = 178 SYS_QUOTACTL = 179 SYS_NFSSERVCTL = 180 SYS_GETPMSG = 181 SYS_PUTPMSG = 182 SYS_AFS_SYSCALL = 183 SYS_TUXCALL = 184 SYS_SECURITY = 185 SYS_GETTID = 186 SYS_READAHEAD = 187 SYS_SETXATTR = 188 SYS_LSETXATTR = 189 SYS_FSETXATTR = 190 SYS_GETXATTR = 191 SYS_LGETXATTR = 192 SYS_FGETXATTR = 193 SYS_LISTXATTR = 194 SYS_LLISTXATTR = 195 SYS_FLISTXATTR = 196 SYS_REMOVEXATTR = 197 SYS_LREMOVEXATTR = 198 SYS_FREMOVEXATTR = 199 SYS_TKILL = 200 SYS_TIME = 201 SYS_FUTEX = 202 SYS_SCHED_SETAFFINITY = 203 SYS_SCHED_GETAFFINITY = 204 SYS_SET_THREAD_AREA = 205 SYS_IO_SETUP = 206 SYS_IO_DESTROY = 207 SYS_IO_GETEVENTS = 208 SYS_IO_SUBMIT = 209 SYS_IO_CANCEL = 210 SYS_GET_THREAD_AREA = 211 SYS_LOOKUP_DCOOKIE = 212 SYS_EPOLL_CREATE = 213 SYS_EPOLL_CTL_OLD = 214 SYS_EPOLL_WAIT_OLD = 215 SYS_REMAP_FILE_PAGES = 216 SYS_GETDENTS64 = 217 SYS_SET_TID_ADDRESS = 218 SYS_RESTART_SYSCALL = 219 SYS_SEMTIMEDOP = 220 SYS_FADVISE64 = 221 SYS_TIMER_CREATE = 222 SYS_TIMER_SETTIME = 223 SYS_TIMER_GETTIME = 224 SYS_TIMER_GETOVERRUN = 225 SYS_TIMER_DELETE = 226 SYS_CLOCK_SETTIME = 227 SYS_CLOCK_GETTIME = 228 SYS_CLOCK_GETRES = 229 SYS_CLOCK_NANOSLEEP = 230 SYS_EXIT_GROUP = 231 SYS_EPOLL_WAIT = 232 SYS_EPOLL_CTL = 233 SYS_TGKILL = 234 SYS_UTIMES = 235 SYS_VSERVER = 236 SYS_MBIND = 237 SYS_SET_MEMPOLICY = 238 SYS_GET_MEMPOLICY = 239 SYS_MQ_OPEN = 240 SYS_MQ_UNLINK = 241 SYS_MQ_TIMEDSEND = 242 SYS_MQ_TIMEDRECEIVE = 243 SYS_MQ_NOTIFY = 244 SYS_MQ_GETSETATTR = 245 SYS_KEXEC_LOAD = 246 SYS_WAITID = 247 SYS_ADD_KEY = 248 SYS_REQUEST_KEY = 249 SYS_KEYCTL = 250 SYS_IOPRIO_SET = 251 SYS_IOPRIO_GET = 252 SYS_INOTIFY_INIT = 253 SYS_INOTIFY_ADD_WATCH = 254 SYS_INOTIFY_RM_WATCH = 255 SYS_MIGRATE_PAGES = 256 SYS_OPENAT = 257 SYS_MKDIRAT = 258 SYS_MKNODAT = 259 SYS_FCHOWNAT = 260 SYS_FUTIMESAT = 261 SYS_NEWFSTATAT = 262 SYS_UNLINKAT = 263 SYS_RENAMEAT = 264 SYS_LINKAT = 265 SYS_SYMLINKAT = 266 SYS_READLINKAT = 267 SYS_FCHMODAT = 268 SYS_FACCESSAT = 269 SYS_PSELECT6 = 270 SYS_PPOLL = 271 SYS_UNSHARE = 272 SYS_SET_ROBUST_LIST = 273 SYS_GET_ROBUST_LIST = 274 SYS_SPLICE = 275 SYS_TEE = 276 SYS_SYNC_FILE_RANGE = 277 SYS_VMSPLICE = 278 SYS_MOVE_PAGES = 279 SYS_UTIMENSAT = 280 SYS_EPOLL_PWAIT = 281 SYS_SIGNALFD = 282 SYS_TIMERFD_CREATE = 283 SYS_EVENTFD = 284 SYS_FALLOCATE = 285 SYS_TIMERFD_SETTIME = 286 SYS_TIMERFD_GETTIME = 287 SYS_ACCEPT4 = 288 SYS_SIGNALFD4 = 289 SYS_EVENTFD2 = 290 SYS_EPOLL_CREATE1 = 291 SYS_DUP3 = 292 SYS_PIPE2 = 293 SYS_INOTIFY_INIT1 = 294 SYS_PREADV = 295 SYS_PWRITEV = 296 SYS_RT_TGSIGQUEUEINFO = 297 SYS_PERF_EVENT_OPEN = 298 SYS_RECVMMSG = 299 SYS_FANOTIFY_INIT = 300 SYS_FANOTIFY_MARK = 301 SYS_PRLIMIT64 = 302 SYS_NAME_TO_HANDLE_AT = 303 SYS_OPEN_BY_HANDLE_AT = 304 SYS_CLOCK_ADJTIME = 305 SYS_SYNCFS = 306 SYS_SENDMMSG = 307 SYS_SETNS = 308 SYS_GETCPU = 309 SYS_PROCESS_VM_READV = 310 SYS_PROCESS_VM_WRITEV = 311 )
trust-tech/go-trustmachine
vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go
GO
lgpl-3.0
10,655
/* Mesquite source code. Copyright 1997-2009 W. Maddison and D. Maddison. Version 2.7, August 2009. Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code. The commenting leaves much to be desired. Please approach this source code with the spirit of helping out. Perhaps with your help we can be more than a few, and make Mesquite better. Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. Mesquite's web site is http://mesquiteproject.org This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.lib; import java.util.*; import java.io.*; import org.dom4j.*; import org.dom4j.io.*; public class XMLUtil { /*.................................................................................................................*/ public static Element addFilledElement(Element containingElement, String name, String content) { if (content == null || name == null) return null; Element element = DocumentHelper.createElement(name); element.addText(content); containingElement.add(element); return element; } /*.................................................................................................................*/ public static Element addFilledElement(Element containingElement, String name, CDATA cdata) { if (cdata == null || name == null) return null; Element element = DocumentHelper.createElement(name); element.add(cdata); containingElement.add(element); return element; } public static String getTextFromElement(Element containingElement, String name){ Element e = containingElement.element(name); if (e == null) return null; else return e.getText(); } /*.................................................................................................................*/ public static String getDocumentAsXMLString(Document doc, boolean escapeText) { try { String encoding = doc.getXMLEncoding(); if (encoding == null) encoding = "UTF-8"; Writer osw = new StringWriter(); OutputFormat opf = new OutputFormat(" ", true, encoding); XMLWriter writer = new XMLWriter(osw, opf); writer.setEscapeText(escapeText); writer.write(doc); writer.close(); return osw.toString(); } catch (IOException e) { MesquiteMessage.warnProgrammer("XML Document could not be returned as string."); } return null; } /*.................................................................................................................*/ public static String getElementAsXMLString(Element doc, String encoding, boolean escapeText) { try { Writer osw = new StringWriter(); OutputFormat opf = new OutputFormat(" ", true, encoding); XMLWriter writer = new XMLWriter(osw, opf); writer.setEscapeText(escapeText); writer.write(doc); writer.close(); return osw.toString(); } catch (IOException e) { MesquiteMessage.warnProgrammer("XML Document could not be returned as string."); } return null; } /*.................................................................................................................*/ public static String getDocumentAsXMLString(Document doc) { return getDocumentAsXMLString(doc,true); } /*.................................................................................................................*/ public static String getDocumentAsXMLString2(Document doc) { try { String encoding = doc.getXMLEncoding(); //if (encoding == null) // encoding = "UTF-8"; Writer osw = new StringWriter(); OutputFormat opf = new OutputFormat(" ", true); XMLWriter writer = new XMLWriter(osw, opf); writer.write(doc); writer.close(); return osw.toString(); } catch (IOException e) { MesquiteMessage.warnProgrammer("XML Document could not be returned as string."); } return null; } /*.................................................................................................................*/ public static Document getDocumentFromString(String rootElementName, String contents) { Document doc = null; try { doc = DocumentHelper.parseText(contents); } catch (Exception e) { return null; } if (doc == null || doc.getRootElement() == null) { return null; } else if (!StringUtil.blank(rootElementName) && !doc.getRootElement().getName().equals(rootElementName)) { return null; } return doc; } /*.................................................................................................................*/ public static Document getDocumentFromString(String contents) { return getDocumentFromString("",contents); } /*.................................................................................................................*/ public static Element getRootXMLElementFromString(String rootElementName, String contents) { Document doc = getDocumentFromString(rootElementName, contents); if (doc==null) return null; return doc.getRootElement(); } /*.................................................................................................................*/ public static Element getRootXMLElementFromString(String contents) { return getRootXMLElementFromString("",contents); } /*.................................................................................................................*/ public static Element getRootXMLElementFromURL(String rootElementName, String url) { SAXReader saxReader = new SAXReader(); Document doc = null; try { doc = saxReader.read(url); } catch (Exception e) { return null; } if (doc == null || doc.getRootElement() == null) { return null; } else if (!StringUtil.blank(rootElementName) && !doc.getRootElement().getName().equals(rootElementName)) { return null; } Element root = doc.getRootElement(); return root; } /*.................................................................................................................*/ public static Element getRootXMLElementFromURL(String url) { return getRootXMLElementFromURL("",url); } /*.................................................................................................................*/ public static void readXMLPreferences(MesquiteModule module, XMLPreferencesProcessor xmlPrefProcessor, String contents) { Element root = getRootXMLElementFromString("mesquite",contents); if (root==null) return; Element element = root.element(module.getXMLModuleName()); if (element != null) { Element versionElement = element.element("version"); if (versionElement == null) return ; else { int version = MesquiteInteger.fromString(element.elementText("version")); boolean acceptableVersion = (module.getXMLPrefsVersion()==version || !module.xmlPrefsVersionMustMatch()); if (acceptableVersion) processPreferencesFromXML(xmlPrefProcessor, element); else return; } } } /*.................................................................................................................*/ public static void processPreferencesFromXML ( XMLPreferencesProcessor xmlPrefProcessor, Element element) { List prefElement = element.elements(); for (Iterator iter = prefElement.iterator(); iter.hasNext();) { // this is going through all of the notices Element messageElement = (Element) iter.next(); xmlPrefProcessor.processSingleXMLPreference(messageElement.getName(), messageElement.getText()); } } }
MesquiteProject/MesquiteArchive
releases/Mesquite2.7/Mesquite Project/Source/mesquite/lib/XMLUtil.java
Java
lgpl-3.0
7,607
/* * XAdES4j - A Java library for generation and verification of XAdES signatures. * Copyright (C) 2010 Luis Goncalves. * * XAdES4j 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 any later version. * * XAdES4j 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 XAdES4j. If not, see <http://www.gnu.org/licenses/>. */ package xades4j.xml.marshalling; import java.util.EnumMap; import java.util.List; import xades4j.properties.IdentifierType; import xades4j.properties.ObjectIdentifier; import xades4j.properties.data.BaseCertRefsData; import xades4j.properties.data.CertRef; import xades4j.xml.bind.xades.XmlCertIDListType; import xades4j.xml.bind.xades.XmlCertIDType; import xades4j.xml.bind.xades.XmlDigestAlgAndValueType; import xades4j.xml.bind.xades.XmlIdentifierType; import xades4j.xml.bind.xades.XmlObjectIdentifierType; import xades4j.xml.bind.xades.XmlQualifierType; import xades4j.xml.bind.xmldsig.XmlDigestMethodType; import xades4j.xml.bind.xmldsig.XmlX509IssuerSerialType; /** * @author Luís */ class ToXmlUtils { ToXmlUtils() { } private static final EnumMap<IdentifierType, XmlQualifierType> identifierTypeConv; static { identifierTypeConv = new EnumMap(IdentifierType.class); identifierTypeConv.put(IdentifierType.OIDAsURI, XmlQualifierType.OID_AS_URI); identifierTypeConv.put(IdentifierType.OIDAsURN, XmlQualifierType.OID_AS_URN); } static XmlObjectIdentifierType getXmlObjectId(ObjectIdentifier objId) { XmlObjectIdentifierType xmlObjId = new XmlObjectIdentifierType(); // Object identifier XmlIdentifierType xmlId = new XmlIdentifierType(); xmlId.setValue(objId.getIdentifier()); // If it is IdentifierType.URI the converter returns null, which is the // same as not specifying a qualifier. xmlId.setQualifier(identifierTypeConv.get(objId.getIdentifierType())); xmlObjId.setIdentifier(xmlId); return xmlObjId; } /**/ static XmlCertIDListType getXmlCertRefList(BaseCertRefsData certRefsData) { XmlCertIDListType xmlCertRefListProp = new XmlCertIDListType(); List<XmlCertIDType> xmlCertRefList = xmlCertRefListProp.getCert(); XmlDigestAlgAndValueType certDigest; XmlDigestMethodType certDigestMethod; XmlX509IssuerSerialType issuerSerial; XmlCertIDType certID; for (CertRef certRef : certRefsData.getCertRefs()) { certDigestMethod = new XmlDigestMethodType(); certDigestMethod.setAlgorithm(certRef.digestAlgUri); certDigest = new XmlDigestAlgAndValueType(); certDigest.setDigestMethod(certDigestMethod); certDigest.setDigestValue(certRef.digestValue); issuerSerial = new XmlX509IssuerSerialType(); issuerSerial.setX509IssuerName(certRef.issuerDN); issuerSerial.setX509SerialNumber(certRef.serialNumber); certID = new XmlCertIDType(); certID.setCertDigest(certDigest); certID.setIssuerSerial(issuerSerial); xmlCertRefList.add(certID); } return xmlCertRefListProp; } }
entaksi/xades4j
src/main/java/xades4j/xml/marshalling/ToXmlUtils.java
Java
lgpl-3.0
3,617
/* * This file is part of RskJ * Copyright (C) 2017 RSK Labs Ltd. * * This program 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. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.rsk.core; import com.google.common.primitives.UnsignedBytes; import org.ethereum.rpc.TypeConverter; import org.ethereum.util.ByteUtil; import org.ethereum.vm.DataWord; import java.util.Arrays; import java.util.Comparator; /** * Immutable representation of an RSK address. * It is a simple wrapper on the raw byte[]. * * @author Ariel Mendelzon */ public class RskAddress { /** * This is the size of an RSK address in bytes. */ public static final int LENGTH_IN_BYTES = 20; private static final RskAddress NULL_ADDRESS = new RskAddress(); /** * This compares using the lexicographical order of the sender unsigned bytes. */ public static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR = Comparator.comparing( RskAddress::getBytes, UnsignedBytes.lexicographicalComparator()); private final byte[] bytes; /** * @param address a data word containing an address in the last 20 bytes. */ public RskAddress(DataWord address) { this(address.getLast20Bytes()); } /** * @param address the hex-encoded 20 bytes long address, with or without 0x prefix. */ public RskAddress(String address) { this(TypeConverter.stringHexToByteArray(address)); } /** * @param bytes the 20 bytes long raw address bytes. */ public RskAddress(byte[] bytes) { if (bytes.length != LENGTH_IN_BYTES) { throw new RuntimeException(String.format("An RSK address must be %d bytes long", LENGTH_IN_BYTES)); } this.bytes = bytes; } /** * This instantiates the contract creation address. */ private RskAddress() { this.bytes = new byte[0]; } /** * @return the null address, which is the receiver of contract creation transactions. */ public static RskAddress nullAddress() { return NULL_ADDRESS; } public byte[] getBytes() { return bytes; } public String toHexString() { return ByteUtil.toHexString(bytes); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } RskAddress otherSender = (RskAddress) other; return Arrays.equals(bytes, otherSender.bytes); } @Override public int hashCode() { return Arrays.hashCode(bytes); } /** * @return a DEBUG representation of the address, mainly used for logging. */ @Override public String toString() { return toHexString(); } public String toJsonString() { if (NULL_ADDRESS.equals(this)) { return null; } return TypeConverter.toUnformattedJsonHex(this.getBytes()); } }
rsksmart/rskj
rskj-core/src/main/java/co/rsk/core/RskAddress.java
Java
lgpl-3.0
3,619
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws 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. QtAws 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 QtAws. If not, see <http://www.gnu.org/licenses/>. */ #include "deleterepositoryresponse.h" #include "deleterepositoryresponse_p.h" #include <QDebug> #include <QNetworkReply> #include <QXmlStreamReader> namespace QtAws { namespace ECRPublic { /*! * \class QtAws::ECRPublic::DeleteRepositoryResponse * \brief The DeleteRepositoryResponse class provides an interace for ECRPublic DeleteRepository responses. * * \inmodule QtAwsECRPublic * * <fullname>Amazon Elastic Container Registry Public</fullname> * * Amazon Elastic Container Registry (Amazon ECR) is a managed container image registry service. Amazon ECR provides both * public and private registries to host your container images. You can use the familiar Docker CLI, or their preferred * client, to push, pull, and manage images. Amazon ECR provides a secure, scalable, and reliable registry for your Docker * or Open Container Initiative (OCI) images. Amazon ECR supports public repositories with this API. For information about * the Amazon ECR API for private repositories, see <a * href="https://docs.aws.amazon.com/AmazonECR/latest/APIReference/Welcome.html">Amazon Elastic Container Registry API * * \sa ECRPublicClient::deleteRepository */ /*! * Constructs a DeleteRepositoryResponse object for \a reply to \a request, with parent \a parent. */ DeleteRepositoryResponse::DeleteRepositoryResponse( const DeleteRepositoryRequest &request, QNetworkReply * const reply, QObject * const parent) : ECRPublicResponse(new DeleteRepositoryResponsePrivate(this), parent) { setRequest(new DeleteRepositoryRequest(request)); setReply(reply); } /*! * \reimp */ const DeleteRepositoryRequest * DeleteRepositoryResponse::request() const { Q_D(const DeleteRepositoryResponse); return static_cast<const DeleteRepositoryRequest *>(d->request); } /*! * \reimp * Parses a successful ECRPublic DeleteRepository \a response. */ void DeleteRepositoryResponse::parseSuccess(QIODevice &response) { //Q_D(DeleteRepositoryResponse); QXmlStreamReader xml(&response); /// @todo } /*! * \class QtAws::ECRPublic::DeleteRepositoryResponsePrivate * \brief The DeleteRepositoryResponsePrivate class provides private implementation for DeleteRepositoryResponse. * \internal * * \inmodule QtAwsECRPublic */ /*! * Constructs a DeleteRepositoryResponsePrivate object with public implementation \a q. */ DeleteRepositoryResponsePrivate::DeleteRepositoryResponsePrivate( DeleteRepositoryResponse * const q) : ECRPublicResponsePrivate(q) { } /*! * Parses a ECRPublic DeleteRepository response element from \a xml. */ void DeleteRepositoryResponsePrivate::parseDeleteRepositoryResponse(QXmlStreamReader &xml) { Q_ASSERT(xml.name() == QLatin1String("DeleteRepositoryResponse")); Q_UNUSED(xml) ///< @todo } } // namespace ECRPublic } // namespace QtAws
pcolby/libqtaws
src/ecrpublic/deleterepositoryresponse.cpp
C++
lgpl-3.0
3,571
#pragma once #include <type_traits> #include <limits> #include <utility> namespace sio { template<typename T> struct is_bit_enum: public std::false_type {}; template<typename Enum, std::enable_if_t<std::is_enum<Enum>{}, int> = 0> class bitfield { public: using integer = std::underlying_type_t<Enum>; private: integer bits; public: constexpr bitfield() noexcept: bits(0) {} constexpr bitfield(Enum bit) noexcept: bits(static_cast<integer>(bit)) {} explicit constexpr bitfield(integer value) noexcept: bits(value) {} bitfield &operator|=(bitfield rhs) noexcept { bits |= rhs.bits; return *this; } bitfield &operator&=(bitfield rhs) noexcept { bits &= rhs.bits; return *this; } bitfield &operator^=(bitfield rhs) noexcept { bits ^= rhs.bits; return *this; } constexpr bitfield operator|(bitfield rhs) const noexcept { return bitfield { bits | rhs.bits }; } constexpr bitfield operator&(bitfield rhs) const noexcept { return bitfield { bits & rhs.bits }; } constexpr bitfield operator^(bitfield rhs) const noexcept { return bitfield { bits ^ rhs.bits }; } constexpr bitfield operator~() const noexcept { return bitfield { ~bits }; } constexpr operator bool() const noexcept { return !!bits; } constexpr bool operator==(bitfield rhs) const noexcept { return bits == rhs.bits; } constexpr bool operator!=(bitfield rhs) const noexcept { return bits != rhs.bits; } }; template<typename Writer, typename Enum> void write(Writer &&w, bitfield<Enum> field) { bool first = true; for (int i = std::numeric_limits<typename bitfield<Enum>::integer>::digits-1; i >= 0; --i) { Enum bit = static_cast<Enum>(1 << i); if (field & bit) { if (!first) { write(std::forward<Writer>(w), " | "); } else { first = false; } write(std::forward<Writer>(w), bit); } } } } // namespace sio template<typename Enum, std::enable_if_t<sio::is_bit_enum<Enum>{}, int> = 0> sio::bitfield<Enum> operator|(Enum lhs, sio::bitfield<decltype(lhs)> rhs) { return rhs | lhs; } template<typename Enum, std::enable_if_t<sio::is_bit_enum<Enum>{}, int> = 0> sio::bitfield<Enum> operator&(Enum lhs, sio::bitfield<decltype(lhs)> rhs) { return rhs & lhs; } template<typename Enum, std::enable_if_t<sio::is_bit_enum<Enum>{}, int> = 0> sio::bitfield<Enum> operator^(Enum lhs, sio::bitfield<decltype(lhs)> rhs) { return rhs ^ lhs; } template<typename Enum, std::enable_if_t<sio::is_bit_enum<Enum>{}, int> = 0> sio::bitfield<Enum> operator~(Enum lhs) { return ~sio::bitfield<Enum>(lhs); }
fknorr/sio
include/sio/bitfield.hh
C++
lgpl-3.0
2,838
#include <bits/stdc++.h> using namespace std; #define DEBUG // comment this line to pull out print statements #ifdef DEBUG // completely copied from http://saadahmad.ca/cc-preprocessor-metaprogramming-2/ const char NEWLINE[] = "\n"; const char TAB[] = "\t"; #define EMPTY() #define DEFER(...) __VA_ARGS__ EMPTY() #define DEFER2(...) __VA_ARGS__ DEFER(EMPTY) () #define DEFER3(...) __VA_ARGS__ DEFER2(EMPTY) () #define EVAL_1(...) __VA_ARGS__ #define EVAL_2(...) EVAL_1(EVAL_1(__VA_ARGS__)) #define EVAL_3(...) EVAL_2(EVAL_2(__VA_ARGS__)) #define EVAL_4(...) EVAL_3(EVAL_3(__VA_ARGS__)) #define EVAL_5(...) EVAL_4(EVAL_4(__VA_ARGS__)) #define EVAL_6(...) EVAL_5(EVAL_5(__VA_ARGS__)) #define EVAL_7(...) EVAL_6(EVAL_6(__VA_ARGS__)) #define EVAL_8(...) EVAL_7(EVAL_7(__VA_ARGS__)) #define EVAL(...) EVAL_8(__VA_ARGS__) #define NOT_0 EXISTS(1) #define NOT(x) TRY_EXTRACT_EXISTS ( CAT(NOT_, x), 0 ) #define IS_ENCLOSED(x, ...) TRY_EXTRACT_EXISTS ( IS_ENCLOSED_TEST x, 0 ) #define ENCLOSE_EXPAND(...) EXPANDED, ENCLOSED, (__VA_ARGS__) ) EAT ( #define GET_CAT_EXP(a, b) (a, ENCLOSE_EXPAND b, DEFAULT, b ) #define CAT_WITH_ENCLOSED(a, b) a b #define CAT_WITH_DEFAULT(a, b) a ## b #define CAT_WITH(a, _, f, b) CAT_WITH_ ## f (a, b) #define EVAL_CAT_WITH(...) CAT_WITH __VA_ARGS__ #define CAT(a, b) EVAL_CAT_WITH ( GET_CAT_EXP(a, b) ) #define IF_1(true, ...) true #define IF_0(true, ...) __VA_ARGS__ #define IF(value) CAT(IF_, value) #define HEAD(x, ...) x #define TAIL(x, ...) __VA_ARGS__ #define TEST_LAST EXISTS(1) #define IS_LIST_EMPTY(...) TRY_EXTRACT_EXISTS( DEFER(HEAD) (__VA_ARGS__ EXISTS(1)) , 0) #define IS_LIST_NOT_EMPTY(...) NOT(IS_LIST_EMPTY(__VA_ARGS__)) #define DOES_VALUE_EXIST_EXISTS(...) 1 #define DOES_VALUE_EXIST_DOESNT_EXIST 0 #define DOES_VALUE_EXIST(x) CAT(DOES_VALUE_EXIST_, x) #define TRY_EXTRACT_EXISTS(value, ...) IF ( DOES_VALUE_EXIST(TEST_EXISTS(value)) ) \ ( EXTRACT_VALUE(value), __VA_ARGS__ ) #define EXTRACT_VALUE_EXISTS(...) __VA_ARGS__ #define EXTRACT_VALUE(value) CAT(EXTRACT_VALUE_, value) #define EAT(...) #define EXPAND_TEST_EXISTS(...) EXPANDED, EXISTS(__VA_ARGS__) ) EAT ( #define GET_TEST_EXISTS_RESULT(x) ( CAT(EXPAND_TEST_, x), DOESNT_EXIST ) #define GET_TEST_EXIST_VALUE_(expansion, existValue) existValue #define GET_TEST_EXIST_VALUE(x) GET_TEST_EXIST_VALUE_ x #define TEST_EXISTS(x) GET_TEST_EXIST_VALUE ( GET_TEST_EXISTS_RESULT(x) ) #define ENCLOSE(...) ( __VA_ARGS__ ) #define REM_ENCLOSE_(...) __VA_ARGS__ #define REM_ENCLOSE(...) REM_ENCLOSE_ __VA_ARGS__ #define IF_ENCLOSED_1(true, ...) true #define IF_ENCLOSED_0(true, ...) __VA_ARGS__ #define IF_ENCLOSED(...) CAT(IF_ENCLOSED_, IS_ENCLOSED(__VA_ARGS__)) #define OPT_REM_ENCLOSE(...) \ IF_ENCLOSED (__VA_ARGS__) ( REM_ENCLOSE(__VA_ARGS__), __VA_ARGS__ ) #define FOR_EACH_INDIRECT() FOR_EACH_NO_EVAL #define FOR_EACH_NO_EVAL(fVisitor, ...) \ IF ( IS_LIST_NOT_EMPTY( __VA_ARGS__ ) ) \ ( \ fVisitor( OPT_REM_ENCLOSE(HEAD(__VA_ARGS__)) ) \ DEFER2 ( FOR_EACH_INDIRECT )() (fVisitor, TAIL(__VA_ARGS__)) \ ) #define FOR_EACH(fVisitor, ...) \ EVAL(FOR_EACH_NO_EVAL(fVisitor, __VA_ARGS__)) #define STRINGIFY(x) #x #define DUMP_VAR(x) std::cout << STRINGIFY(x) << ": " << x << TAB; #define debug(...) FOR_EACH(DUMP_VAR, __VA_ARGS__); std::cout << NEWLINE; #define dbg(block) block #else #define debug(...) #define dbg(block) #endif const double EPS = 1E-9; // --- GEOMETRY --- // --- points, lines, functions for lines and points, triangles, // --- circles. // -- insert geometry.hh here for geometric functions // --- END GEOMETRY --- typedef vector<int> vi; typedef vector<pair<int,int>> vii; #define UN(v) SORT(v),v.erase(unique(v.begin(),v.end()),v.end()) #define SORT(c) sort((c).begin(),(c).end()) #define FOR(i,a,b) for (int i=(a); i < (b); i++) #define REP(i,n) FOR(i,0,(int)n) #define CL(a,b) memset(a,b,sizeof(a)) #define CL2d(a,b,x,y) memset(a, b, sizeof(a[0][0])*x*y) /* global variables */ int W, N; int l, w; int i, j, k; char Ws[20], Ns[20]; int total_area; char line[100]; //char answers[10000][21]; char answers[100000]; int ans, ansb; int tlen, clen; /* global variables */ void dump() { // dump data } bool getInput() { if (feof(stdin)) return false; return true; } void process() { // int a = 2, b = 5, c = 3; // debug(a, b, c); // debugging example // printf("%d\n", total_area/W); } int main() { ios_base::sync_with_stdio(false); char digits[10]; fgets_unlocked(line, 99, stdin); do { for (i = 0; line[i] != '\n'; ++i) { Ws[i] = line[i]; } Ws[i] = 0; for (k = 0; k < i-1; ++k) { W += Ws[k]-'0'; W *= 10; } W += Ws[k]-'0'; fgets_unlocked(line, 99, stdin); for (j = 0; line[j] != '\n'; ++j) { Ns[j] = line[j]; } for (k = 0; k < j-1; ++k) { N += Ns[k]-'0'; N *= 10; } N += Ns[k]-'0'; REP(counter, N) { l = w = 0; fgets_unlocked(line, 99, stdin); for (i = 0; line[i] != ' '; ++i) { Ws[i] = line[i]; } Ws[i+1] = 0; for (k = 0; k < i-1; ++k) { l += Ws[k]-'0'; l *= 10; } l += Ws[k]-'0'; while (line[i] == ' ') { ++i; } for (j = 0; line[i] != '\n' && line[i] != 0; ++i, ++j) { Ns[j] = line[i]; } Ns[j+1] = 0; for (k = 0; k < j-1; ++k) { w += Ns[k]-'0'; w *= 10; } w += Ns[k]-'0'; total_area += l*w; } ans = total_area/W, ansb = ans; digits[9] = '\n'; clen = 9; while (ans != 0) { digits[--clen] = (ans%10)+'0'; ans /= 10; } memcpy(&answers[tlen], &digits[clen], 10-clen); tlen += 10-clen; /* CLEAR GLOBAL VARIABLES! */ total_area = 0; W = 0; N = 0; l = 0; w = 0; /* CLEAR GLOBAL VARIABLES! */ fgets_unlocked(line, 99, stdin); } while (!feof_unlocked(stdin)); fwrite_unlocked(&answers, sizeof(char), tlen, stdout); return 0; }
mgavin/acm-code
uva/code/13287_cake.cc
C++
lgpl-3.0
5,774
# -*- coding: utf-8 -*- """ This module put my utility functions """ __author__ = "Jiang Yu-Kuan <yukuan.jiang@gmail.com>" __date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)" import re import os import sys #------------------------------------------------------------------------------ # File #------------------------------------------------------------------------------ def save_utf8_file(fn, lines): """Save string lines into an UTF8 text files. """ with open(fn, "w") as out_file: out_file.write("\n".join(lines).encode("utf-8")) def main_basename(path): r"""Return a main name of a basename of a given file path. Example ------- >>> main_basename('c:\code\langconv\MsgID.h') 'MsgID.h' """ base = os.path.basename(path) base_main, _base_ext = os.path.splitext(base) return base_main #------------------------------------------------------------------------------ # Math #------------------------------------------------------------------------------ def is_numeric(str): try: _offset = int(eval(str)) except: return False return True #------------------------------------------------------------------------------ # String #------------------------------------------------------------------------------ def replace_chars(text, replaced_pairs='', deleted_chars=''): """Return a char replaced text. Arguments --------- text -- the text replaced_pairs -- the replaced chars Example ------- >>> replaced = [('a','b'), ('c','d')] >>> removed = 'e' >>> replace_chars('abcde', replaced, removed) 'bbdd' """ for old, new in replaced_pairs: text = text.replace(old, new) for ch in deleted_chars: text = text.replace(ch, '') return text def camel_case(string): """Return camel case string from a space-separated string. Example ------- >>> camel_case('good job') 'GoodJob' """ return ''.join(w.capitalize() for w in string.split()) def replace_punctuations(text): """Replace punctuation characters with abbreviations for a string. """ punctuations = [ ('?', 'Q'), # Q: question mark ('.', 'P'), # P: period; full stop ('!', 'E'), # E: exclamation mark ("'", 'SQ'), # SQ: single quotation mark; single quote ('"', 'DQ'), # DQ: double quotation mark; double quotes ('(', 'LP'), # LP: left parenthese (')', 'RP'), # RP: right parenthese (':', 'Cn'), # Cn: colon (',', 'Ca'), # Ca: comma (';', 'S'), # S: semicolon ] deleted = '+-*/^=%$#@|\\<>{}[]' return replace_chars(text, punctuations, deleted) def remain_alnum(text): """Remain digits and English letters of a string. """ return ''.join(c for c in text if c.isalnum() and ord(' ') <= ord(c) <= ord('z')) #------------------------------------------------------------------------------ # For code generation #------------------------------------------------------------------------------ def c_identifier(text): """Convert input text into an legal identifier in C. Example ------- >>> c_identifier("Hello World") 'HelloWorld' >>> c_identifier("Anti-Shake") 'Antishake' """ if ' ' in text: text = camel_case(text) text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text) text = re.sub(r'\-\d+', lambda x: x.group().replace('-', 'N'), text) text = replace_punctuations(text) return remain_alnum(text) def wrap_header_guard(lines, h_fn): """Wrap a C header guard for a given line list. """ def underscore(txt): """Return an under_scores text from a CamelCase text. This function will leave a CamelCase text unchanged. """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() h_fn_sig = '%s_H_' % underscore(main_basename(h_fn)).upper() begin = ['#ifndef %s' % h_fn_sig] begin += ['#define %s' % h_fn_sig, '', ''] end = ['', '', '#endif // %s' % h_fn_sig, ''] return begin + lines + end def prefix_info(lines, software, version, author, comment_mark='//'): """Prefix information to the given lines with given comment-mark. """ prefix = ['%s Generated by the %s v%s' % (comment_mark, software, version)] prefix += ['%s !author: %s' % (comment_mark, author)] prefix += ['%s !trail: %s %s' % (comment_mark, os.path.basename(sys.argv[0]), ' '.join(sys.argv[1:]))] return prefix + lines
YorkJong/pyResourceLink
reslnk/myutil.py
Python
lgpl-3.0
4,850
/** \file millionaire_prob.cpp \author sreeram.sadasivam@cased.de \copyright ABY - A Framework for Efficient Mixed-protocol Secure Two-party Computation Copyright (C) 2019 Engineering Cryptographic Protocols Group, TU Darmstadt This program 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. ABY is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. \brief Implementation of the millionaire problem using ABY Framework. */ #include "millionaire_prob.h" #include "../../../abycore/circuit/booleancircuits.h" #include "../../../abycore/sharing/sharing.h" int32_t test_millionaire_prob_circuit(e_role role, const std::string& address, uint16_t port, seclvl seclvl, uint32_t bitlen, uint32_t nthreads, e_mt_gen_alg mt_alg, e_sharing sharing) { /** Step 1: Create the ABYParty object which defines the basis of all the operations which are happening. Operations performed are on the basis of the role played by this object. */ ABYParty* party = new ABYParty(role, address, port, seclvl, bitlen, nthreads, mt_alg); /** Step 2: Get to know all the sharing types available in the program. */ std::vector<Sharing*>& sharings = party->GetSharings(); /** Step 3: Create the circuit object on the basis of the sharing type being inputed. */ Circuit* circ = sharings[sharing]->GetCircuitBuildRoutine(); /** Step 4: Creating the share objects - s_alice_money, s_bob_money which is used as input to the computation function. Also s_out which stores the output. */ share *s_alice_money, *s_bob_money, *s_out; /** Step 5: Initialize Alice's and Bob's money with random values. Both parties use the same seed, to be able to verify the result. In a real example each party would only supply one input value. */ uint32_t alice_money, bob_money, output; srand(time(NULL)); alice_money = rand(); bob_money = rand(); /** Step 6: Copy the randomly generated money into the respective share objects using the circuit object method PutINGate() for my inputs and PutDummyINGate() for the other parties input. Also mention who is sharing the object. */ //s_alice_money = circ->PutINGate(alice_money, bitlen, CLIENT); //s_bob_money = circ->PutINGate(bob_money, bitlen, SERVER); if(role == SERVER) { s_alice_money = circ->PutDummyINGate(bitlen); s_bob_money = circ->PutINGate(bob_money, bitlen, SERVER); } else { //role == CLIENT s_alice_money = circ->PutINGate(alice_money, bitlen, CLIENT); s_bob_money = circ->PutDummyINGate(bitlen); } /** Step 7: Call the build method for building the circuit for the problem by passing the shared objects and circuit object. Don't forget to type cast the circuit object to type of share */ s_out = BuildMillionaireProbCircuit(s_alice_money, s_bob_money, (BooleanCircuit*) circ); /** Step 8: Modify the output receiver based on the role played by the server and the client. This step writes the output to the shared output object based on the role. */ s_out = circ->PutOUTGate(s_out, ALL); /** Step 9: Executing the circuit using the ABYParty object evaluate the problem. */ party->ExecCircuit(); /** Step 10:Type casting the value to 32 bit unsigned integer for output. */ output = s_out->get_clear_value<uint32_t>(); std::cout << "Testing Millionaire's Problem in " << get_sharing_name(sharing) << " sharing: " << std::endl; std::cout << "\nAlice Money:\t" << alice_money; std::cout << "\nBob Money:\t" << bob_money; std::cout << "\nCircuit Result:\t" << (output ? ALICE : BOB); std::cout << "\nVerify Result: \t" << ((alice_money > bob_money) ? ALICE : BOB) << "\n"; delete party; return 0; } share* BuildMillionaireProbCircuit(share *s_alice, share *s_bob, BooleanCircuit *bc) { share* out; /** Calling the greater than equal function in the Boolean circuit class.*/ out = bc->PutGTGate(s_alice, s_bob); return out; }
encryptogroup/ABY
src/examples/millionaire_prob/common/millionaire_prob.cpp
C++
lgpl-3.0
4,536
<?php /* dvdetect DVD detection, analysis & DVDETECT lookup library Copyright (C) 2013-2015 Norbert Schlia <nschlia@dvdetect.de> This program 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. 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 LESSER GENERAL PUBLIC LICENSE for more details. You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*! \file functions.search.inc.php * * \brief PHP function collection */ function addVideoStream($mysqli, $tagDVDVIDEOSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDVIDEOSTREAM->attributes(); $Type = value_or_null($attributes["Type"]); $ID = value_or_null($attributes["ID"]); $VideoCodingMode = value_or_null($attributes["VideoCodingMode"]); $VideoStandard = value_or_null($attributes["VideoStandard"]); $VideoAspect = value_or_null($attributes["VideoAspect"]); $AutomaticPanScanDisallowed = value_or_null($attributes["AutomaticPanScanDisallowed"]); $CCForLine21Field1InGOP = value_or_null($attributes["CCForLine21Field1InGOP"]); $CCForLine21Field2InGOP = value_or_null($attributes["CCForLine21Field2InGOP"]); $CBR = value_or_null($attributes["CBR"]); $Resolution = value_or_null($attributes["Resolution"]); $LetterBoxed = value_or_null($attributes["LetterBoxed"]); $SourceFilm = value_or_null($attributes["SourceFilm"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "INSERT INTO DVDVIDEOSTREAM (DVDVMGMKey, DVDVTSKey, Type, ID, VideoCodingMode, VideoStandard, VideoAspect, AutomaticPanScanDisallowed, CCForLine21Field1InGOP, CCForLine21Field2InGOP, CBR, Resolution, LetterBoxed, SourceFilm) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iisisssiiiisii", $idDVDVMGM, $idDVDVTS, $Type, $ID, $VideoCodingMode, $VideoStandard, $VideoAspect, $AutomaticPanScanDisallowed, $CCForLine21Field1InGOP, $CCForLine21Field2InGOP, $CBR, $Resolution, $LetterBoxed, $SourceFilm)) { $ResponseText = "Error binding parameters for DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function updateVideoStream($mysqli, $tagDVDVIDEOSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDVIDEOSTREAM->attributes(); $Type = value_or_null($attributes["Type"]); $ID = value_or_null($attributes["ID"]); $VideoCodingMode = value_or_null($attributes["VideoCodingMode"]); $VideoStandard = value_or_null($attributes["VideoStandard"]); $VideoAspect = value_or_null($attributes["VideoAspect"]); $AutomaticPanScanDisallowed = value_or_null($attributes["AutomaticPanScanDisallowed"]); $CCForLine21Field1InGOP = value_or_null($attributes["CCForLine21Field1InGOP"]); $CCForLine21Field2InGOP = value_or_null($attributes["CCForLine21Field2InGOP"]); $CBR = value_or_null($attributes["CBR"]); $Resolution = value_or_null($attributes["Resolution"]); $LetterBoxed = value_or_null($attributes["LetterBoxed"]); $SourceFilm = value_or_null($attributes["SourceFilm"]); if ($idDVDVMGM == null) { $Type = "VMG"; } $strSQL = "UPDATE DVDVIDEOSTREAM SET ID = ?, VideoCodingMode = ?, VideoStandard = ?, VideoAspect = ?, AutomaticPanScanDisallowed = ?, CCForLine21Field1InGOP = ?, CCForLine21Field2InGOP = ?, CBR = ?, Resolution = ?, LetterBoxed = ?, SourceFilm = ? "; if ($idDVDVMGM != null) { $strSQL .= "WHERE DVDVMGMKey = ? AND DVDVTSKey IS NULL AND Type = ?;"; } else { $strSQL .= "WHERE DVDVMGMKey IS NULL AND DVDVTSKey = ? AND Type = ?;"; } $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if ($idDVDVMGM != null) { if (!$stmt->bind_param("isssiiiisiiis", $ID, $VideoCodingMode, $VideoStandard, $VideoAspect, $AutomaticPanScanDisallowed, $CCForLine21Field1InGOP, $CCForLine21Field2InGOP, $CBR, $Resolution, $LetterBoxed, $SourceFilm, $idDVDVMGM, $Type)) { $ResponseText = "Error binding parameters for DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } else { if (!$stmt->bind_param("isssiiiisiiis", $ID, $VideoCodingMode, $VideoStandard, $VideoAspect, $AutomaticPanScanDisallowed, $CCForLine21Field1InGOP, $CCForLine21Field2InGOP, $CBR, $Resolution, $LetterBoxed, $SourceFilm, $idDVDVTS, $Type)) { $ResponseText = "Error binding parameters for DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVIDEOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function addAudioStream($mysqli, $tagDVDAUDIOSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDAUDIOSTREAM->attributes(); $Number = value_or_null($attributes["Number"]); $Type = value_or_null($attributes["Type"]); $ID = value_or_null($attributes["ID"]); $Channels = value_or_null($attributes["Channels"]); $SampleRate = value_or_null($attributes["SampleRate"]); $Quantisation = value_or_null($attributes["Quantisation"]); $MultichannelExtPresent = value_or_null($attributes["MultichannelExtPresent"]); $CodingMode = value_or_null($attributes["CodingMode"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "INSERT INTO DVDAUDIOSTREAM (DVDVMGMKey, DVDVTSKey, Number, Type, ID, SampleRate, Channels, Quantisation, CodingMode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiisiiiss", $idDVDVMGM, $idDVDVTS, $Number, $Type, $ID, $SampleRate, $Channels, $Quantisation, $CodingMode)) { $ResponseText = "Error binding parameters for DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function updateAudioStream($mysqli, $tagDVDAUDIOSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDAUDIOSTREAM->attributes(); $Number = value_or_null($attributes["Number"]); $Type = value_or_null($attributes["Type"]); $ID = value_or_null($attributes["ID"]); $Channels = value_or_null($attributes["Channels"]); $SampleRate = value_or_null($attributes["SampleRate"]); $Quantisation = value_or_null($attributes["Quantisation"]); $MultichannelExtPresent = value_or_null($attributes["MultichannelExtPresent"]); $CodingMode = value_or_null($attributes["CodingMode"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "UPDATE DVDAUDIOSTREAM SET ID = ?, SampleRate = ?, Channels = ?, Quantisation = ?, CodingMode = ? "; if ($idDVDVMGM != null) { $strSQL .= "WHERE DVDVMGMKey = ? AND DVDVTSKey IS NULL AND Number = ? AND Type = ?;"; } else { $strSQL .= "WHERE DVDVMGMKey IS NULL AND DVDVTSKey = ? AND Number = ? AND Type = ?;"; } $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if ($idDVDVMGM != null) { if (!$stmt->bind_param("iiissiis", $ID, $SampleRate, $Channels, $Quantisation, $CodingMode, $idDVDVMGM, $Number, $Type)) { $ResponseText = "Error binding parameters for DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } else { if (!$stmt->bind_param("iiissiis", $ID, $SampleRate, $Channels, $Quantisation, $CodingMode, $idDVDVTS, $Number, $Type)) { $ResponseText = "Error binding parameters for DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDAUDIOSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function addAudioStreamEx($mysqli, $audiostreamExTag, $idDVDVTS) { $attributes = $audiostreamExTag->attributes(); $Number = value_or_null($attributes["Number"]); $Type = value_or_null($attributes["Type"]); $SuitableForDolbySurroundDecoding = value_or_null($attributes["SuitableForDolbySurroundDecoding"]); $KaraokeVersion = value_or_null($attributes["KaraokeVersion"]); $ApplicationMode = value_or_null($attributes["ApplicationMode"]); $MCIntroPresent = value_or_null($attributes["MCIntroPresent"]); $LanguageCodePresent = value_or_null($attributes["LanguageCodePresent"]); $LanguageCode = value_or_null($attributes["LanguageCode"]); $CodeExtPresent = value_or_null($attributes["CodeExtPresent"]); $CodeExt = value_or_null($attributes["CodeExt"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "INSERT INTO DVDAUDIOSTREAMEX (DVDVTSKey, Number, SuitableForDolbySurroundDecoding, KaraokeVersion, ApplicationMode, MCIntroPresent, LanguageCodePresent, LanguageCode, CodeExtPresent, CodeExt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiiisiisii", $idDVDVTS, $Number, $SuitableForDolbySurroundDecoding, $KaraokeVersion, $ApplicationMode, $MCIntroPresent, $LanguageCodePresent, $LanguageCode, $CodeExtPresent, $CodeExt)) { $ResponseText = "Error binding parameters for DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function updateAudioStreamEx($mysqli, $audiostreamExTag, $idDVDVTS) { $attributes = $audiostreamExTag->attributes(); $Number = value_or_null($attributes["Number"]); $SuitableForDolbySurroundDecoding = value_or_null($attributes["SuitableForDolbySurroundDecoding"]); $KaraokeVersion = value_or_null($attributes["KaraokeVersion"]); $ApplicationMode = value_or_null($attributes["ApplicationMode"]); $MCIntroPresent = value_or_null($attributes["MCIntroPresent"]); $LanguageCodePresent = value_or_null($attributes["LanguageCodePresent"]); $LanguageCode = value_or_null($attributes["LanguageCode"]); $CodeExtPresent = value_or_null($attributes["CodeExtPresent"]); $CodeExt = value_or_null($attributes["CodeExt"]); $strSQL = "UPDATE DVDAUDIOSTREAMEX SET SuitableForDolbySurroundDecoding = ?, KaraokeVersion = ?, ApplicationMode = ?, MCIntroPresent = ?, LanguageCodePresent = ?, LanguageCode = ?, CodeExtPresent = ?, CodeExt = ? WHERE DVDVTSKey = ? AND Number = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("isiisiiiii", $SuitableForDolbySurroundDecoding, $KaraokeVersion, $ApplicationMode, $MCIntroPresent, $LanguageCodePresent, $LanguageCode, $CodeExtPresent, $CodeExt, $idDVDVTS, $Number)) { $ResponseText = "Error binding parameters for DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDAUDIOSTREAMEX table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function addSubPictureStream($mysqli, $tagDVDSUBPICSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDSUBPICSTREAM->attributes(); $Number = value_or_null($attributes["Number"]); $ID = value_or_null($attributes["ID"]); $Type = value_or_null($attributes["Type"]); $CodingMode = value_or_null($attributes["CodingMode"]); $LanguageCodePresent = value_or_null($attributes["LanguageCodePresent"]); $LanguageCode = value_or_null($attributes["LanguageCode"]); $CodeExtPresent = value_or_null($attributes["CodeExtPresent"]); $CodeExt = value_or_null($attributes["CodeExt"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "INSERT INTO DVDSUBPICSTREAM (DVDVMGMKey, DVDVTSKey, Number, ID, Type, CodingMode, LanguageCodePresent, LanguageCode, CodeExtPresent, CodeExt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiissiisii", $idDVDVMGM, $idDVDVTS, $Number, $ID, $Type, $CodingMode, $LanguageCodePresent, $LanguageCode, $CodeExtPresent, $CodeExt)) { $ResponseText = "Error binding parameters for DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function updateSubPictureStream($mysqli, $tagDVDSUBPICSTREAM, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDSUBPICSTREAM->attributes(); $Number = value_or_null($attributes["Number"]); $ID = value_or_null($attributes["ID"]); $Type = value_or_null($attributes["Type"]); $CodingMode = value_or_null($attributes["CodingMode"]); $LanguageCodePresent = value_or_null($attributes["LanguageCodePresent"]); $LanguageCode = value_or_null($attributes["LanguageCode"]); $CodeExtPresent = value_or_null($attributes["CodeExtPresent"]); $CodeExt = value_or_null($attributes["CodeExt"]); if ($idDVDVTS == null) { $Type = "VMG"; } $strSQL = "UPDATE DVDSUBPICSTREAM SET ID = ?, CodingMode = ?, LanguageCodePresent = ?, LanguageCode = ?, CodeExtPresent = ?, CodeExt = ? "; if ($idDVDVMGM != null) { $strSQL .= "WHERE DVDVMGMKey = ? AND DVDVTSKey IS NULL AND Number = ? AND Type = ?;"; } else { $strSQL .= "WHERE DVDVMGMKey IS NULL AND DVDVTSKey = ? AND Number = ? AND Type = ?;"; } $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if ($idDVDVMGM != null) { if (!$stmt->bind_param("siisiiiis", $ID, $CodingMode, $LanguageCodePresent, $LanguageCode, $CodeExtPresent, $CodeExt, $idDVDVMGM, $Number, $Type)) { $ResponseText = "Error binding parameters for DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } else { if (!$stmt->bind_param("siisiiiis", $ID, $CodingMode, $LanguageCodePresent, $LanguageCode, $CodeExtPresent, $CodeExt, $idDVDVTS, $Number, $Type)) { $ResponseText = "Error binding parameters for DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDSUBPICSTREAM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function addFileset($mysqli, $tagDVDFILE, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDFILE->attributes(); $FileSetNo = value_or_null($attributes["Number"]); $Type = value_or_null($attributes["Type"]); $VobNo = value_or_null($attributes["VobNo"]); $Size = value_or_null($attributes["Size"]); $Date = value_or_null($attributes["Date"]); $strSQL = "INSERT INTO DVDFILE (DVDVMGMKey, DVDVTSKey, FileSetNo, Type, VobNo, Size, Date) VALUES (?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiisiis", $idDVDVMGM, $idDVDVTS, $FileSetNo, $Type, $VobNo, $Size, $Date)) { $ResponseText = "Error binding parameters for DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function updateFileset($mysqli, $tagDVDFILE, $idDVDVMGM, $idDVDVTS) { $attributes = $tagDVDFILE->attributes(); $FileSetNo = value_or_null($attributes["Number"]); $Type = value_or_null($attributes["Type"]); $VobNo = value_or_null($attributes["VobNo"]); $Size = value_or_null($attributes["Size"]); $Date = value_or_null($attributes["Date"]); $strSQL = "UPDATE `DVDFILE` SET `Type` = ?, `VobNo` = ?, `Size` = ?, `Date` = ? "; if ($idDVDVMGM != null) { $strSQL .= "WHERE DVDVMGMKey = ? AND DVDVTSKey IS NULL AND FileSetNo = ?;"; } else { $strSQL .= "WHERE DVDVMGMKey IS NULL AND DVDVTSKey = ? AND FileSetNo = ?;"; } $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if ($idDVDVMGM != null) { if (!$stmt->bind_param("siisii", $Type, $VobNo, $Size, $Date, $idDVDVMGM, $FileSetNo)) { $ResponseText = "Error binding parameters for DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } else { if (!$stmt->bind_param("siisii", $Type, $VobNo, $Size, $Date, $idDVDVTS, $FileSetNo)) { $ResponseText = "Error binding parameters for DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDFILE table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); } function submit($mysqli, $xml, $XmlVersion) { /* query_server($mysqli, "TRUNCATE TABLE `DVDAUDIOSTREAM`;"); query_server($mysqli, "TRUNCATE TABLE `DVDAUDIOSTREAMEX`;"); query_server($mysqli, "TRUNCATE TABLE `DVDSUBPICSTREAM`;"); query_server($mysqli, "TRUNCATE TABLE `DVDVIDEOSTREAM`;"); query_server($mysqli, "TRUNCATE TABLE `DVDFILE`;"); query_server($mysqli, "TRUNCATE TABLE `DVDPTTVMG`;"); query_server($mysqli, "TRUNCATE TABLE `DVDPTTVTS`;"); query_server($mysqli, "TRUNCATE TABLE `DVDUNIT`;"); query_server($mysqli, "TRUNCATE TABLE `DVDCELL`;"); query_server($mysqli, "TRUNCATE TABLE `DVDPROGRAM`;"); query_server($mysqli, "TRUNCATE TABLE `DVDPGC`;"); query_server($mysqli, "TRUNCATE TABLE `DVDVTS`;"); query_server($mysqli, "TRUNCATE TABLE `DVDVMGM`;"); */ // Start a transaction query_server($mysqli, "START TRANSACTION;"); foreach ($xml->DVD as $tagDVDVMGM) { $attributes = $tagDVDVMGM->attributes(); $Hash = value_or_null($attributes["Hash"]); $SubmitterIP = value_or_null($_SERVER['REMOTE_ADDR']); $Album = value_or_null($tagDVDVMGM->Album); $OriginalAlbum = value_or_null($tagDVDVMGM->OriginalAlbum); $AlbumArtist = value_or_null($tagDVDVMGM->AlbumArtist); $Genre = value_or_null($tagDVDVMGM->Genre); $Cast = value_or_null($tagDVDVMGM->Cast); $Crew = value_or_null($tagDVDVMGM->Crew); $Director = value_or_null($tagDVDVMGM->Director); $Screenplay = value_or_null($tagDVDVMGM->Screenplay); $Producer = value_or_null($tagDVDVMGM->Producer); $Editing = value_or_null($tagDVDVMGM->Editing); $Cinematography = value_or_null($tagDVDVMGM->Cinematography); $Country = value_or_null($tagDVDVMGM->Country); $OriginalLanguage = value_or_null($tagDVDVMGM->OriginalLanguage); $ReleaseDate = date_or_null($tagDVDVMGM->ReleaseDate); $SpecialFeatures = value_or_null($tagDVDVMGM->SpecialFeatures); $EAN_UPC = value_or_null($tagDVDVMGM->EAN_UPC); $Storyline = value_or_null($tagDVDVMGM->Storyline); $Submitter = value_or_null($tagDVDVMGM->Submitter); $Client = value_or_null($tagDVDVMGM->Client); $Remarks = value_or_null($tagDVDVMGM->Remarks); $Keywords = value_or_null($tagDVDVMGM->Keywords); $RegionProhibited1 = value_or_null($attributes["RegionProhibited1"]); $RegionProhibited2 = value_or_null($attributes["RegionProhibited2"]); $RegionProhibited3 = value_or_null($attributes["RegionProhibited3"]); $RegionProhibited4 = value_or_null($attributes["RegionProhibited4"]); $RegionProhibited5 = value_or_null($attributes["RegionProhibited5"]); $RegionProhibited6 = value_or_null($attributes["RegionProhibited6"]); $RegionProhibited7 = value_or_null($attributes["RegionProhibited7"]); $RegionProhibited8 = value_or_null($attributes["RegionProhibited8"]); $VersionNumberMajor = value_or_null($attributes["VersionNumberMajor"]); $VersionNumberMinor = value_or_null($attributes["VersionNumberMinor"]); $NumberOfVolumes = value_or_null($attributes["NumberOfVolumes"]); $VolumeNumber = value_or_null($attributes["VolumeNumber"]); $SideID = value_or_null($attributes["SideID"]); if ($Submitter == DEFSUBMITTER) { $Submitter = null; } // Check if dataset exists $found = FALSE; /* Feature #884: deactivated unstable feature for rev 0.40 $strSQL = "SELECT `idDVDVMGM`, `RowLastChanged`, `RowCreationDate`, `Submitter`, `SubmitterIP` FROM `DVDVMGM` ". "WHERE `Hash` = '" . $Hash . "' AND `Active` = 1 " . "ORDER BY `Revision` DESC;"; $rsDVDVMGM = query_server($mysqli, $strSQL); if (is_array($Cols = $rsDVDVMGM->fetch_row())) { $idDVDVMGM = $Cols[0]; $RowLastChanged = $Cols[1]; $RowCreationDate = $Cols[2]; $LastSubmitter = $Cols[3]; $LastSubmitterIP = $Cols[4]; // TODO: maybe check submission time if ($Submitter == $LastSubmitter && $SubmitterIP == $LastSubmitterIP) { $found = TRUE; } } $rsDVDVMGM->close(); */ if (!$found) { // Not found: insert new $strSQL = "INSERT INTO `DVDVMGM` (`Hash`, `Album`, `AlbumArtist`, `Genre`, `Cast`, `Crew`, `Director`, `Country`, `ReleaseDate`, `SpecialFeatures`, `EAN_UPC`, `Storyline`, `Remarks`, `Submitter`, `SubmitterIP`, `Client`, `Keywords`, `RegionProhibited1`, `RegionProhibited2`, `RegionProhibited3`, `RegionProhibited4`, `RegionProhibited5`, `RegionProhibited6`, `RegionProhibited7`, `RegionProhibited8`, `VersionNumberMajor`, `VersionNumberMinor`, `NumberOfVolumes`, `VolumeNumber`, `SideID`, `OriginalAlbum`, `Screenplay`, `Producer`, `Editing`, `Cinematography`, `OriginalLanguage`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("sssssssssssssssssiiiiiiiiiiiiissssss", $Hash, $Album, $AlbumArtist, $Genre, $Cast, $Crew, $Director, $Country, $ReleaseDate, $SpecialFeatures, $EAN_UPC, $Storyline, $Remarks, $Submitter, $SubmitterIP, $Client, $Keywords, $RegionProhibited1, $RegionProhibited2, $RegionProhibited3, $RegionProhibited4, $RegionProhibited5, $RegionProhibited6, $RegionProhibited7, $RegionProhibited8, $VersionNumberMajor, $VersionNumberMinor, $NumberOfVolumes, $VolumeNumber, $SideID, $OriginalAlbum, $Screenplay, $Producer, $Editing, $Cinematography, $OriginalLanguage)) { $ResponseText = "Error binding parameters for DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); $stmt = null; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); $stmt = null; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDVMGM = $mysqli->insert_id; $stmt->close(); $stmt = null; // Physical structure $tagPhysical = $tagDVDVMGM->physical; foreach ($tagPhysical->DVDVTS as $tagDVDVTS) { // Insert DVDVTS (Video Title Set) $attributes = $tagDVDVTS->attributes(); $TitleSetNo = $attributes["TitleSetNo"]; $VersionNumberMajor = value_or_null($attributes["VersionNumberMajor"]); $VersionNumberMinor = value_or_null($attributes["VersionNumberMinor"]); $strSQL = "INSERT INTO `DVDVTS` (`DVDVMGMKey`, `TitleSetNo`, `VersionNumberMajor`, `VersionNumberMinor`) VALUES (?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiii", $idDVDVMGM, $TitleSetNo, $VersionNumberMajor, $VersionNumberMinor)) { $ResponseText = "Error binding parameters for DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDVTS = $mysqli->insert_id; $stmt->close(); foreach ($tagDVDVTS->DVDPGC as $tagDVDPGC) { // Insert DVDPGC (Program Chain) $attributes = $tagDVDPGC->attributes(); $ProgramChainNo = value_or_null($attributes["Number"]); $EntryPGC = value_or_null($attributes["EntryPGC"]); $strSQL = "INSERT INTO `DVDPGC` (`DVDVTSKey`, `ProgramChainNo`, `EntryPGC`) VALUES (?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iii", $idDVDVTS, $ProgramChainNo, $EntryPGC)) { $ResponseText = "Error binding parameters for DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDPGC = $mysqli->insert_id; $stmt->close(); foreach ($tagDVDPGC->DVDPROGRAM as $tagDVDPROGRAM) { // Insert DVDPGC (Program) $attributes = $tagDVDPROGRAM->attributes(); $ProgramNo = value_or_null($attributes["Number"]); $strSQL = "INSERT INTO `DVDPROGRAM` (`DVDPGCKey`, `ProgramNo`) VALUES (?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for chapter table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("ii", $idDVDPGC, $ProgramNo)) { $ResponseText = "Error binding parameters for chapter table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on chapter table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDPROGRAM = $mysqli->insert_id; $stmt->close(); foreach ($tagDVDPROGRAM->DVDCELL as $tagDVDCELL) { // Insert DVDCELL (Cell) $attributes = $tagDVDCELL->attributes(); $CellNo = value_or_null($attributes["Number"]); $CellType = value_or_null($attributes["CellType"]); $BlockType = value_or_null($attributes["BlockType"]); $SeamlessMultiplex = value_or_null($attributes["SeamlessMultiplex"]); $Interleaved = value_or_null($attributes["Interleaved"]); $SCRdiscontinuity = value_or_null($attributes["SCRdiscontinuity"]); $SeamlessAngleLinkedInDSI = value_or_null($attributes["SeamlessAngleLinkedInDSI"]); $VOBStillMode = value_or_null($attributes["VOBStillMode"]); $StopsTrickPlay = value_or_null($attributes["StopsTrickPlay"]); $CellStillTime = value_or_null($attributes["CellStillTime"]); $CellCommand = value_or_null($attributes["CellCommand"]); $PlayTime = value_or_null($attributes["PlayTime"]); $FrameRate = value_or_null($attributes["FrameRate"]); $FirstVOBUStartSector = value_or_null($attributes["FirstVOBUStartSector"]); $FirstILVUEndSector = value_or_null($attributes["FirstILVUEndSector"]); $LastVOBUStartSector = value_or_null($attributes["LastVOBUStartSector"]); $LastVOBUEndSector = value_or_null($attributes["LastVOBUEndSector"]); $VOBidn = value_or_null($attributes["VOBidn"]); $CELLidn = value_or_null($attributes["CELLidn"]); $NumberOfVOBIds = value_or_null($attributes["NumberOfVOBIds"]); $strSQL = "INSERT INTO `DVDCELL` (`DVDPROGRAMKey`, `CellNo`, `CellType`, `BlockType`, `SeamlessMultiplex`, `Interleaved`, `SCRdiscontinuity`, `SeamlessAngleLinkedInDSI`, `VOBStillMode`, `StopsTrickPlay`, `CellStillTime`, `CellCommand`, `PlayTime`, `FrameRate`, `FirstVOBUStartSector`, `FirstILVUEndSector`, `LastVOBUStartSector`, `LastVOBUEndSector`, `VOBidn`, `CELLidn`, `NumberOfVOBIds`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iissiiiiiiiiiiiiiiiii", $idDVDPROGRAM, $CellNo, $CellType, $BlockType, $SeamlessMultiplex, $Interleaved, $SCRdiscontinuity, $SeamlessAngleLinkedInDSI, $VOBStillMode, $StopsTrickPlay, $CellStillTime, $CellCommand, $PlayTime, $FrameRate, $FirstVOBUStartSector, $FirstILVUEndSector, $LastVOBUStartSector, $LastVOBUEndSector, $VOBidn, $CELLidn, $NumberOfVOBIds)) { $ResponseText = "Error binding parameters for DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDCELL = $mysqli->insert_id; $stmt->close(); foreach ($tagDVDCELL->DVDUNIT as $tagDVDUNIT) { // Insert DVDUNIT (Unit) $attributes = $tagDVDUNIT->attributes(); $UnitNo = value_or_null($attributes["Number"]); $StartSector = value_or_null($attributes["StartSector"]); $EndSector = value_or_null($attributes["EndSector"]); $strSQL = "INSERT INTO `DVDUNIT` (`DVDCELLKey`, `UnitNo`, `StartSector`, `EndSector`) VALUES (?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiii", $idDVDCELL, $UnitNo, $StartSector, $EndSector)) { $ResponseText = "Error binding parameters for DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } //$idDVDUNIT = $mysqli->insert_id; $stmt->close(); } } } } // DVDVIDEOSTREAM foreach ($tagDVDVTS->DVDVIDEOSTREAM as $tagDVDVIDEOSTREAM) { addVideoStream($mysqli, $tagDVDVIDEOSTREAM, null, $idDVDVTS); } // DVDAUDIOSTREAM foreach ($tagDVDVTS->DVDAUDIOSTREAM as $tagDVDAUDIOSTREAM) { addAudioStream($mysqli, $tagDVDAUDIOSTREAM, null, $idDVDVTS); } // DVDAUDIOSTREAMEX foreach ($tagDVDVTS->DVDAUDIOSTREAMEX as $audiostreamExTag) { addAudioStreamEx($mysqli, $audiostreamExTag, $idDVDVTS); } // DVDSUBPICSTREAM foreach ($tagDVDVTS->DVDSUBPICSTREAM as $tagDVDSUBPICSTREAM) { addSubpictureStream($mysqli, $tagDVDSUBPICSTREAM, null, $idDVDVTS); } // Fileset foreach ($tagDVDVTS->DVDFILE as $tagDVDFILE) { addFileset($mysqli, $tagDVDFILE, null, $idDVDVTS); } } // Virtual structure $tagVirtual = $tagDVDVMGM->virtual; foreach ($tagVirtual->DVDPTTVMG as $tagDVDPTTVMG) { // Insert DVDPTTVMG (Video Title Set) $attributes = $tagDVDPTTVMG->attributes(); $Title = value_or_null($tagDVDPTTVMG->Title); $TitleSetNo = value_or_null($attributes["TitleSetNo"]); $PlaybackType = value_or_null($attributes["PlaybackType"]); $NumberOfVideoAngles = value_or_null($attributes["NumberOfVideoAngles"]); $ParentalMgmMaskVMG = value_or_null($attributes["ParentalMgmMaskVMG"]); $ParentalMgmMaskVTS = value_or_null($attributes["ParentalMgmMaskVTS"]); $NumberOfVideoAngles = value_or_null($attributes["NumberOfVideoAngles"]); $VideoTitleSetNo = value_or_null($attributes["VideoTitleSetNo"]); $TitleNo = value_or_null($attributes["TitleNo"]); $strSQL = "INSERT INTO `DVDPTTVMG` (`DVDVMGMKey`, `TitleSetNo`, `Title`, `PlaybackType`, `NumberOfVideoAngles`, `ParentalMgmMaskVMG`, `ParentalMgmMaskVTS`, `VideoTitleSetNo`, `TitleNo`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iisiiiiii", $idDVDVMGM, $TitleSetNo, $Title, $PlaybackType, $NumberOfVideoAngles, $ParentalMgmMaskVMG, $ParentalMgmMaskVTS, $VideoTitleSetNo, $TitleNo)) { $ResponseText = "Error binding parameters for DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $idDVDPTTVMG = $mysqli->insert_id; $stmt->close(); foreach ($tagDVDPTTVMG->DVDPTTVTS as $tagDVDPTTVTS) { // Insert DVDPTTVTS (Chapter) $attributes = $tagDVDPTTVTS->attributes(); $Title = value_or_null($tagDVDPTTVTS->Title); $Artist = value_or_null($tagDVDPTTVTS->Artist); $ProgramChainNo = value_or_null($attributes["ProgramChainNo"]); $ProgramNo = value_or_null($attributes["ProgramNo"]); $PttTitleSetNo = value_or_null($attributes["PttTitleSetNo"]); $PttChapterNo = value_or_null($attributes["Number"]); $TitleSetNo = value_or_null($attributes["TitleSetNo"]); $strSQL = "INSERT INTO `DVDPTTVTS` (`DVDPTTVMGKey`, `Artist`, `Title`, `ProgramChainNo`, `ProgramNo`, `PttTitleSetNo`, `PttChapterNo`, `TitleSetNo`) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("issiiiii", $idDVDPTTVMG, $Artist, $Title, $ProgramChainNo, $ProgramNo, $PttTitleSetNo, $PttChapterNo, $TitleSetNo)) { $ResponseText = "Error binding parameters for DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } //$idDVDPTTVTS = $mysqli->insert_id; $stmt->close(); } } // DVDVIDEOSTREAM foreach ($tagDVDVMGM->DVDVIDEOSTREAM as $tagDVDVIDEOSTREAM) { addVideoStream($mysqli, $tagDVDVIDEOSTREAM, $idDVDVMGM, null); } // DVDAUDIOSTREAM foreach ($tagDVDVMGM->DVDAUDIOSTREAM as $tagDVDAUDIOSTREAM) { addAudioStream($mysqli, $tagDVDAUDIOSTREAM, $idDVDVMGM, null); } // DVDSUBPICSTREAM foreach ($tagDVDVMGM->DVDSUBPICSTREAM as $tagDVDSUBPICSTREAM) { addSubpictureStream($mysqli, $tagDVDSUBPICSTREAM, $idDVDVMGM, null); } // Fileset foreach ($tagDVDVMGM->DVDFILE as $tagDVDFILE) { addFileset($mysqli, $tagDVDFILE, $idDVDVMGM, null); } } else { // Found: do an update $strSQL = "UPDATE `DVDVMGM` SET `Album` = ?, `AlbumArtist` = ?, `Genre` = ?, `Cast` = ?, `Crew` = ?, `Director` = ?, `Country` = ?, `ReleaseDate` = ?, `SpecialFeatures` = ?, `EAN_UPC` = ?, `Storyline` = ?, `Remarks` = ?, `Submitter` = ?, `SubmitterIP` = ?, `Client` = ?, `Keywords` = ?, `RegionProhibited1` = ?, `RegionProhibited2` = ?, `RegionProhibited3` = ?, `RegionProhibited4` = ?, `RegionProhibited5` = ?, `RegionProhibited6` = ?, `RegionProhibited7` = ?, `RegionProhibited8` = ?, `VersionNumberMajor` = ?, `VersionNumberMinor` = ?, `NumberOfVolumes` = ?, `VolumeNumber` = ?, `OriginalAlbum` = ?, `Screenplay` = ?, `Producer` = ?, `Editing` = ?, `Cinematography` = ?, `OriginalLanguage` = ?, `SideID` = ? WHERE `idDVDVMGM` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("ssssssssssssssssiiiiiiiiiiiissssssii", $Album, $AlbumArtist, $Genre, $Cast, $Crew, $Director, $Country, $ReleaseDate, $SpecialFeatures, $EAN_UPC, $Storyline, $Remarks, $Submitter, $SubmitterIP, $Client, $Keywords, $RegionProhibited1, $RegionProhibited2, $RegionProhibited3, $RegionProhibited4, $RegionProhibited5, $RegionProhibited6, $RegionProhibited7, $RegionProhibited8, $VersionNumberMajor, $VersionNumberMinor, $NumberOfVolumes, $VolumeNumber, $OriginalAlbum, $Screenplay, $Producer, $Editing, $Cinematography, $OriginalLanguage, $SideID, $idDVDVMGM)) { $ResponseText = "Error binding parameters for DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); $stmt = null; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVMGM table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); $stmt = null; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); $stmt = null; // Physical structure $tagPhysical = $tagDVDVMGM->physical; foreach ($tagPhysical->DVDVTS as $tagDVDVTS) { // Update DVDVTS (Video Title Set) $attributes = $tagDVDVTS->attributes(); $TitleSetNo = $attributes["TitleSetNo"]; $VersionNumberMajor = value_or_null($attributes["VersionNumberMajor"]); $VersionNumberMinor = value_or_null($attributes["VersionNumberMinor"]); $idDVDVTS = getPrimaryKey($mysqli, "DVDVTS", "idDVDVTS", "`DVDVMGMKey` = $idDVDVMGM AND `TitleSetNo` = $TitleSetNo"); $strSQL = "UPDATE `DVDVTS` SET `TitleSetNo` = ?, `VersionNumberMajor` = ?, `VersionNumberMinor` = ? WHERE `idDVDVTS` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing update statement for DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiii", $TitleSetNo, $VersionNumberMajor, $VersionNumberMinor, $idDVDVTS)) { $ResponseText = "Error binding parameters for DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); foreach ($tagDVDVTS->DVDPGC as $tagDVDPGC) { // Update DVDPGC (Program Chain) $attributes = $tagDVDPGC->attributes(); $ProgramChainNo = value_or_null($attributes["Number"]); $EntryPGC = value_or_null($attributes["EntryPGC"]); $idDVDPGC = getPrimaryKey($mysqli, "DVDPGC", "idDVDPGC", "`DVDVTSKey` = $idDVDVTS AND `ProgramChainNo` = $ProgramChainNo"); $strSQL = "UPDATE `DVDPGC` SET `EntryPGC` = ? WHERE `idDVDPGC` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("ii", $EntryPGC, $idDVDPGC)) { $ResponseText = "Error binding parameters for DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPGC table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); foreach ($tagDVDPGC->DVDPROGRAM as $tagDVDPROGRAM) { // Update DVDPGC (Program) $attributes = $tagDVDPROGRAM->attributes(); $ProgramNo = value_or_null($attributes["Number"]); // Nothing to update... $idDVDPROGRAM = getPrimaryKey($mysqli, "DVDPROGRAM", "idDVDPROGRAM", "`DVDPGCKey` = $idDVDPGC AND `ProgramNo` = $ProgramNo"); foreach ($tagDVDPROGRAM->DVDCELL as $tagDVDCELL) { // Update DVDCELL (Cell) $attributes = $tagDVDCELL->attributes(); $CellNo = value_or_null($attributes["Number"]); $CellType = value_or_null($attributes["CellType"]); $BlockType = value_or_null($attributes["BlockType"]); $SeamlessMultiplex = value_or_null($attributes["SeamlessMultiplex"]); $Interleaved = value_or_null($attributes["Interleaved"]); $SCRdiscontinuity = value_or_null($attributes["SCRdiscontinuity"]); $SeamlessAngleLinkedInDSI = value_or_null($attributes["SeamlessAngleLinkedInDSI"]); $VOBStillMode = value_or_null($attributes["VOBStillMode"]); $StopsTrickPlay = value_or_null($attributes["StopsTrickPlay"]); $CellStillTime = value_or_null($attributes["CellStillTime"]); $CellCommand = value_or_null($attributes["CellCommand"]); $PlayTime = value_or_null($attributes["PlayTime"]); $FrameRate = value_or_null($attributes["FrameRate"]); $FirstVOBUStartSector = value_or_null($attributes["FirstVOBUStartSector"]); $FirstILVUEndSector = value_or_null($attributes["FirstILVUEndSector"]); $LastVOBUStartSector = value_or_null($attributes["LastVOBUStartSector"]); $LastVOBUEndSector = value_or_null($attributes["LastVOBUEndSector"]); $VOBidn = value_or_null($attributes["VOBidn"]); $CELLidn = value_or_null($attributes["CELLidn"]); $NumberOfVOBIds = value_or_null($attributes["NumberOfVOBIds"]); $idDVDCELL = getPrimaryKey($mysqli, "DVDCELL", "idDVDCELL", "`DVDPROGRAMKey` = $idDVDPROGRAM AND `CellNo` = $CellNo"); $strSQL = "UPDATE `DVDCELL` SET `CellType` = ?, `BlockType` = ?, `SeamlessMultiplex` = ?, `Interleaved` = ?, `SCRdiscontinuity` = ?, `SeamlessAngleLinkedInDSI` = ?, `VOBStillMode` = ?, `StopsTrickPlay` = ?, `CellStillTime` = ?, `CellCommand` = ?, `PlayTime` = ?, `FrameRate` = ?, `FirstVOBUStartSector` = ?, `FirstILVUEndSector` = ?, `LastVOBUStartSector` = ?, `LastVOBUEndSector` = ?, `VOBidn` = ?, `CELLidn` = ?, `NumberOfVOBIds` = ? WHERE `idDVDCELL` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("ssiiiiiiiiiiiiiiiiii", $CellType, $BlockType, $SeamlessMultiplex, $Interleaved, $SCRdiscontinuity, $SeamlessAngleLinkedInDSI, $VOBStillMode, $StopsTrickPlay, $CellStillTime, $CellCommand, $PlayTime, $FrameRate, $FirstVOBUStartSector, $FirstILVUEndSector, $LastVOBUStartSector, $LastVOBUEndSector, $VOBidn, $CELLidn, $NumberOfVOBIds, $idDVDCELL)) { $ResponseText = "Error binding parameters for DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDCELL table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); foreach ($tagDVDCELL->DVDUNIT as $tagDVDUNIT) { // Update DVDUNIT (Unit) $attributes = $tagDVDUNIT->attributes(); $UnitNo = value_or_null($attributes["Number"]); $StartSector = value_or_null($attributes["StartSector"]); $EndSector = value_or_null($attributes["EndSector"]); $strSQL = "UPDATE `DVDUNIT` SET `StartSector` = ?, `EndSector` = ? WHERE `DVDCELLKey` = ? AND `UnitNo` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("iiii", $StartSector, $EndSector, $idDVDCELL, $UnitNo)) { $ResponseText = "Error binding parameters for DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDUNIT table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } //$idDVDUNIT = $mysqli->insert_id; $stmt->close(); } } } } // DVDVIDEOSTREAM foreach ($tagDVDVTS->DVDVIDEOSTREAM as $tagDVDVIDEOSTREAM) { updateVideoStream($mysqli, $tagDVDVIDEOSTREAM, null, $idDVDVTS); } // DVDAUDIOSTREAM foreach ($tagDVDVTS->DVDAUDIOSTREAM as $tagDVDAUDIOSTREAM) { updateAudioStream($mysqli, $tagDVDAUDIOSTREAM, null, $idDVDVTS); } // DVDAUDIOSTREAMEX foreach ($tagDVDVTS->DVDAUDIOSTREAMEX as $audiostreamExTag) { updateAudioStreamEx($mysqli, $audiostreamExTag, $idDVDVTS); } // DVDSUBPICSTREAM foreach ($tagDVDVTS->DVDSUBPICSTREAM as $tagDVDSUBPICSTREAM) { updateSubpictureStream($mysqli, $tagDVDSUBPICSTREAM, null, $idDVDVTS); } // Fileset foreach ($tagDVDVTS->DVDFILE as $tagDVDFILE) { updateFileset($mysqli, $tagDVDFILE, null, $idDVDVTS); } } // Virtual structure $tagVirtual = $tagDVDVMGM->virtual; foreach ($tagVirtual->DVDPTTVMG as $tagDVDPTTVMG) { // Update DVDPTTVMG (Video Title Set) $attributes = $tagDVDPTTVMG->attributes(); $Title = value_or_null($tagDVDPTTVMG->Title); $TitleSetNo = value_or_null($attributes["TitleSetNo"]); $PlaybackType = value_or_null($attributes["PlaybackType"]); $NumberOfVideoAngles = value_or_null($attributes["NumberOfVideoAngles"]); $ParentalMgmMaskVMG = value_or_null($attributes["ParentalMgmMaskVMG"]); $ParentalMgmMaskVTS = value_or_null($attributes["ParentalMgmMaskVTS"]); $NumberOfVideoAngles = value_or_null($attributes["NumberOfVideoAngles"]); $VideoTitleSetNo = value_or_null($attributes["VideoTitleSetNo"]); $TitleNo = value_or_null($attributes["TitleNo"]); $idDVDPTTVMG = getPrimaryKey($mysqli, "DVDPTTVMG", "idDVDPTTVMG", "`DVDVMGMKey` = $idDVDVMGM AND `TitleSetNo` = $TitleSetNo"); $strSQL = "UPDATE `DVDPTTVMG` SET `Title` = ?, `PlaybackType` = ?, `NumberOfVideoAngles` = ?, `ParentalMgmMaskVMG` = ?, `ParentalMgmMaskVTS` = ?, `VideoTitleSetNo` = ?, `TitleNo` = ? WHERE `idDVDPTTVMG` = ?;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("siiiiiii", $Title, $PlaybackType, $NumberOfVideoAngles, $ParentalMgmMaskVMG, $ParentalMgmMaskVTS, $VideoTitleSetNo, $TitleNo, $idDVDPTTVMG)) { $ResponseText = "Error binding parameters for DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPTTVMG table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } $stmt->close(); foreach ($tagDVDPTTVMG->DVDPTTVTS as $tagDVDPTTVTS) { // Update DVDPTTVTS (Chapter) $attributes = $tagDVDPTTVTS->attributes(); $Title = value_or_null($tagDVDPTTVTS->Title); $Artist = value_or_null($tagDVDPTTVTS->Artist); $ProgramChainNo = value_or_null($attributes["ProgramChainNo"]); $ProgramNo = value_or_null($attributes["ProgramNo"]); $PttTitleSetNo = value_or_null($attributes["PttTitleSetNo"]); $PttChapterNo = value_or_null($attributes["Number"]); $TitleSetNo = value_or_null($attributes["TitleSetNo"]); $strSQL = "UPDATE `DVDPTTVTS` SET `Artist` = ?, `Title` = ?, `ProgramChainNo` = ?, `ProgramNo` = ?, `PttTitleSetNo` = ?, TitleSetNo = ? WHERE `DVDPTTVMGKey` = ? AND `PttChapterNo` = ? ;"; $stmt = $mysqli->prepare($strSQL); if (!$stmt) { $ResponseText = "Error preparing insert statement for DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->bind_param("ssiiiiii", $Artist, $Title, $ProgramChainNo, $ProgramNo, $PttTitleSetNo, $TitleSetNo, $idDVDPTTVMG, $PttChapterNo)) { $ResponseText = "Error binding parameters for DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } if (!$stmt->execute()) { $ResponseText = "Error executing statement on DVDPTTVTS table.\nSQL Error: " . $mysqli->error . "\nSQL State: " . $mysqli->sqlstate; $stmt->close(); throw new Exception($ResponseText, XMLRESULT_SQL_ERROR); } //$idDVDPTTVTS = $mysqli->insert_id; $stmt->close(); } } // DVDVIDEOSTREAM foreach ($tagDVDVMGM->DVDVIDEOSTREAM as $tagDVDVIDEOSTREAM) { updateVideoStream($mysqli, $tagDVDVIDEOSTREAM, $idDVDVMGM, null); } // DVDAUDIOSTREAM foreach ($tagDVDVMGM->DVDAUDIOSTREAM as $tagDVDAUDIOSTREAM) { updateAudioStream($mysqli, $tagDVDAUDIOSTREAM, $idDVDVMGM, null); } // DVDSUBPICSTREAM foreach ($tagDVDVMGM->DVDSUBPICSTREAM as $tagDVDSUBPICSTREAM) { updateSubpictureStream($mysqli, $tagDVDSUBPICSTREAM, $idDVDVMGM, null); } // Fileset foreach ($tagDVDVMGM->DVDFILE as $tagDVDFILE) { updateFileset($mysqli, $tagDVDFILE, $idDVDVMGM, null); } } } // Commit the transaction $rs = query_server($mysqli, "COMMIT;"); } ?>
nschlia/libdvdetect
php/inc/functions.submit.inc.php
PHP
lgpl-3.0
70,731
/* Galois, a framework to exploit amorphous data-parallelism in irregular programs. Copyright (C) 2010, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. File: GNode.java */ package galois.objects.graph; import galois.objects.GObject; import galois.objects.Lockable; import galois.objects.Mappable; import galois.runtime.Replayable; /** * A node in a graph. * * @param <N> the type of the data stored in each node */ public interface GNode<N> extends Replayable, Lockable, Mappable<GNode<N>>, GObject { /** * Retrieves the node data associated with the vertex * * All the Galois runtime actions (e.g., conflict detection) will be performed when * the method is executed. * * @return the data contained in the node */ public N getData(); /** * Retrieves the node data associated with the vertex. Equivalent to {@link #getData(byte, byte)} * passing <code>flags</code> to both parameters. * * @param flags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method. See {@link galois.objects.MethodFlag} * @return the data contained in the node */ public N getData(byte flags); /** * Retrieves the node data associated with the vertex. For convenience, this method * also calls {@link GObject#access(byte)} on the returned data. * * <p>Recall that the * {@link GNode} object maintains information about the vertex and its connectivity * in the graph. This is separate from the data itself. For example, * <code>getData(MethodFlag.NONE, MethodFlag.SAVE_UNDO)</code> * does not acquire an abstract lock on the {@link GNode} (perhaps because * it was returned by a call to {@link GNode#map(util.fn.LambdaVoid)}), but it * saves undo information on the returned data in case the iteration needs to * be rolled back. * </p> * * @param nodeFlags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method on the <i>node itself</i>. * See {@link galois.objects.MethodFlag} * @param dataFlags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method on the <i>data</i> contained in the node. * See {@link galois.objects.MethodFlag} * @return the data contained in the node */ public N getData(byte nodeFlags, byte dataFlags); /** * Sets the node data. * * All the Galois runtime actions (e.g., conflict detection) will be performed when * the method is executed. * * @param d the data to be stored * @return the old data associated with the node */ public N setData(N d); /** * Sets the node data. * * @param d the data to be stored * @param flags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method. See {@link galois.objects.MethodFlag} * @return the old data associated with the node */ public N setData(N d, byte flags); }
chmaruni/SCJ
Shared/libs_src/Galois-2.0/src/galois/objects/graph/GNode.java
Java
lgpl-3.0
3,896
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace SharpGraphLib { public partial class LegendControl : UserControl { List<LegendLabel> _Labels = new List<LegendLabel>(); bool _AllowHighlightingGraphs = true, _AllowDisablingGraphs = true; [Category("Behavior")] [DefaultValue(true)] public bool AllowDisablingGraphs { get { return _AllowDisablingGraphs; } set { _AllowDisablingGraphs = value;} } [Category("Behavior")] [DefaultValue(true)] public bool AllowHighlightingGraphs { get { return _AllowHighlightingGraphs; } set { _AllowHighlightingGraphs = value; } } bool _Autosize; internal bool Autosize { get { return _Autosize; } set { _Autosize = value; if (value) { Width = _AutoWidth; Height = _AutoHeight; } } } public LegendControl() { InitializeComponent(); } [Category("Appearance")] public string NoGraphsLabel { get { return label1.Text; } set { label1.Text = value; } } internal GraphViewer _GraphViewer; int _AutoWidth, _AutoHeight; /// <summary> /// Collection items should implement ILegendItem /// </summary> protected virtual System.Collections.IEnumerable Items { get { if (_GraphViewer == null) return null; return _GraphViewer.DisplayedGraphs; } } public void UpdateLegend() { foreach (LegendLabel lbl in _Labels) lbl.Dispose(); _Labels.Clear(); int i = 0; if (Items != null) { _AutoWidth = 0; foreach (ILegendItem gr in Items) { if (gr.HiddenFromLegend) continue; LegendLabel lbl = new LegendLabel { ForeColor = ForeColor }; lbl.Parent = this; lbl.SquareColor = gr.Color; lbl.Text = gr.Hint; lbl.Grayed = gr.Hidden; lbl.Left = 0; lbl.Top = i * lbl.Height + label1.Top; lbl.Width = Width; lbl.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; lbl.Tag = gr; lbl.Cursor = Cursors.Arrow; lbl.MouseClick += new MouseEventHandler(LegendPanel_MouseClick); lbl.MouseEnter += new EventHandler(LegendPanel_MouseEnter); lbl.MouseLeave += new EventHandler(LegendPanel_MouseLeave); lbl.MouseMove += new MouseEventHandler(lbl_MouseMove); lbl.MouseDown += new MouseEventHandler(lbl_MouseDown); _AutoWidth = Math.Max(_AutoWidth, lbl.Left + lbl.MeasureWidth() + 10); _AutoHeight = lbl.Bottom + 10; lbl.Visible = true; _Labels.Add(lbl); i++; } label1.Visible = false; } if (i == 0) { label1.Visible = true; _AutoWidth = label1.Right + 10; _AutoHeight = label1.Bottom + 10; } if (_Autosize) { Width = _AutoWidth; Height = _AutoHeight; } } protected virtual void lbl_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point newPoint = PointToClient((sender as Control).PointToScreen(e.Location)); OnMouseDown(new MouseEventArgs(e.Button, e.Clicks, newPoint.X, newPoint.Y, e.Delta)); } } protected virtual void lbl_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point newPoint = PointToClient((sender as Control).PointToScreen(e.Location)); OnMouseMove(new MouseEventArgs(e.Button, e.Clicks, newPoint.X, newPoint.Y, e.Delta)); } } public delegate void HandleLabelHilighted(ILegendItem item); public event HandleLabelHilighted OnLabelHilighted; LegendLabel _ActiveLabel; public ILegendItem ActiveItem { get { if (_ActiveLabel == null) return null; return _ActiveLabel.Tag as ILegendItem; } } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); _ActiveLabel = null; } void LegendPanel_MouseLeave(object sender, EventArgs e) { if (!_AllowHighlightingGraphs) return; LegendLabel lbl = sender as LegendLabel; lbl.BackColor = BackColor; if (OnLabelHilighted != null) OnLabelHilighted(null); } void LegendPanel_MouseEnter(object sender, EventArgs e) { _ActiveLabel = sender as LegendLabel; if (!_AllowHighlightingGraphs) return; LegendLabel lbl = sender as LegendLabel; lbl.BackColor = _HighlightedColor; if (OnLabelHilighted != null) OnLabelHilighted((ILegendItem)lbl.Tag); } public delegate void HandleLabelGrayed(ILegendItem graph, bool grayed); public event HandleLabelGrayed OnLabelGrayed; virtual protected void LegendPanel_MouseClick(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Left) return; if (!_AllowDisablingGraphs) return; LegendLabel label = sender as LegendLabel; label.Grayed = !label.Grayed; if (OnLabelGrayed != null) OnLabelGrayed((ILegendItem)label.Tag, label.Grayed); } private Color _HighlightedColor = Color.LemonChiffon; public System.Drawing.Color HighlightedColor { get { return _HighlightedColor; } set { _HighlightedColor = value; Invalidate(); } } } }
sysprogs/SharpGraphLib
SharpGraphLib/LegendControl.cs
C#
lgpl-3.0
7,121
/** * * This file is part of Disco. * * Disco 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. * * Disco 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 Disco. If not, see <http://www.gnu.org/licenses/>. */ package eu.diversify.disco.cloudml; import eu.diversify.disco.population.diversity.TrueDiversity; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Options { private static final String JSON_FILE_NAME = "[^\\.]*\\.json$"; private static final String DOUBLE_LITERAL = "((\\+|-)?([0-9]+)(\\.[0-9]+)?)|((\\+|-)?\\.?[0-9]+)"; public static final String ENABLE_GUI = "-gui"; public static Options fromCommandLineArguments(String... arguments) { Options extracted = new Options(); for (String argument : arguments) { if (isJsonFile(argument)) { extracted.addDeploymentModel(argument); } else if (isDouble(argument)) { extracted.setReference(Double.parseDouble(argument)); } else if (isEnableGui(argument)) { extracted.setGuiEnabled(true); } else { throw new IllegalArgumentException("Unknown argument: " + argument); } } return extracted; } private static boolean isJsonFile(String argument) { return argument.matches(JSON_FILE_NAME); } private static boolean isDouble(String argument) { return argument.matches(DOUBLE_LITERAL); } private static boolean isEnableGui(String argument) { return argument.matches(ENABLE_GUI); } private boolean guiEnabled; private final List<String> deploymentModels; private double reference; public Options() { this.guiEnabled = false; this.deploymentModels = new ArrayList<String>(); this.reference = 0.75; } public boolean isGuiEnabled() { return guiEnabled; } public void setGuiEnabled(boolean guiEnabled) { this.guiEnabled = guiEnabled; } public double getReference() { return reference; } public void setReference(double setPoint) { this.reference = setPoint; } public List<String> getDeploymentModels() { return Collections.unmodifiableList(deploymentModels); } public void addDeploymentModel(String pathToModel) { this.deploymentModels.add(pathToModel); } public void launchDiversityController() { final CloudMLController controller = new CloudMLController(new TrueDiversity().normalise()); if (guiEnabled) { startGui(controller); } else { startCommandLine(controller); } } private void startGui(final CloudMLController controller) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { final Gui gui = new Gui(controller); gui.setReference(reference); gui.setFileToLoad(deploymentModels.get(0)); gui.setVisible(true); } }); } private void startCommandLine(final CloudMLController controller) { final CommandLine commandLine = new CommandLine(controller); for (String deployment : getDeploymentModels()) { commandLine.controlDiversity(deployment, reference); } } }
DIVERSIFY-project/disco
samples/cloudml/controller/src/main/java/eu/diversify/disco/cloudml/Options.java
Java
lgpl-3.0
3,917
using iTextSharp.text; namespace PdfRpt.VectorCharts { /// <summary> /// BarChartItem /// </summary> public class BarChartItem { /// <summary> /// BarChartItem /// </summary> public BarChartItem() { } /// <summary> /// BarChartItem /// </summary> /// <param name="value">Value of the chart's item.</param> /// <param name="label">Label of the item.</param> /// <param name="color">Color of the item.</param> public BarChartItem(double value, string label, BaseColor color) { Value = value; Label = label; Color = color; } /// <summary> /// BarChartItem /// </summary> /// <param name="value">Value of the chart's item.</param> /// <param name="label">Label of the item.</param> /// <param name="color">Color of the item.</param> public BarChartItem(double value, string label, System.Drawing.Color color) { Value = value; Label = label; Color = new BaseColor(color.ToArgb()); } /// <summary> /// Value of the chart's item. /// </summary> public double Value { set; get; } /// <summary> /// Label of the item. /// </summary> public string Label { set; get; } /// <summary> /// Color of the item. /// </summary> public BaseColor Color { set; get; } } }
VahidN/PdfReport
Lib/VectorCharts/BarChartItem.cs
C#
lgpl-3.0
1,535
#include <cstdio> #include <iostream> #include <vector> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; #define DEBUG #undef DEBUG //uncomment this line to pull out print statements #ifdef DEBUG #define TAB '\t' #define debug(a, end) cout << #a << ": " << a << end #else #define debug(a, end) #endif typedef pair<int, int> point; typedef long long int64; //for clarity typedef vector<int> vi; //? typedef vector<point> vp; //? template<class T> void chmin(T &t, T f) { if (t > f) t = f; } //change min template<class T> void chmax(T &t, T f) { if (t < f) t = f; } //change max #define UN(v) SORT(v),v.erase(unique(v.begin(),v.end()),v.end()) #define SORT(c) sort((c).begin(),(c).end()) #define FOR(i,a,b) for (int i=(a); i < (b); i++) #define REP(i,n) FOR(i,0,n) #define CL(a,b) memset(a,b,sizeof(a)) #define CL2d(a,b,x,y) memset(a, b, sizeof(a[0][0])*x*y) /*global variables*/ bool first_time = true; const double PI = acos(-1.0); int n; /*global variables*/ void dump() { //dump data } bool getInput() { //get input if (scanf("%d\n", &n) == EOF) return false; if (!first_time) printf("\n"); else first_time = false; return true; } bool in_circle(const point& x, double radius) { double y = (x.first*x.first + x.second*x.second); if (y < (radius*radius)) { debug(y, TAB); debug(radius, endl); } return y <= (radius*radius); } void process() { //process input //int t = (int)ceil(((2*n-1)*(2*n-1))/4*PI)/4; double r = (double)(2*n-1)/2; int in = 0, out = 0; point x; REP(i, n) { REP(j, n) { x.first = i; x.second = j; //top left if (in_circle(x, r)) { debug("contained segment", endl); out++; x.first = i+1; x.second = j+1; //bottom right if (in_circle(x, r)) { debug("fully in", endl); in++; out--; } } } } printf("In the case n = %d, %d cells contain segments of the circle.\n", n, out*4); printf("There are %d cells completely contained in the circle.\n", in*4); } int main() { while (getInput()) { process(); /*output*/ /*output*/ } return 0; }
mgavin/acm-code
uva/code/356_pegsnholes.cpp
C++
lgpl-3.0
2,379
class WeavingType < ActiveRecord::Base acts_as_content_block :belongs_to_attachment => true has_many :weavings belongs_to :user validates_presence_of :name validates_uniqueness_of :name end
agiletoolkit/bcms_mano_weavings
app/models/weaving_type.rb
Ruby
lgpl-3.0
200
/** * DynamicReports - Free Java reporting library for creating reports dynamically * * Copyright (C) 2010 - 2012 Ricardo Mariaca * http://dynamicreports.sourceforge.net * * This file is part of DynamicReports. * * DynamicReports 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. * * DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.dynamicreports.examples.complex.applicationform; /** * @author Ricardo Mariaca (dynamicreports@gmail.com) */ public enum MaritalStatus { SINGLE, MARRIED, DIVORCED }
robcowell/dynamicreports
dynamicreports-examples/src/main/java/net/sf/dynamicreports/examples/complex/applicationform/MaritalStatus.java
Java
lgpl-3.0
1,083
<?php if (file_exists('../libcompactmvc.php')) include_once ('../libcompactmvc.php'); LIBCOMPACTMVC_ENTRY; /** * Mutex * * @author Botho Hohbaum <bhohbaum@googlemail.com> * @package LibCompactMVC * @copyright Copyright (c) Botho Hohbaum * @license BSD License (see LICENSE file in root directory) * @link https://github.com/bhohbaum/LibCompactMVC */ class Mutex { private $key; private $token; private $delay; private $maxwait; public function __construct($key) { $this->key = $key; $this->token = md5(microtime() . rand(0, 99999999)); $this->delay = 2; $this->register(); } public function __destruct() { $this->unregister(); } public function lock($maxwait = 60) { echo ("Lock\n"); $start = time(); $this->maxwait = $maxwait; while (time() < $start + $maxwait) { if (count($this->get_requests()) == 0) { $this->set_request(); // usleep($this->delay * 5000); if (count($this->get_requests()) == 1) { if (count($this->get_acks()) + 1 == count($this->get_registrations())) { return; } } } if (count($this->get_requests()) == 1) { if (!$this->is_ack_set() && !$this->is_request_set()) { $this->set_ack(); } } if (count($this->get_requests()) > 1) { echo ("Increasing delay: " . $this->delay . "\n"); $this->delay += 1; } $this->unlock(); usleep(rand(0, $this->delay * 500)); } throw new MutexException("max wait time elapsed", 500); } public function unlock() { echo ("UnLock\n"); foreach ($this->get_acks() as $ack) { echo ("Deleting " . $ack . "\n"); RedisAdapter::get_instance()->delete($ack, false); } foreach ($this->get_requests() as $request) { echo ("Deleting " . $request . "\n"); RedisAdapter::get_instance()->delete($request, false); } } private function register() { echo ("Registering " . REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token, 1, false); RedisAdapter::get_instance()->expire(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $elem->token, $this->maxwait); } private function unregister() { echo ("Unregistering " . REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token, false); } private function get_registrations() { return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_*", false); } private function set_request() { echo ("Setting request " . REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false); } private function del_request() { echo ("Deleting request " . REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false); } private function get_requests() { return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_*", false); } private function is_request_set() { return (RedisAdapter::get_instance()->get(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false) != null); } private function set_ack() { echo ("Set ACK " . REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false); } private function del_ack() { echo ("Del ACK " . REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token . "\n"); RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false); } private function get_acks() { return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_*", false); } private function is_ack_set() { return (RedisAdapter::get_instance()->get(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false) != null); } }
bhohbaum/libcompactmvc
include/libcompactmvc/mutex.php
PHP
lgpl-3.0
4,191
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Copyright (c) 2015-2020 The plumed team (see the PEOPLE file at the root of the distribution for a list of names) See http://www.plumed.org for more information. This file is part of plumed, version 2. plumed 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. plumed 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 plumed. If not, see <http://www.gnu.org/licenses/>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #include "core/ActionAtomistic.h" #include "core/ActionPilot.h" #include "core/ActionRegister.h" #include "tools/File.h" #include "core/PlumedMain.h" #include "core/Atoms.h" namespace PLMD { namespace generic { //+PLUMEDOC PRINTANALYSIS DUMPMASSCHARGE /* Dump masses and charges on a selected file. This command dumps a file containing charges and masses. It does so only once in the simulation (at first step). File can be recycled in the \ref driver tool. Notice that masses and charges are only written once at the beginning of the simulation. In case no atom list is provided, charges and masses for all atoms are written. \par Examples You can add the DUMPMASSCHARGE action at the end of the plumed.dat file that you use during an MD simulations: \plumedfile c1: COM ATOMS=1-10 c2: COM ATOMS=11-20 DUMPATOMS ATOMS=c1,c2 FILE=coms.xyz STRIDE=100 DUMPMASSCHARGE FILE=mcfile \endplumedfile In this way, you will be able to use the same masses while processing a trajectory from the \ref driver . To do so, you need to add the --mc flag on the driver command line, e.g. \verbatim plumed driver --mc mcfile --plumed plumed.dat --ixyz traj.xyz \endverbatim With the following input you can dump only the charges for a specific group. \plumedfile solute_ions: GROUP ATOMS=1-121,200-2012 DUMPATOMS FILE=traj.gro ATOMS=solute_ions STRIDE=100 DUMPMASSCHARGE FILE=mcfile ATOMS=solute_ions \endplumedfile Notice however that if you want to process the charges with the driver (e.g. reading traj.gro) you have to fix atom numbers first, e.g. with the script \verbatim awk 'BEGIN{c=0}{ if(match($0,"#")) print ; else {print c,$2,$3; c++} }' < mc > newmc }' \endverbatim then \verbatim plumed driver --mc newmc --plumed plumed.dat --ixyz traj.gro \endverbatim */ //+ENDPLUMEDOC class DumpMassCharge: public ActionAtomistic, public ActionPilot { std::string file; bool first; bool second; bool print_masses; bool print_charges; public: explicit DumpMassCharge(const ActionOptions&); ~DumpMassCharge(); static void registerKeywords( Keywords& keys ); void prepare() override; void calculate() override {} void apply() override {} void update() override; }; PLUMED_REGISTER_ACTION(DumpMassCharge,"DUMPMASSCHARGE") void DumpMassCharge::registerKeywords( Keywords& keys ) { Action::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); ActionAtomistic::registerKeywords( keys ); keys.add("compulsory","STRIDE","1","the frequency with which the atoms should be output"); keys.add("atoms", "ATOMS", "the atom indices whose charges and masses you would like to print out"); keys.add("compulsory", "FILE", "file on which to output charges and masses."); keys.addFlag("ONLY_MASSES",false,"Only output masses to file"); keys.addFlag("ONLY_CHARGES",false,"Only output charges to file"); } DumpMassCharge::DumpMassCharge(const ActionOptions&ao): Action(ao), ActionAtomistic(ao), ActionPilot(ao), first(true), second(true), print_masses(true), print_charges(true) { std::vector<AtomNumber> atoms; parse("FILE",file); if(file.length()==0) error("name of output file was not specified"); log.printf(" output written to file %s\n",file.c_str()); parseAtomList("ATOMS",atoms); if(atoms.size()==0) { for(int i=0; i<plumed.getAtoms().getNatoms(); i++) { atoms.push_back(AtomNumber::index(i)); } } bool only_masses = false; parseFlag("ONLY_MASSES",only_masses); if(only_masses) { print_charges = false; log.printf(" only masses will be written to file\n"); } bool only_charges = false; parseFlag("ONLY_CHARGES",only_charges); if(only_charges) { print_masses = false; log.printf(" only charges will be written to file\n"); } checkRead(); log.printf(" printing the following atoms:" ); for(unsigned i=0; i<atoms.size(); ++i) log.printf(" %d",atoms[i].serial() ); log.printf("\n"); requestAtoms(atoms); if(only_masses && only_charges) { plumed_merror("using both ONLY_MASSES and ONLY_CHARGES doesn't make sense"); } } void DumpMassCharge::prepare() { if(!first && second) { requestAtoms(std::vector<AtomNumber>()); second=false; } } void DumpMassCharge::update() { if(!first) return; first=false; OFile of; of.link(*this); of.open(file); for(unsigned i=0; i<getNumberOfAtoms(); i++) { int ii=getAbsoluteIndex(i).index(); of.printField("index",ii); if(print_masses) {of.printField("mass",getMass(i));} if(print_charges) {of.printField("charge",getCharge(i));} of.printField(); } } DumpMassCharge::~DumpMassCharge() { } } }
PabloPiaggi/plumed2
src/generic/DumpMassCharge.cpp
C++
lgpl-3.0
5,635
// // Copyright 2012 Josh Blum // // This program 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. // // 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef INCLUDED_LIBTSBE_ELEMENT_IMPL_HPP #define INCLUDED_LIBTSBE_ELEMENT_IMPL_HPP #include <tsbe/thread_pool.hpp> #include <tsbe_impl/common_impl.hpp> #include <vector> #include <queue> #include <iostream> namespace tsbe { //! ElementImpl is both a topology and a block to allow interconnection struct ElementImpl { ElementImpl(void) { //NOP } ~ElementImpl(void) { this->actor.reset(); } bool block; bool is_block(void) { return block; } boost::shared_ptr<Actor> actor; boost::shared_ptr<Theron::Framework> framework; ThreadPool thread_pool; }; } //namespace tsbe #endif /*INCLUDED_LIBTSBE_ELEMENT_IMPL_HPP*/
guruofquality/tsbe
lib/tsbe_impl/element_impl.hpp
C++
lgpl-3.0
1,398
package org.molgenis.lifelines.catalog; import nl.umcg.hl7.service.studydefinition.POQMMT000002UVObservation; import org.molgenis.omx.catalogmanager.OmxCatalogFolder; import org.molgenis.omx.observ.Protocol; public class PoqmObservationCatalogItem extends OmxCatalogFolder { private final POQMMT000002UVObservation observation; public PoqmObservationCatalogItem(POQMMT000002UVObservation observation, Protocol protocol) { super(protocol); if (observation == null) throw new IllegalArgumentException("observation is null"); this.observation = observation; } @Override public String getName() { return observation.getCode().getDisplayName(); } @Override public String getDescription() { return observation.getCode().getOriginalText().getContent().toString(); } @Override public String getCode() { return observation.getCode().getCode(); } @Override public String getCodeSystem() { return observation.getCode().getCodeSystem(); } }
dennishendriksen/molgenis-lifelines
src/main/java/org/molgenis/lifelines/catalog/PoqmObservationCatalogItem.java
Java
lgpl-3.0
972
/* * SonarQube Lua Plugin * Copyright (C) 2016 * mailto:fati.ahmadi AT gmail DOT com * * This program 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.lua.checks; import org.junit.Test; import org.sonar.lua.LuaAstScanner; import org.sonar.squidbridge.api.SourceFile; import org.sonar.squidbridge.checks.CheckMessagesVerifier; import org.sonar.squidbridge.api.SourceFunction; import java.io.File; public class TableComplexityCheckTest { @Test public void test() { TableComplexityCheck check = new TableComplexityCheck(); check.setMaximumTableComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/tableComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("Table has a complexity of 1 which is greater than 0 authorized.") .noMore(); } }
SonarQubeCommunity/sonar-lua
lua-checks/src/test/java/org/sonar/lua/checks/TableComplexityCheckTest.java
Java
lgpl-3.0
1,600
#!/usr/bin/python # -*- coding: utf-8 -*- "Visual Property Editor (using wx PropertyGrid) of gui2py's components" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2013- Mariano Reingart" __license__ = "LGPL 3.0" # some parts where inspired or borrowed from wxFormBuilders & wxPython examples import sys, time, math, os, os.path import wx _ = wx.GetTranslation import wx.propgrid as wxpg from gui.component import InitSpec, StyleSpec, Spec, EventSpec, DimensionSpec from gui.font import Font DEBUG = False class PropertyEditorPanel(wx.Panel): def __init__( self, parent, log ): wx.Panel.__init__(self, parent, wx.ID_ANY) self.log = log self.callback = None self.panel = panel = wx.Panel(self, wx.ID_ANY) topsizer = wx.BoxSizer(wx.VERTICAL) # Difference between using PropertyGridManager vs PropertyGrid is that # the manager supports multiple pages and a description box. self.pg = pg = wxpg.PropertyGrid(panel, style=wxpg.PG_SPLITTER_AUTO_CENTER | wxpg.PG_AUTO_SORT | wxpg.PG_TOOLBAR) # Show help as tooltips pg.SetExtraStyle(wxpg.PG_EX_HELP_AS_TOOLTIPS) pg.Bind( wxpg.EVT_PG_CHANGED, self.OnPropGridChange ) pg.Bind( wxpg.EVT_PG_PAGE_CHANGED, self.OnPropGridPageChange ) pg.Bind( wxpg.EVT_PG_SELECTED, self.OnPropGridSelect ) pg.Bind( wxpg.EVT_PG_RIGHT_CLICK, self.OnPropGridRightClick ) ##pg.AddPage( "Page 1 - Testing All" ) # store the property grid for future reference self.pg = pg # load empty object (just draws categories) self.load_object(None) # sizing stuff: topsizer.Add(pg, 1, wx.EXPAND) panel.SetSizer(topsizer) topsizer.SetSizeHints(panel) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(panel, 1, wx.EXPAND) self.SetSizer(sizer) self.SetAutoLayout(True) def load_object(self, obj, callback=None): pg = self.pg # get the property grid reference self.callback = callback # store the update method # delete all properties pg.Clear() # clean references and aux structures appended = set() self.obj = obj self.groups = {} # loop on specs and append each property (categorized): for i, cat, class_ in ((1, 'Init Specs', InitSpec), (2, 'Dimension Specs', DimensionSpec), (3, 'Style Specs', StyleSpec), (5, 'Events', EventSpec), (4, 'Basic Specs', Spec), ): pg.Append(wxpg.PropertyCategory("%s - %s" % (i, cat))) if obj is None: continue specs = sorted(obj._meta.specs.items(), key=lambda it: it[0]) for name, spec in specs: if DEBUG: print "setting prop", spec, class_, spec.type if isinstance(spec, class_): prop = {'string': wxpg.StringProperty, 'integer': wxpg.IntProperty, 'float': wxpg.FloatProperty, 'boolean': wxpg.BoolProperty, 'text': wxpg.LongStringProperty, 'code': wxpg.LongStringProperty, 'enum': wxpg.EnumProperty, 'edit_enum': wxpg.EditEnumProperty, 'expr': wxpg.StringProperty, 'array': wxpg.ArrayStringProperty, 'font': wxpg.FontProperty, 'image_file': wxpg.ImageFileProperty, 'colour': wxpg.ColourProperty}.get(spec.type) if prop and name not in appended: value = getattr(obj, name) if DEBUG: print "name", name, value if spec.type == "code" and value is None: value = "" if spec.type == "boolean" and value is None: value = False if spec.type == "integer" and value is None: value = -1 if spec.type in ("string", "text") and value is None: value = "" if spec.type == "expr": value = repr(value) if spec.type == "font": if value is None: value = wx.NullFont else: value = value.get_wx_font() if callable(value): # event binded at runtime cannot be modified: value = str(value) readonly = True else: readonly = False if spec.type == "enum": prop = prop(name, name, spec.mapping.keys(), spec.mapping.values(), value=spec.mapping.get(value, 0)) elif spec.type == "edit_enum": prop = prop(name, name, spec.mapping.keys(), range(len(spec.mapping.values())), value=spec.mapping[value]) else: try: prop = prop(name, value=value) except Exception, e: print "CANNOT LOAD PROPERTY", name, value, e prop.SetPyClientData(spec) appended.add(name) if spec.group is None: pg.Append(prop) if readonly: pg.SetPropertyReadOnly(prop) else: # create a group hierachy (wxpg uses dot notation) group = "" prop_parent = None for grp in spec.group.split("."): prev_group = group # ancestor group += ("." if group else "") + grp # path if group in self.groups: prop_parent = self.groups[group] else: prop_group = wxpg.StringProperty(grp, value="<composed>") if not prop_parent: pg.Append(prop_group) else: pg.AppendIn(prev_group, prop_group) prop_parent = prop_group self.groups[group] = prop_parent pg.SetPropertyReadOnly(group) pg.AppendIn(spec.group, prop) pg.Collapse(spec.group) name = spec.group + "." + name if spec.type == "boolean": pg.SetPropertyAttribute(name, "UseCheckbox", True) doc = spec.__doc__ if doc: pg.SetPropertyHelpString(name, doc) def edit(self, name=""): "Programatically select a (default) property to start editing it" # for more info see DoSelectAndEdit in propgrid.cpp for name in (name, "label", "value", "text", "title", "filename", "name"): prop = self.pg.GetPropertyByName(name) if prop is not None: break self.Parent.SetFocus() self.Parent.Raise() self.pg.SetFocus() # give time to the ui to show the prop grid and set focus: wx.CallLater(250, self.select, prop.GetName()) def select(self, name, flags=0): "Select a property (and start the editor)" # do not call this directly from another window, use edit() instead # // wxPropertyGrid::DoSelectProperty flags (selFlags) -see propgrid.h- wxPG_SEL_FOCUS=0x0001 # Focuses to created editor wxPG_SEL_FORCE=0x0002 # Forces deletion and recreation of editor flags |= wxPG_SEL_FOCUS # | wxPG_SEL_FORCE prop = self.pg.GetPropertyByName(name) self.pg.SelectProperty(prop, flags) if DEBUG: print "selected!", prop def OnPropGridChange(self, event): p = event.GetProperty() if DEBUG: print "change!", p if p: name = p.GetName() spec = p.GetPyClientData() if spec and 'enum' in spec.type: value = p.GetValueAsString() else: value = p.GetValue() #self.log.write(u'%s changed to "%s"\n' % (p,p.GetValueAsString())) # if it a property child (parent.child), extract its name if "." in name: name = name[name.rindex(".") + 1:] if spec and not name in self.groups: if name == 'font': # TODO: detect property type # create a gui font from the wx.Font font = Font() font.set_wx_font(value) value = font # expressions must be evaluated to store the python object if spec.type == "expr": value = eval(value) # re-create the wx_object with the new property value # (this is required at least to apply new styles and init specs) if DEBUG: print "changed", self.obj.name kwargs = {str(name): value} wx.CallAfter(self.obj.rebuild, **kwargs) if name == 'name': wx.CallAfter(self.callback, **dict(name=self.obj.name)) def OnPropGridSelect(self, event): p = event.GetProperty() if p: self.log.write(u'%s selected\n' % (event.GetProperty().GetName())) else: self.log.write(u'Nothing selected\n') def OnDeleteProperty(self, event): p = self.pg.GetSelectedProperty() if p: self.pg.DeleteProperty(p) else: wx.MessageBox("First select a property to delete") def OnReserved(self, event): pass def OnPropGridRightClick(self, event): p = event.GetProperty() if p: self.log.write(u'%s right clicked\n' % (event.GetProperty().GetName())) else: self.log.write(u'Nothing right clicked\n') #self.obj.get_parent().Refresh() def OnPropGridPageChange(self, event): index = self.pg.GetSelectedPage() self.log.write('Page Changed to \'%s\'\n' % (self.pg.GetPageName(index))) if __name__ == '__main__': import sys,os app = wx.App() f = wx.Frame(None) from gui.controls import Button, Label, TextBox, CheckBox, ListBox, ComboBox frame = wx.Frame(None) #o = Button(frame, name="btnTest", label="click me!", default=True) #o = Label(frame, name="lblTest", alignment="right", size=(-1, 500), text="hello!") o = TextBox(frame, name="txtTest", border=False, text="hello world!") #o = CheckBox(frame, name="chkTest", border='none', label="Check me!") #o = ListBox(frame, name="lstTest", border='none', # items={'datum1': 'a', 'datum2':'b', 'datum3':'c'}, # multiselect="--multiselect" in sys.argv) #o = ComboBox(frame, name="cboTest", # items={'datum1': 'a', 'datum2':'b', 'datum3':'c'}, # readonly='--readonly' in sys.argv, # ) frame.Show() log = sys.stdout w = PropertyEditorPanel(f, log) w.load_object(o) f.Show() app.MainLoop()
reingart/gui2py
gui/tools/propeditor.py
Python
lgpl-3.0
12,658
#!/usr/bin/python3 import sys from pathlib import Path list_scope_path = Path("./list_scope_tokens.txt") keyword_bit = 13 list_scope_bit = 14 def main(): if len(sys.argv) < 2: print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr) return 1 list_scopes = set() with list_scope_path.open('r') as f: for line in f: line = line.strip() if line.startswith('#') or len(line) == 0: continue list_scopes.add(line) max_kw_len = max( len(kw) for kw in list_scopes ) if sys.argv[1] == 'tokens': t_id = (1 << (keyword_bit - 1)) | (1 << (list_scope_bit-1)) for t in sorted(list_scopes): print(' {:<{width}} = 0x{:4X};'.format(t.upper(), t_id, width=max_kw_len)) t_id += 1 elif sys.argv[1] == 'emitters': for t in sorted(list_scopes): print(' {:<{width}} => T_{}(Lexeme);'.format('"' + t + '"', t.upper(), width = max_kw_len + 2)) else: print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr) return 1 return 0 if __name__ == '__main__': sys.exit(main())
zijistark/zckTools
src/zck/token_codegen.py
Python
lgpl-3.0
1,078
package com.faralot.core.ui.fragments; import android.app.Activity; import android.app.AlertDialog.Builder; import android.app.Fragment; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.provider.MediaStore.Images.Media; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import com.faralot.core.App; import com.faralot.core.R; import com.faralot.core.R.drawable; import com.faralot.core.R.id; import com.faralot.core.R.layout; import com.faralot.core.R.string; import com.faralot.core.lib.LocalizationSystem; import com.faralot.core.lib.LocalizationSystem.Listener; import com.faralot.core.rest.model.Location; import com.faralot.core.rest.model.location.Coord; import com.faralot.core.ui.holder.LocalizationHolder; import com.faralot.core.utils.Dimension; import com.faralot.core.utils.Localization; import com.faralot.core.utils.Util; import com.orhanobut.dialogplus.DialogPlus; import com.orhanobut.dialogplus.OnItemClickListener; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.RequestBody; import org.osmdroid.bonuspack.overlays.InfoWindow; import org.osmdroid.bonuspack.overlays.MapEventsOverlay; import org.osmdroid.bonuspack.overlays.MapEventsReceiver; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.ItemizedIconOverlay; import org.osmdroid.views.overlay.OverlayItem; import java.io.File; import java.util.ArrayList; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; public class LocationAddSelectFragment extends Fragment { protected MapView mapView; protected TextView latitude; protected ProgressBar latitudeProgress; protected TextView longitude; protected ProgressBar longitudeProgress; protected ImageButton submit; private boolean forceZoom; public LocationAddSelectFragment() { } @Override public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(layout.fragment_location_add_select, container, false); initElements(view); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(getString(string.find_coordinates)); } onChoose(); return view; } private void initElements(View view) { mapView = (MapView) view.findViewById(id.map); latitude = (TextView) view.findViewById(id.result_lat); latitudeProgress = (ProgressBar) view.findViewById(id.progress_latitude); longitude = (TextView) view.findViewById(id.result_lon); longitudeProgress = (ProgressBar) view.findViewById(id.progress_longitude); Button back = (Button) view.findViewById(id.back); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearResultLayout(); onChoose(); onChoose(); } }); submit = (ImageButton) view.findViewById(id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onSubmit(); } }); } private void generateContent(float lat, float lon) { GeoPoint actPosition = new GeoPoint((double) lat, (double) lon); Util.setMapViewSettings(mapView, actPosition, forceZoom); ArrayList<OverlayItem> locations = new ArrayList<>(1); OverlayItem actPositionItem = new OverlayItem(getString(string.here), getString(string.my_position), actPosition); actPositionItem.setMarker(Util.resizeDrawable(getResources() .getDrawable(drawable.ic_marker_dark), getResources(), new Dimension(45, 45))); locations.add(actPositionItem); // Bonuspack MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(getActivity(), new MapEventsReceiver() { @Override public boolean singleTapConfirmedHelper(GeoPoint geoPoint) { InfoWindow.closeAllInfoWindowsOn(mapView); return true; } @Override public boolean longPressHelper(GeoPoint geoPoint) { InfoWindow.closeAllInfoWindowsOn(mapView); setResultLayout((float) geoPoint.getLatitude(), (float) geoPoint .getLongitude()); return true; } }); mapView.getOverlays().add(0, mapEventsOverlay); mapView.getOverlays().add(new ItemizedIconOverlay<>(getActivity(), locations, null)); } protected final void onChoose() { clearResultLayout(); forceZoom = true; ArrayList<Localization> localizations = new ArrayList<>(4); localizations.add(new Localization(drawable.ic_gps_dark, getString(string.gps_coordinates), Localization.GPS)); localizations.add(new Localization(drawable.ic_camera_dark, getString(string.coord_photo_exif), Localization.PIC_COORD)); localizations.add(new Localization(drawable.ic_manual_dark, getString(string.add_manual), Localization.MANUAL)); if (App.palsActive) { localizations.add(new Localization(drawable.ic_pals_dark, getString(string.pals_provider), Localization.PALS)); } DialogPlus dialog = DialogPlus.newDialog(getActivity()) .setAdapter(new LocalizationHolder(getActivity(), localizations)) .setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(DialogPlus dialog, Object item, View view, int position) { Listener listener = new Listener() { @Override public void onComplete(Coord coord, boolean valid) { if (valid) { setResultLayout(coord.getLatitude(), coord.getLongitude()); } } }; dialog.dismiss(); if (position == 0) { App.localization.getCoords(LocalizationSystem.GPS, listener); } else if (position == 1) { searchExif(); } else if (position == 2) { searchManual(); } else if (position == 3) { App.localization.getCoords(LocalizationSystem.PALS, listener); } } }) .setContentWidth(LayoutParams.WRAP_CONTENT) .setContentHeight(LayoutParams.WRAP_CONTENT) .create(); dialog.show(); } void searchManual() { Builder alertDialog = new Builder(getActivity()); final View layout = getActivity().getLayoutInflater() .inflate(R.layout.dialog_location_add_manual, null); alertDialog.setView(layout); alertDialog.setPositiveButton(getString(string.confirm), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText latitude = (EditText) layout.findViewById(id.latitude); EditText longitude = (EditText) layout.findViewById(id.longitude); setResultLayout(Float.parseFloat(latitude.getText() .toString()), Float.parseFloat(longitude.getText().toString())); } }); alertDialog.show(); } void searchExif() { Intent intent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, 0); } void setResultLayout(float lat, float lon) { if (lat != 0 && lon != 0) { submit.setVisibility(View.VISIBLE); } latitudeProgress.setVisibility(View.GONE); latitude.setText(String.valueOf(lat)); longitudeProgress.setVisibility(View.GONE); longitude.setText(String.valueOf(lon)); generateContent(lat, lon); forceZoom = false; } private void clearResultLayout() { submit.setVisibility(View.GONE); latitudeProgress.setVisibility(View.VISIBLE); latitudeProgress.setIndeterminate(true); latitude.setText(null); longitudeProgress.setVisibility(View.VISIBLE); longitudeProgress.setIndeterminate(true); longitude.setText(null); } protected final void onSubmit() { float lat = Float.parseFloat(latitude.getText().toString()); float lon = Float.parseFloat(longitude.getText().toString()); if (lat != 0 && lon != 0) { Fragment fragment = new LocationAddFragment(); Bundle bundle = new Bundle(); bundle.putFloat(Location.GEOLOCATION_COORD_LATITUDE, lat); bundle.putFloat(Location.GEOLOCATION_COORD_LONGITUDE, lon); fragment.setArguments(bundle); Util.changeFragment(null, fragment, id.frame_container, getActivity(), null); } else { Util.getMessageDialog(getString(string.no_valid_coords), getActivity()); } } /** * Bild wird ausgesucht und uebergeben */ @Override public final void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 0 && resultCode == Activity.RESULT_OK) { String path = Util.getPathFromCamera(data, getActivity()); if (path != null) { RequestBody typedFile = RequestBody.create(MediaType.parse("image/*"), new File(path)); App.rest.location.getLocationByExif(typedFile).enqueue(new Callback<Coord>() { @Override public void onResponse(Response<Coord> response, Retrofit retrofit) { if (response.isSuccess()) { setResultLayout(response.body().getLatitude(), response .body() .getLongitude()); } else { setResultLayout(0, 0); } } @Override public void onFailure(Throwable t) { Util.getMessageDialog(t.getMessage(), getActivity()); } }); } } } }
bestog/faralot-core
app/src/main/java/com/faralot/core/ui/fragments/LocationAddSelectFragment.java
Java
lgpl-3.0
9,954
module RailsLog class MailerSubscriber < ActiveSupport::LogSubscriber def record(event) payload = event.payload log_mailer = Logged::LogMailer.new(message_object_id: payload[:message_object_id], mailer: payload[:mailer]) log_mailer.action_name = payload[:action_name] log_mailer.params = payload[:params] log_mailer.save info 'mailer log saved!' end def deliver(event) payload = event.payload log_mailer = Logged::LogMailer.find_or_initialize_by(message_object_id: payload[:message_object_id], mailer: payload[:mailer]) log_mailer.subject = payload[:subject] log_mailer.sent_status = payload[:sent_status] log_mailer.sent_string = payload[:sent_string] log_mailer.mail_to = payload[:mail_to] log_mailer.cc_to = payload[:cc_to] log_mailer.save info 'mailer log updated!' end end end RailsLog::MailerSubscriber.attach_to :action_mailer
qinmingyuan/rails_log
lib/rails_log/mailer_subscriber.rb
Ruby
lgpl-3.0
952
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2016 Pelican Mapping * http://osgearth.org * * osgEarth 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <osgEarthFeatures/FeatureDisplayLayout> #include <limits> using namespace osgEarth; using namespace osgEarth::Features; using namespace osgEarth::Symbology; //------------------------------------------------------------------------ FeatureLevel::FeatureLevel( const Config& conf ) : _minRange( 0.0f ), _maxRange( FLT_MAX ) { fromConfig( conf ); } FeatureLevel::FeatureLevel( float minRange, float maxRange ) { _minRange = minRange; _maxRange = maxRange; } FeatureLevel::FeatureLevel( float minRange, float maxRange, const std::string& styleName ) { _minRange = minRange; _maxRange = maxRange; _styleName = styleName; } void FeatureLevel::fromConfig( const Config& conf ) { conf.getIfSet( "min_range", _minRange ); conf.getIfSet( "max_range", _maxRange ); conf.getIfSet( "style", _styleName ); conf.getIfSet( "class", _styleName ); // alias } Config FeatureLevel::getConfig() const { Config conf( "level" ); conf.addIfSet( "min_range", _minRange ); conf.addIfSet( "max_range", _maxRange ); conf.addIfSet( "style", _styleName ); return conf; } //------------------------------------------------------------------------ FeatureDisplayLayout::FeatureDisplayLayout( const Config& conf ) : _tileSizeFactor( 15.0f ), _minRange ( 0.0f ), _maxRange ( 0.0f ), _cropFeatures ( false ), _priorityOffset( 0.0f ), _priorityScale ( 1.0f ), _minExpiryTime ( 0.0f ) { fromConfig( conf ); } void FeatureDisplayLayout::fromConfig( const Config& conf ) { conf.getIfSet( "tile_size", _tileSize ); conf.getIfSet( "tile_size_factor", _tileSizeFactor ); conf.getIfSet( "crop_features", _cropFeatures ); conf.getIfSet( "priority_offset", _priorityOffset ); conf.getIfSet( "priority_scale", _priorityScale ); conf.getIfSet( "min_expiry_time", _minExpiryTime ); conf.getIfSet( "min_range", _minRange ); conf.getIfSet( "max_range", _maxRange ); ConfigSet children = conf.children( "level" ); for( ConfigSet::const_iterator i = children.begin(); i != children.end(); ++i ) addLevel( FeatureLevel( *i ) ); } Config FeatureDisplayLayout::getConfig() const { Config conf( "layout" ); conf.addIfSet( "tile_size", _tileSize ); conf.addIfSet( "tile_size_factor", _tileSizeFactor ); conf.addIfSet( "crop_features", _cropFeatures ); conf.addIfSet( "priority_offset", _priorityOffset ); conf.addIfSet( "priority_scale", _priorityScale ); conf.addIfSet( "min_expiry_time", _minExpiryTime ); conf.addIfSet( "min_range", _minRange ); conf.addIfSet( "max_range", _maxRange ); for( Levels::const_iterator i = _levels.begin(); i != _levels.end(); ++i ) conf.add( i->second.getConfig() ); return conf; } void FeatureDisplayLayout::addLevel( const FeatureLevel& level ) { _levels.insert( std::make_pair( -level.maxRange().get(), level ) ); } unsigned FeatureDisplayLayout::getNumLevels() const { return _levels.size(); } const FeatureLevel* FeatureDisplayLayout::getLevel( unsigned n ) const { unsigned i = 0; for( Levels::const_iterator k = _levels.begin(); k != _levels.end(); ++k ) { if ( n == i++ ) return &(k->second); } return 0L; } unsigned FeatureDisplayLayout::chooseLOD( const FeatureLevel& level, double fullExtentRadius ) const { double radius = fullExtentRadius; unsigned lod = 1; for( ; lod < 20; ++lod ) { radius *= 0.5; float lodMaxRange = radius * _tileSizeFactor.value(); if ( level.maxRange() >= lodMaxRange ) break; } return lod-1; }
ldelgass/osgearth
src/osgEarthFeatures/FeatureDisplayLayout.cpp
C++
lgpl-3.0
4,505
package de.riedquat.java.io; import de.riedquat.java.util.Arrays; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import static de.riedquat.java.io.Util.copy; import static de.riedquat.java.util.Arrays.EMPTY_BYTE_ARRAY; import static org.junit.Assert.assertArrayEquals; public class UtilTest { @Test public void emptyStream_copiesNothing() throws IOException { assertCopies(EMPTY_BYTE_ARRAY); } @Test public void copiesData() throws IOException { assertCopies(Arrays.createRandomByteArray(10001)); } private void assertCopies(final byte[] testData) throws IOException { final ByteArrayInputStream in = new ByteArrayInputStream(testData); final ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(out, in); assertArrayEquals(testData, out.toByteArray()); } }
christianhujer/japi
WebServer/test/de/riedquat/java/io/UtilTest.java
Java
lgpl-3.0
934
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2014 Pelican Mapping * http://osgearth.org * * osgEarth 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <string> #include <osg/Notify> #include <osg/Timer> #include <osg/ShapeDrawable> #include <osg/PositionAttitudeTransform> #include <osgGA/StateSetManipulator> #include <osgGA/GUIEventHandler> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgEarth/GeoMath> #include <osgEarth/GeoTransform> #include <osgEarth/MapNode> #include <osgEarth/TerrainEngineNode> #include <osgEarth/Viewpoint> #include <osgEarthUtil/EarthManipulator> #include <osgEarthUtil/AutoClipPlaneHandler> #include <osgEarthUtil/Controls> #include <osgEarthUtil/ExampleResources> #include <osgEarthAnnotation/AnnotationUtils> #include <osgEarthAnnotation/LabelNode> #include <osgEarthSymbology/Style> using namespace osgEarth::Util; using namespace osgEarth::Util::Controls; using namespace osgEarth::Annotation; #define D2R (osg::PI/180.0) #define R2D (180.0/osg::PI) namespace { /** * Builds our help menu UI. */ Control* createHelp( osgViewer::View* view ) { const char* text[] = { "left mouse :", "pan", "middle mouse :", "rotate", "right mouse :", "continuous zoom", "double-click :", "zoom to point", "scroll wheel :", "zoom in/out", "arrows :", "pan", "1-6 :", "fly to preset viewpoints", "shift-right-mouse :", "locked panning", "u :", "toggle azimuth lock", "c :", "toggle perspective/ortho", "t :", "toggle tethering", "a :", "toggle viewpoint arcing", "z :", "toggle throwing", "k :", "toggle collision" }; Grid* g = new Grid(); for( unsigned i=0; i<sizeof(text)/sizeof(text[0]); ++i ) { unsigned c = i % 2; unsigned r = i / 2; g->setControl( c, r, new LabelControl(text[i]) ); } VBox* v = new VBox(); v->addControl( g ); return v; } /** * Some preset viewpoints to show off the setViewpoint function. */ static Viewpoint VPs[] = { Viewpoint( "Africa", osg::Vec3d( 0.0, 0.0, 0.0 ), 0.0, -90.0, 10e6 ), Viewpoint( "California", osg::Vec3d( -121.0, 34.0, 0.0 ), 0.0, -90.0, 6e6 ), Viewpoint( "Europe", osg::Vec3d( 0.0, 45.0, 0.0 ), 0.0, -90.0, 4e6 ), Viewpoint( "Washington DC", osg::Vec3d( -77.0, 38.0, 0.0 ), 0.0, -90.0, 1e6 ), Viewpoint( "Australia", osg::Vec3d( 135.0, -20.0, 0.0 ), 0.0, -90.0, 2e6 ), Viewpoint( "Boston", osg::Vec3d( -71.096936, 42.332771, 0 ), 0.0, -90, 1e5 ) }; /** * Handler that demonstrates the "viewpoint" functionality in * osgEarthUtil::EarthManipulator. Press a number key to fly to a viewpoint. */ struct FlyToViewpointHandler : public osgGA::GUIEventHandler { FlyToViewpointHandler( EarthManipulator* manip ) : _manip(manip) { } bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { if ( ea.getEventType() == ea.KEYDOWN && ea.getKey() >= '1' && ea.getKey() <= '6' ) { _manip->setViewpoint( VPs[ea.getKey()-'1'], 4.0 ); aa.requestRedraw(); } return false; } osg::observer_ptr<EarthManipulator> _manip; }; /** * Handler to toggle "azimuth locking", which locks the camera's relative Azimuth * while panning. For example, it can maintain "north-up" as you pan around. The * caveat is that when azimuth is locked you cannot cross the poles. */ struct LockAzimuthHandler : public osgGA::GUIEventHandler { LockAzimuthHandler(char key, EarthManipulator* manip) : _key(key), _manip(manip) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key) { bool lockAzimuth = _manip->getSettings()->getLockAzimuthWhilePanning(); _manip->getSettings()->setLockAzimuthWhilePanning(!lockAzimuth); aa.requestRedraw(); return true; } return false; } void getUsage(osg::ApplicationUsage& usage) const { using namespace std; usage.addKeyboardMouseBinding(string(1, _key), string("Toggle azimuth locking")); } char _key; osg::ref_ptr<EarthManipulator> _manip; }; /** * Handler to toggle "viewpoint transtion arcing", which causes the camera to "arc" * as it travels from one viewpoint to another. */ struct ToggleArcViewpointTransitionsHandler : public osgGA::GUIEventHandler { ToggleArcViewpointTransitionsHandler(char key, EarthManipulator* manip) : _key(key), _manip(manip) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key) { bool arc = _manip->getSettings()->getArcViewpointTransitions(); _manip->getSettings()->setArcViewpointTransitions(!arc); aa.requestRedraw(); return true; } return false; } void getUsage(osg::ApplicationUsage& usage) const { using namespace std; usage.addKeyboardMouseBinding(string(1, _key), string("Arc viewpoint transitions")); } char _key; osg::ref_ptr<EarthManipulator> _manip; }; /** * Toggles the projection matrix between perspective and orthographic. */ struct ToggleProjectionHandler : public osgGA::GUIEventHandler { ToggleProjectionHandler(char key, EarthManipulator* manip) : _key(key), _manip(manip) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key) { if ( _manip->getSettings()->getCameraProjection() == EarthManipulator::PROJ_PERSPECTIVE ) _manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_ORTHOGRAPHIC ); else _manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_PERSPECTIVE ); aa.requestRedraw(); return true; } return false; } void getUsage(osg::ApplicationUsage& usage) const { using namespace std; usage.addKeyboardMouseBinding(string(1, _key), string("Toggle projection type")); } char _key; osg::ref_ptr<EarthManipulator> _manip; }; /** * Toggles the throwing feature. */ struct ToggleThrowingHandler : public osgGA::GUIEventHandler { ToggleThrowingHandler(char key, EarthManipulator* manip) : _key(key), _manip(manip) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key) { bool throwing = _manip->getSettings()->getThrowingEnabled(); _manip->getSettings()->setThrowingEnabled( !throwing ); aa.requestRedraw(); return true; } return false; } void getUsage(osg::ApplicationUsage& usage) const { using namespace std; usage.addKeyboardMouseBinding(string(1, _key), string("Toggle throwing")); } char _key; osg::ref_ptr<EarthManipulator> _manip; }; /** * Toggles the collision feature. */ struct ToggleCollisionHandler : public osgGA::GUIEventHandler { ToggleCollisionHandler(char key, EarthManipulator* manip) : _key(key), _manip(manip) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key) { bool collision = _manip->getSettings()->getDisableCollisionAvoidance(); _manip->getSettings()->setDisableCollisionAvoidance( !collision ); aa.requestRedraw(); return true; } return false; } void getUsage(osg::ApplicationUsage& usage) const { using namespace std; usage.addKeyboardMouseBinding(string(1, _key), string("Toggle collision avoidance")); } char _key; osg::ref_ptr<EarthManipulator> _manip; }; /** * A simple simulator that moves an object around the Earth. We use this to * demonstrate/test tethering. */ struct Simulator : public osgGA::GUIEventHandler { Simulator( osg::Group* root, EarthManipulator* manip, MapNode* mapnode, osg::Node* model) : _manip(manip), _mapnode(mapnode), _model(model), _lat0(55.0), _lon0(45.0), _lat1(-55.0), _lon1(-45.0) { if ( !model ) { _model = AnnotationUtils::createSphere( 250.0, osg::Vec4(1,.7,.4,1) ); } _xform = new GeoTransform(); _xform->setTerrain(mapnode->getTerrain()); _pat = new osg::PositionAttitudeTransform(); _pat->addChild( _model ); _xform->addChild( _pat ); _cam = new osg::Camera(); _cam->setRenderOrder( osg::Camera::NESTED_RENDER, 1 ); _cam->addChild( _xform ); Style style; style.getOrCreate<TextSymbol>()->size() = 32.0f; style.getOrCreate<TextSymbol>()->declutter() = false; _label = new LabelNode(_mapnode, GeoPoint(), "Hello World", style); _label->setDynamic( true ); _cam->addChild( _label ); root->addChild( _cam.get() ); } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { if ( ea.getEventType() == ea.FRAME ) { double t = fmod( osg::Timer::instance()->time_s(), 600.0 ) / 600.0; double lat, lon; GeoMath::interpolate( D2R*_lat0, D2R*_lon0, D2R*_lat1, D2R*_lon1, t, lat, lon ); GeoPoint p( SpatialReference::create("wgs84"), R2D*lon, R2D*lat, 2500.0 ); double bearing = GeoMath::bearing(D2R*_lat1, D2R*_lon1, lat, lon); _xform->setPosition( p ); _pat->setAttitude(osg::Quat(bearing, osg::Vec3d(0,0,1))); _label->setPosition( p ); } else if ( ea.getEventType() == ea.KEYDOWN && ea.getKey() == 't' ) { _manip->getSettings()->setTetherMode(osgEarth::Util::EarthManipulator::TETHER_CENTER_AND_HEADING); _manip->setTetherNode( _manip->getTetherNode() ? 0L : _xform.get(), 2.0 ); Viewpoint vp = _manip->getViewpoint(); vp.setRange(5000); _manip->setViewpoint(vp); return true; } return false; } MapNode* _mapnode; EarthManipulator* _manip; osg::ref_ptr<osg::Camera> _cam; osg::ref_ptr<GeoTransform> _xform; osg::ref_ptr<osg::PositionAttitudeTransform> _pat; double _lat0, _lon0, _lat1, _lon1; LabelNode* _label; osg::Node* _model; }; } int main(int argc, char** argv) { osg::ArgumentParser arguments(&argc,argv); if (arguments.read("--help") || argc==1) { OE_WARN << "Usage: " << argv[0] << " [earthFile] [--model modelToLoad]" << std::endl; return 0; } osgViewer::Viewer viewer(arguments); // install the programmable manipulator. EarthManipulator* manip = new EarthManipulator(); viewer.setCameraManipulator( manip ); // UI: Control* help = createHelp(&viewer); osg::Node* earthNode = MapNodeHelper().load( arguments, &viewer, help ); if (!earthNode) { OE_WARN << "Unable to load earth model." << std::endl; return -1; } osg::Group* root = new osg::Group(); root->addChild( earthNode ); osgEarth::MapNode* mapNode = osgEarth::MapNode::findMapNode( earthNode ); if ( mapNode ) { if ( mapNode ) manip->setNode( mapNode->getTerrainEngine() ); if ( mapNode->getMap()->isGeocentric() ) { manip->setHomeViewpoint( Viewpoint( osg::Vec3d( -90, 0, 0 ), 0.0, -90.0, 5e7 ) ); } } // user model? osg::Node* model = 0L; std::string modelFile; if (arguments.read("--model", modelFile)) model = osgDB::readNodeFile(modelFile); // Simulator for tethering: viewer.addEventHandler( new Simulator(root, manip, mapNode, model) ); manip->getSettings()->getBreakTetherActions().push_back( EarthManipulator::ACTION_PAN ); manip->getSettings()->getBreakTetherActions().push_back( EarthManipulator::ACTION_GOTO ); // Set the minimum distance to something larger than the default manip->getSettings()->setMinMaxDistance(5.0, manip->getSettings()->getMaxDistance()); viewer.setSceneData( root ); manip->getSettings()->bindMouse( EarthManipulator::ACTION_EARTH_DRAG, osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON, osgGA::GUIEventAdapter::MODKEY_SHIFT ); manip->getSettings()->setArcViewpointTransitions( true ); viewer.addEventHandler(new FlyToViewpointHandler( manip )); viewer.addEventHandler(new LockAzimuthHandler('u', manip)); viewer.addEventHandler(new ToggleProjectionHandler('c', manip)); viewer.addEventHandler(new ToggleArcViewpointTransitionsHandler('a', manip)); viewer.addEventHandler(new ToggleThrowingHandler('z', manip)); viewer.addEventHandler(new ToggleCollisionHandler('k', manip)); viewer.getCamera()->setNearFarRatio(0.00002); viewer.getCamera()->setSmallFeatureCullingPixelSize(-1.0f); while(!viewer.done()) { viewer.frame(); // simulate slow frame rate //OpenThreads::Thread::microSleep(1000*1000); } return 0; }
Riorlan/osgearth
src/applications/osgearth_manip/osgearth_manip.cpp
C++
lgpl-3.0
15,525
package com.darkona.adventurebackpack.inventory; import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; import com.darkona.adventurebackpack.init.ModBlocks; import com.darkona.adventurebackpack.item.ItemAdventureBackpack; import com.darkona.adventurebackpack.util.Utils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; /** * Created by Darkona on 12/10/2014. */ public class SlotBackpack extends SlotAdventureBackpack { public SlotBackpack(IInventoryAdventureBackpack inventory, int id, int x, int y) { super(inventory, id, x, y); } @Override public boolean isItemValid(ItemStack stack) { return (!(stack.getItem() instanceof ItemAdventureBackpack) && !(stack.getItem() == Item.getItemFromBlock(ModBlocks.blockBackpack))); } @Override public void onPickupFromSlot(EntityPlayer p_82870_1_, ItemStack p_82870_2_) { super.onPickupFromSlot(p_82870_1_, p_82870_2_); } }
Mazdallier/AdventureBackpack2
src/main/java/com/darkona/adventurebackpack/inventory/SlotBackpack.java
Java
lgpl-3.0
1,030
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitExAPI.Markets.Kraken.Requests { /// <summary> /// https://api.kraken.com/0/private/TradeBalance /// </summary> public class RequestTradeBalance { } } /*Input: aclass = asset class (optional): currency (default) asset = base asset used to determine balance (default = ZUSD) Result: array of trade balance info eb = equivalent balance (combined balance of all currencies) tb = trade balance (combined balance of all equity currencies) m = margin amount of open positions n = unrealized net profit/loss of open positions c = cost basis of open positions v = current floating valuation of open positions e = equity = trade balance + unrealized net profit/loss mf = free margin = equity - initial margin (maximum margin available to open new positions) ml = margin level = (equity / initial margin) * 100 */
Horndev/Bitcoin-Exchange-APIs.NET
BitExAPI/Markets/Kraken/Requests/RequestTradeBalance.cs
C#
lgpl-3.0
965
// // BitWiseTrie.hpp // Scissum // // Created by Marten van de Sanden on 12/1/15. // Copyright © 2015 MVDS. All rights reserved. // #ifndef BitWiseTrie_hpp #define BitWiseTrie_hpp #include <vector> //#include <iostream> #include <cstring> #define __SCISSUM_BITWISE_TRIE_USE_ZERO_TABLE 1 namespace scissum { /// TODO: Add cache locality and allocation efficiency by pre allocating an array of nodes!!!!! template <class _Key, class _Value> class BitWiseTrie { public: struct Node { size_t childs[2]; _Value value; Node() { childs[0] = 0; childs[1] = 0; } }; BitWiseTrie() { d_nodes.resize(sizeof(_Key)*8+1); for (size_t i = 0; i < sizeof(_Key)*8+1; ++i) { d_zeroTable[i] = i; } } Node const *node(size_t index) const { return &d_nodes[index]; } Node const *roots(size_t lz) const { return &d_nodes[d_zeroTable[lz]]; } Node *insert(_Key key) { int z = (key != 0?__builtin_clz(key):(sizeof(_Key) * 8)); size_t root = d_zeroTable[z]; int c = (sizeof(_Key) * 8) - z; while (c-- > 0) { //std::cout << "A " << c << " = " << !!(key & (1 << c)) << ".\n"; size_t n = d_nodes[root].childs[!!(key & (1 << c))]; if (n == 0) { break; } root = n; } while (c > 0) { //std::cout << "B " << c << " = " << !!(key & (1 << c)) << ".\n"; size_t n = d_nodes.size(); d_nodes.push_back(Node()); d_nodes[root].childs[!!(key & (1 << c--))] = n; root = n; } if (c == 0) { //std::cout << "C = " << !!(key & 1) << ".\n"; size_t n = d_nodes.size(); d_nodes.push_back(Node()); d_nodes[root].childs[!!(key & 1)] = n; return &d_nodes[n]; } return &d_nodes[root]; } private: std::vector<Node> d_nodes; size_t d_zeroTable[sizeof(_Key)*8+1]; }; } #endif /* BitWiseTrie_hpp */
mvdsanden/scissum
src/utils/BitWiseTrie2.hpp
C++
lgpl-3.0
2,584
/** *×÷Õß:Âé²Ë *ÈÕÆÚ:2013Äê6ÔÂ20ÈÕ *¹¦ÄÜ:×Ô¶¨ÒåÑÕɫѡÔñ¶ÔÏó,´ÓQColorDialogÀàÖÐÌáÈ¡ÖØÐ·â×°.½ö±£Áôͨ¹ýÊó±êpickÌáÈ¡ÑÕÉ«µÄ¿Ø¼þ *˵Ã÷:¿ªÔ´,Ãâ·Ñ,ʹÓÃʱÇë±£³Ö¿ªÔ´¾«Éñ. *ÁªÏµ:12319597@qq.com *²©¿Í:www.newdebug.com **/ #include "colorshowlabel.h" #include <QApplication> #include <QPainter> #include <QMimeData> #include <QDrag> #include <QMouseEvent> YviColorShowLabel::YviColorShowLabel(QWidget *parent) : QFrame(parent) { this->setFrameStyle(QFrame::Panel|QFrame::Sunken); this->setAcceptDrops(true); m_mousePressed = false; } void YviColorShowLabel::paintEvent(QPaintEvent *e) { QPainter p(this); drawFrame(&p); p.fillRect(contentsRect()&e->rect(), m_color); } void YviColorShowLabel::mousePressEvent(QMouseEvent *e) { m_mousePressed = true; m_pressPos = e->pos(); } void YviColorShowLabel::mouseMoveEvent(QMouseEvent *e) { if (!m_mousePressed) return; if ((m_pressPos - e->pos()).manhattanLength() > QApplication::startDragDistance()) { QMimeData *mime = new QMimeData; mime->setColorData(m_color); QPixmap pix(30, 20); pix.fill(m_color); QPainter p(&pix); p.drawRect(0, 0, pix.width() - 1, pix.height() - 1); p.end(); QDrag *drg = new QDrag(this); drg->setMimeData(mime); drg->setPixmap(pix); m_mousePressed = false; drg->start(); } } void YviColorShowLabel::mouseReleaseEvent(QMouseEvent *) { if (!m_mousePressed) return; m_mousePressed = false; }
newdebug/NewDebug
Qt/YviColorDialog/colorshowlabel.cpp
C++
lgpl-3.0
1,536
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Harnet.Net { public class Request { #region Properties /// <summary> /// Request method (GET, POST, ...). /// </summary> public string Method { get; set; } /// <summary> /// Absolute URL of the request (fragments are not included). /// </summary> public string Url { get; set; } /// <summary> /// Request HTTP Version. /// </summary> public string HttpVersion { get; set; } /// <summary> /// List of header objects. /// </summary> public Dictionary<string, List<string>> Headers { get; set; } /// <summary> /// List of query parameter objects. /// </summary> public Dictionary<string, List<string>> QueryStrings { get; set; } /// <summary> /// List of cookie objects. /// </summary> public Dictionary<string, List<string>> Cookies { get; set; } /// <summary> /// Total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body. Set to -1 if the info is not available. /// </summary> public int HeaderSize { get; set; } /// <summary> /// Size of the request body (POST data payload) in bytes. Set to -1 if the info is not available. /// </summary> public int BodySize { get; set; } /// <summary> /// Posted data info. /// </summary> public PostData PostData { get; set; } /// <summary> /// A comment provided by the user or the application. /// </summary> public string Comment { get; set; } #endregion #region Methods public List<string> GetHeaderValueByHeaderName(string name) { List<string> value = null; if (Headers.ContainsKey(name)) { value = Headers[name]; } return value; } /// <summary> /// Attempts to retrieve the filename from the request. /// </summary> /// <returns>Returns the filename. If no filename is found, returns null.</returns> public string GetFileName() { string fileName = null; // If we have query strings we remove them first because sometimes they get funky if (this.QueryStrings.Count >= 1) { fileName = StripQueryStringsFromUrl(); } else fileName = Url; // Isolate what's after the trailing slash and before any query string int index = fileName.LastIndexOf("/"); // If difference between index and length is < 1, it means we have no file name // e.g.: http://www.fsf.org/ int diff = fileName.Length - index; if (index > 0 && diff > 1) fileName = fileName.Substring(index +1, diff - 1); else fileName = null; return fileName; } /// <summary> /// Strips the Url of all query strings and returns it (e.g. www.fsf.org/index.html?foo=bar returns www.fsg.org/index.html). /// </summary> /// <returns></returns> public string StripQueryStringsFromUrl() { int indexOf = Url.IndexOf("?"); if (indexOf >= 1) return Url.Substring(0, indexOf); else return Url; } /// <summary> /// Returns whether or not this request contains cookies. /// </summary> /// <returns></returns> public bool HasCookies() { return (this.Cookies.Count > 0) ? true : false; } /// <summary> /// Returns whether or not this request contains headers. /// </summary> /// <returns></returns> public bool HasHeaders() { return (this.Headers.Count > 0) ? true : false; } /// <summary> /// Returns whether or not this request contains query strings. /// </summary> /// <returns></returns> public bool HasQueryStrings() { return (this.QueryStrings.Count > 0) ? true : false; } #endregion } }
acastaner/harnet
harnet/Net/Request.cs
C#
lgpl-3.0
4,474
package org.alfresco.repo.cmis.ws; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="repositoryId" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="extension" type="{http://docs.oasis-open.org/ns/cmis/messaging/200908/}cmisExtensionType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "repositoryId", "extension" }) @XmlRootElement(name = "getRepositoryInfo") public class GetRepositoryInfo { @XmlElement(required = true) protected String repositoryId; @XmlElementRef(name = "extension", namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", type = JAXBElement.class) protected JAXBElement<CmisExtensionType> extension; /** * Gets the value of the repositoryId property. * * @return * possible object is * {@link String } * */ public String getRepositoryId() { return repositoryId; } /** * Sets the value of the repositoryId property. * * @param value * allowed object is * {@link String } * */ public void setRepositoryId(String value) { this.repositoryId = value; } /** * Gets the value of the extension property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link CmisExtensionType }{@code >} * */ public JAXBElement<CmisExtensionType> getExtension() { return extension; } /** * Sets the value of the extension property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link CmisExtensionType }{@code >} * */ public void setExtension(JAXBElement<CmisExtensionType> value) { this.extension = ((JAXBElement<CmisExtensionType> ) value); } }
loftuxab/community-edition-old
projects/remote-api/source/generated/org/alfresco/repo/cmis/ws/GetRepositoryInfo.java
Java
lgpl-3.0
2,688
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace LeagueOfChampios { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
pirufio/leagueofchampions
LeagueOfChampios/App_Start/RouteConfig.cs
C#
lgpl-3.0
585
// Copyright (C) 2013 Columbia University in the City of New York and others. // // Please see the AUTHORS file in the main source directory for a full list // of contributors. // // This file is part of TerraFERMA. // // TerraFERMA 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. // // TerraFERMA 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 TerraFERMA. If not, see <http://www.gnu.org/licenses/>. #include "SemiLagrangianExpression.h" #include "BoostTypes.h" #include "Bucket.h" #include "Logger.h" #include <dolfin.h> using namespace buckettools; //*******************************************************************|************************************************************// // specific constructor (scalar) //*******************************************************************|************************************************************// SemiLagrangianExpression::SemiLagrangianExpression(const Bucket *bucket, const double_ptr time, const std::pair< std::string, std::pair< std::string, std::string > > &function, const std::pair< std::string, std::pair< std::string, std::string > > &velocity, const std::pair< std::string, std::pair< std::string, std::string > > &outside) : dolfin::Expression(), bucket_(bucket), time_(time), funcname_(function), velname_(velocity), outname_(outside), initialized_(false) { tf_not_parallelized("SemiLagrangianExpression"); } //*******************************************************************|************************************************************// // specific constructor (vector) //*******************************************************************|************************************************************// SemiLagrangianExpression::SemiLagrangianExpression(const std::size_t &dim, const Bucket *bucket, const double_ptr time, const std::pair< std::string, std::pair< std::string, std::string > > &function, const std::pair< std::string, std::pair< std::string, std::string > > &velocity, const std::pair< std::string, std::pair< std::string, std::string > > &outside) : dolfin::Expression(dim), bucket_(bucket), time_(time), funcname_(function), velname_(velocity), outname_(outside), initialized_(false) { tf_not_parallelized("SemiLagrangianExpression"); } //*******************************************************************|************************************************************// // specific constructor (tensor) //*******************************************************************|************************************************************// SemiLagrangianExpression::SemiLagrangianExpression(const std::vector<std::size_t> &value_shape, const Bucket *bucket, const double_ptr time, const std::pair< std::string, std::pair< std::string, std::string > > &function, const std::pair< std::string, std::pair< std::string, std::string > > &velocity, const std::pair< std::string, std::pair< std::string, std::string > > &outside) : dolfin::Expression(value_shape), bucket_(bucket), time_(time), funcname_(function), velname_(velocity), outname_(outside), initialized_(false) { tf_not_parallelized("SemiLagrangianExpression"); } //*******************************************************************|************************************************************// // default destructor //*******************************************************************|************************************************************// SemiLagrangianExpression::~SemiLagrangianExpression() { delete ufccellstar_; ufccellstar_ = NULL; delete[] xstar_; xstar_ = NULL; delete v_; v_ = NULL; delete oldv_; oldv_ = NULL; delete vstar_; vstar_ = NULL; delete cellcache_; cellcache_ = NULL; } //*******************************************************************|************************************************************// // initialize the expression //*******************************************************************|************************************************************// void SemiLagrangianExpression::init() { if (!initialized_) { initialized_ = true; if(funcname_.second.first=="field") { func_ = (*(*(*bucket()).fetch_system(funcname_.first)). fetch_field(funcname_.second.second)). genericfunction_ptr(time()); } else { func_ = (*(*(*bucket()).fetch_system(funcname_.first)). fetch_coeff(funcname_.second.second)). genericfunction_ptr(time()); } if(velname_.second.first=="field") { vel_ = (*(*(*bucket()).fetch_system(velname_.first)). fetch_field(velname_.second.second)). genericfunction_ptr((*bucket()).current_time_ptr()); oldvel_ = (*(*(*bucket()).fetch_system(velname_.first)). fetch_field(velname_.second.second)). genericfunction_ptr((*bucket()).old_time_ptr()); } else { vel_ = (*(*(*bucket()).fetch_system(velname_.first)). fetch_coeff(velname_.second.second)). genericfunction_ptr((*bucket()).current_time_ptr()); oldvel_ = (*(*(*bucket()).fetch_system(velname_.first)). fetch_coeff(velname_.second.second)). genericfunction_ptr((*bucket()).old_time_ptr()); } if(outname_.second.first=="field") { out_ = (*(*(*bucket()).fetch_system(outname_.first)). fetch_field(outname_.second.second)). genericfunction_ptr(time()); } else { out_ = (*(*(*bucket()).fetch_system(outname_.first)). fetch_coeff(outname_.second.second)). genericfunction_ptr(time()); } assert(value_rank()==(*func_).value_rank()); assert(value_rank()==(*out_).value_rank()); for (uint i = 0; i < value_rank(); i++) { assert(value_dimension(i)==(*func_).value_dimension(i)); assert(value_dimension(i)==(*out_).value_dimension(i)); } mesh_ = (*(*bucket()).fetch_system(funcname_.first)).mesh();// use the mesh from the function system dim_ = (*mesh_).geometry().dim(); assert((*vel_).value_rank()<2); if((*vel_).value_rank()==0) { assert(dim_==1); } else { assert((*vel_).value_dimension(0)==dim_); } ufccellstar_ = new ufc::cell; xstar_ = new double[dim_]; v_ = new dolfin::Array<double>(dim_); oldv_ = new dolfin::Array<double>(dim_); vstar_ = new dolfin::Array<double>(dim_); cellcache_ = new dolfin::MeshFunction< point_map >(mesh_, dim_); } } //*******************************************************************|************************************************************// // overload dolfin expression eval //*******************************************************************|************************************************************// void SemiLagrangianExpression::eval(dolfin::Array<double>& values, const dolfin::Array<double>& x, const ufc::cell &cell) const { const bool outside = findpoint_(x, cell); dolfin::Array<double> xstar(dim_, xstar_); if (outside) { (*out_).eval(values, xstar, *ufccellstar_); } else { (*func_).eval(values, xstar, *ufccellstar_); } } //*******************************************************************|************************************************************// // find the launch point //*******************************************************************|************************************************************// const bool SemiLagrangianExpression::findpoint_(const dolfin::Array<double>& x, const ufc::cell &cell) const { bool outside = false; point_map &points = (*cellcache_)[cell.index]; dolfin::Point lp(x.size(), x.data()); point_iterator p_it = points.find(lp); findvstar_(x, cell); for (uint k = 0; k < 2; k++) { for (uint i = 0; i < dim_; i++) { xstar_[i] = x[i] - ((*bucket()).timestep()/2.0)*(*vstar_)[i]; } outside = checkpoint_(0, p_it, points, lp); if (outside) { return true; } dolfin::Array<double> xstar(dim_, xstar_); findvstar_(xstar, *ufccellstar_); } for (uint i = 0; i < dim_; i++) { xstar_[i] = x[i] - ((*bucket()).timestep())*(*vstar_)[i]; } outside = checkpoint_(1, p_it, points, lp); if (outside) { return true; } return false; } //*******************************************************************|************************************************************// // find the time weighted velocity at the requested point, x //*******************************************************************|************************************************************// void SemiLagrangianExpression::findvstar_(const dolfin::Array<double>& x, const ufc::cell &cell) const { (*vel_).eval(*v_, x, cell); (*oldvel_).eval(*oldv_, x, cell); for (uint i = 0; i < dim_; i++) { (*vstar_)[i] = 0.5*( (*v_)[i] + (*oldv_)[i] ); } } //*******************************************************************|************************************************************// // check if the current xstar_ is in the cache and/or is valid //*******************************************************************|************************************************************// const bool SemiLagrangianExpression::checkpoint_(const int &index, point_iterator &p_it, point_map &points, const dolfin::Point &lp) const { std::vector<unsigned int> cell_indices; int cell_index; const dolfin::Point p(dim_, xstar_); if (p_it != points.end()) { cell_index = (*p_it).second[index]; bool update = false; if (cell_index < 0) { update = true; } else { dolfin::Cell dolfincell(*mesh_, cell_index); if (!dolfincell.collides(p)) { update = true; } } if (update) { cell_indices = (*(*mesh_).bounding_box_tree()).compute_entity_collisions(p); if (cell_indices.size()==0) { cell_index = -1; } else { cell_index = cell_indices[0]; } (*p_it).second[index] = cell_index; } } else { cell_indices = (*(*mesh_).bounding_box_tree()).compute_entity_collisions(p); if (cell_indices.size()==0) { cell_index = -1; } else { cell_index = cell_indices[0]; } std::vector<int> cells(2, -1); cells[index] = cell_index; points[lp] = cells; } if (cell_index<0) { return true; } dolfin::Cell dolfincell(*mesh_, cell_index); dolfincell.get_cell_data(*ufccellstar_); return false; }
TerraFERMA/TerraFERMA
buckettools/cpp/SemiLagrangianExpression.cpp
C++
lgpl-3.0
13,110
#include "util/checksum.hpp" namespace trillek { namespace util { namespace algorithm { static uint32_t crc32_table[256]; static bool crc32_table_computed = false; static void GenCRC32Table() { uint32_t c; uint32_t i; int k; for(i = 0; i < 256; i++) { c = i; for(k = 0; k < 8; k++) { if(c & 1) c = 0xedb88320ul ^ (c >> 1); else c = c >> 1; } crc32_table[i] = c; } crc32_table_computed = true; } void Crc32::Update(char d) { if(!crc32_table_computed) GenCRC32Table(); ldata = crc32_table[(ldata ^ ((unsigned char)d)) & 0xff] ^ (ldata >> 8); } void Crc32::Update(const std::string &d) { uint32_t c = ldata; std::string::size_type n, l = d.length(); if(!crc32_table_computed) GenCRC32Table(); for(n = 0; n < l; n++) { c = crc32_table[(c ^ ((unsigned char)d[n])) & 0xff] ^ (c >> 8); } ldata = c; } void Crc32::Update(const void *dv, size_t l) { uint32_t c = ldata; std::string::size_type n; char * d = (char*)dv; if(!crc32_table_computed) GenCRC32Table(); for(n = 0; n < l; n++) { c = crc32_table[(c ^ ((unsigned char)d[n])) & 0xff] ^ (c >> 8); } ldata = c; } static const uint32_t ADLER_LIMIT = 5552; static const uint32_t ADLER_BASE = 65521u; void Adler32::Update(const std::string &d) { Update(d.data(), d.length()); } void Adler32::Update(const void *dv, size_t l) { uint32_t c1 = ldata & 0xffff; uint32_t c2 = (ldata >> 16) & 0xffff; unsigned char * d = (unsigned char*)dv; std::string::size_type n = 0; while(l >= ADLER_LIMIT) { l -= ADLER_LIMIT; uint32_t limit = ADLER_LIMIT / 16; while(limit--) { c1 += d[n ]; c2 += c1; c1 += d[n+ 1]; c2 += c1; c1 += d[n+ 2]; c2 += c1; c1 += d[n+ 3]; c2 += c1; c1 += d[n+ 4]; c2 += c1; c1 += d[n+ 5]; c2 += c1; c1 += d[n+ 6]; c2 += c1; c1 += d[n+ 7]; c2 += c1; c1 += d[n+ 8]; c2 += c1; c1 += d[n+ 9]; c2 += c1; c1 += d[n+10]; c2 += c1; c1 += d[n+11]; c2 += c1; c1 += d[n+12]; c2 += c1; c1 += d[n+13]; c2 += c1; c1 += d[n+14]; c2 += c1; c1 += d[n+15]; c2 += c1; n += 16; } c1 %= ADLER_BASE; c2 %= ADLER_BASE; } for(; l; n++, l--) { c1 += d[n]; while(c1 >= ADLER_BASE) { c1 -= ADLER_BASE; } c2 += c1; while(c2 >= ADLER_BASE) { c2 -= ADLER_BASE; } } ldata = (c2 << 16) + c1; } } // algorithm } // util } // trillek
trillek-team/trillek-common
src/util/checksum.cpp
C++
lgpl-3.0
2,639
/* * Copyright (C) 2011-2020 goblinhack@gmail.com * * See the LICENSE file for license. */ #include "my_main.h" #include "my_thing_tile.h" #include "my_time_util.h" #include "my_wid.h" void wid_animate (widp w) {_ if (!w->animate) { return; } tpp tp = wid_get_thing_template(w); if (!tp) { return; } if (!tp_is_animated(tp)) { return; } thing_tilep tile; tile = w->current_tile; if (tile) { /* * If within the animate time of this frame, keep with it. */ if (w->timestamp_change_to_next_frame > time_get_time_ms()) { return; } /* * Stop the animation here? */ if (thing_tile_is_end_of_anim(tile)) { return; } } auto tiles = tp_get_tiles(tp); /* * Get the next tile. */ if (tile) { tile = thing_tile_next(tiles, tile); } /* * Find a tile that matches the things current mode. */ uint32_t size = tiles.size(); uint32_t tries = 0; while (tries < size) { tries++; /* * Cater for wraps. */ if (!tile) { tile = thing_tile_first(tiles); } { if (thing_tile_is_dead(tile)) { tile = thing_tile_next(tiles, tile); continue; } if (thing_tile_is_open(tile)) { tile = thing_tile_next(tiles, tile); continue; } } break; } if (!tile) { return; } /* * Use this tile! */ w->current_tile = tile; wid_set_tilename(w, thing_tile_name(tile)); /* * When does this tile expire ? */ uint32_t delay = thing_tile_delay_ms(tile); if (delay) { delay = myrand() % delay; } w->timestamp_change_to_next_frame = time_get_time_ms() + delay; }
goblinhack/goblinhack2
src/wid_anim.cpp
C++
lgpl-3.0
1,949
/****************************************************************************** * Copyright (c) 2014-2015 Leandro T. C. Melo (ltcmelo@gmail.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA *****************************************************************************/ #include "ui_uaisosettings.h" #include "uaisosettings.h" #include "uaisoeditor.h" #include <coreplugin/icore.h> #include <QPointer> /* Uaiso - https://github.com/ltcmelo/uaiso * * Notice: This implementation has the only purpose of showcasing a few * components of the Uaiso project. It's not intended to be efficient, * nor to be taken as reference on how to write Qt Creator editors. It's * not even complete. The primary concern is to demonstrate Uaiso's API. */ using namespace UaisoQtc; using namespace TextEditor; using namespace uaiso; struct UaisoSettingsPage::UaisoSettingsPagePrivate { explicit UaisoSettingsPagePrivate() : m_displayName(tr("Uaiso Source Analyser")) , m_settingsPrefix(QLatin1String("Uaiso")) , m_prevIndex(-1) , m_page(0) {} const Core::Id m_id; const QString m_displayName; const QString m_settingsPrefix; int m_prevIndex; UaisoSettings m_settings; QPointer<QWidget> m_widget; Ui::UaisoSettingsPage *m_page; }; UaisoSettingsPage::UaisoSettingsPage(QObject *parent) : Core::IOptionsPage(parent) , m_d(new UaisoSettingsPagePrivate) { setId(Constants::SETTINGS_ID); setDisplayName(m_d->m_displayName); setCategory(Constants::SETTINGS_CATEGORY); setDisplayCategory(QCoreApplication::translate("Uaiso", Constants::SETTINGS_TR_CATEGORY)); //setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_ICON)); } UaisoSettingsPage::~UaisoSettingsPage() { delete m_d; } QWidget *UaisoSettingsPage::widget() { if (!m_d->m_widget) { m_d->m_widget = new QWidget; m_d->m_page = new Ui::UaisoSettingsPage; m_d->m_page->setupUi(m_d->m_widget); m_d->m_page->langCombo->setCurrentIndex(0); for (auto lang : supportedLangs()) { m_d->m_page->langCombo->addItem(QString::fromStdString(langName(lang)), QVariant::fromValue(static_cast<int>(lang))); } m_d->m_settings.load(Core::ICore::settings()); m_d->m_prevIndex = -1; // Reset previous index. connect(m_d->m_page->langCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(displayOptionsForLang(int))); settingsToUI(); } return m_d->m_widget; } void UaisoSettingsPage::apply() { if (!m_d->m_page) return; settingsFromUI(); m_d->m_settings.store(Core::ICore::settings()); } void UaisoSettingsPage::finish() { delete m_d->m_widget; if (!m_d->m_page) return; delete m_d->m_page; m_d->m_page = 0; } void UaisoSettingsPage::displayOptionsForLang(int index) { if (m_d->m_prevIndex != -1) updateOptionsOfLang(m_d->m_prevIndex); UaisoSettings::LangOptions &options = m_d->m_settings.m_options[index]; m_d->m_page->enabledCheck->setChecked(options.m_enabled); m_d->m_page->interpreterEdit->setText(options.m_interpreter); m_d->m_page->sysPathEdit->setText(options.m_systemPaths); m_d->m_page->extraPathEdit->setText(options.m_extraPaths); m_d->m_prevIndex = index; } void UaisoSettingsPage::updateOptionsOfLang(int index) { UaisoSettings::LangOptions &options = m_d->m_settings.m_options[index]; options.m_enabled = m_d->m_page->enabledCheck->isChecked(); options.m_interpreter = m_d->m_page->interpreterEdit->text(); options.m_systemPaths = m_d->m_page->sysPathEdit->text(); options.m_extraPaths = m_d->m_page->extraPathEdit->text(); } void UaisoSettingsPage::settingsFromUI() { updateOptionsOfLang(m_d->m_page->langCombo->currentIndex()); } void UaisoSettingsPage::settingsToUI() { displayOptionsForLang(m_d->m_page->langCombo->currentIndex()); } namespace { const QLatin1String kUaiso("UaisoSettings"); const QLatin1String kEnabled("Enabled"); const QLatin1String kInterpreter("Interpreter"); const QLatin1String kSystemPaths("SystemPaths"); const QLatin1String kExtraPaths("ExtraPaths"); } // anonymous void UaisoSettings::store(QSettings *settings, const LangOptions &options, const QString& group) const { settings->beginGroup(group); settings->setValue(kEnabled, options.m_enabled); settings->setValue(kInterpreter, options.m_interpreter); settings->setValue(kSystemPaths, options.m_systemPaths); settings->setValue(kExtraPaths, options.m_extraPaths); settings->endGroup(); } void UaisoSettings::store(QSettings *settings) const { for (auto const& option : m_options) { store(settings, option.second, kUaiso + QString::fromStdString(langName(LangName(option.first)))); } } void UaisoSettings::load(QSettings *settings, LangOptions &options, const QString& group) { settings->beginGroup(group); options.m_enabled = settings->value(kEnabled).toBool(); options.m_interpreter = settings->value(kInterpreter).toString(); options.m_systemPaths = settings->value(kSystemPaths).toString(); options.m_extraPaths = settings->value(kExtraPaths).toString(); settings->endGroup(); } void UaisoSettings::load(QSettings *settings) { for (auto lang : supportedLangs()) { auto& option = m_options[static_cast<int>(lang)]; load(settings, option, kUaiso + QString::fromStdString(langName(lang))); } }
ltcmelo/qt-creator
src/plugins/uaisoeditor/uaisosettings.cpp
C++
lgpl-3.0
6,458
/**************************************************************************** ** ** Copyright (C) 2014-2018 Dinu SV. ** (contact: mail@dinusv.com) ** This file is part of Live CV Application. ** ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPLv3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl.html. ** ****************************************************************************/ #include "qmllibrarydependency.h" #include <QStringList> namespace lv{ QmlLibraryDependency::QmlLibraryDependency(const QString &uri, int versionMajor, int versionMinor) : m_uri(uri) , m_versionMajor(versionMajor) , m_versionMinor(versionMinor) { } QmlLibraryDependency::~QmlLibraryDependency(){ } QmlLibraryDependency QmlLibraryDependency::parse(const QString &import){ int position = import.lastIndexOf(' '); if ( position == -1 ) return QmlLibraryDependency("", -1, -1); int major, minor; bool isVersion = parseVersion(import.mid(position + 1).trimmed(), &major, &minor); if ( !isVersion ) return QmlLibraryDependency("", -1, -1); return QmlLibraryDependency(import.mid(0, position).trimmed(), major, minor); } int QmlLibraryDependency::parseInt(const QStringRef &str, bool *ok){ int pos = 0; int number = 0; while (pos < str.length() && str.at(pos).isDigit()) { if (pos != 0) number *= 10; number += str.at(pos).unicode() - '0'; ++pos; } if (pos != str.length()) *ok = false; else *ok = true; return number; } bool QmlLibraryDependency::parseVersion(const QString &str, int *major, int *minor){ const int dotIndex = str.indexOf(QLatin1Char('.')); if (dotIndex != -1 && str.indexOf(QLatin1Char('.'), dotIndex + 1) == -1) { bool ok = false; *major = parseInt(QStringRef(&str, 0, dotIndex), &ok); if (ok) *minor = parseInt(QStringRef(&str, dotIndex + 1, str.length() - dotIndex - 1), &ok); return ok; } return false; } QString QmlLibraryDependency::path() const{ QStringList splitPath = m_uri.split('.'); QString res = splitPath.join(QLatin1Char('/')); if (res.isEmpty() && !splitPath.isEmpty()) return QLatin1String("/"); return res; } }// namespace
livecv/livecv
lib/lveditqmljs/src/qmllibrarydependency.cpp
C++
lgpl-3.0
2,596
package org.energy_home.dal.functions.data; import java.util.Map; import org.osgi.service.dal.FunctionData; public class DoorLockData extends FunctionData { public final static String STATUS_OPEN = "OPEN"; public final static String STATUS_CLOSED = "CLOSED"; private String status; public DoorLockData(long timestamp, Map metadata) { super(timestamp, metadata); } public DoorLockData(long timestamp, Map metadata, String status) { super(timestamp, metadata); this.status = status; } public String getStatus() { return this.status; } public int compareTo(Object o) { return 0; } }
ismb/jemma.osgi.dal.functions.eh
src/main/java/org/energy_home/dal/functions/data/DoorLockData.java
Java
lgpl-3.0
611
/* * Mentawai Web Framework http://mentawai.lohis.com.br/ * Copyright (C) 2005 Sergio Oliveira Jr. (sergio.oliveira.jr@gmail.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.mentawai.filter; import org.mentawai.core.Filter; import org.mentawai.core.InvocationChain; public class GlobalFilterFreeMarkerFilter implements Filter { private final String[] innerActions; public GlobalFilterFreeMarkerFilter() { this.innerActions = null; } public GlobalFilterFreeMarkerFilter(String ... innerActions) { this.innerActions = innerActions; } public boolean isGlobalFilterFree(String innerAction) { if (innerActions == null) return true; if (innerAction == null) return false; // inner actions are specified... for(String s : innerActions) { if (s.equals(innerAction)) return true; } return false; } public String filter(InvocationChain chain) throws Exception { return chain.invoke(); } public void destroy() { } }
tempbottle/mentawai
src/main/java/org/mentawai/filter/GlobalFilterFreeMarkerFilter.java
Java
lgpl-3.0
1,882
/* * */ // Local #include <vcgNodes/vcgMeshStats/vcgMeshStatsNode.h> #include <vcgNodes/vcgNodeTypeIds.h> // Utils #include <utilities/debugUtils.h> // Function Sets #include <maya/MFnMeshData.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnEnumAttribute.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnMatrixAttribute.h> #include <maya/MFnMatrixData.h> // General Includes #include <maya/MGlobal.h> #include <maya/MPlug.h> #include <maya/MDataBlock.h> #include <maya/MDataHandle.h> #include <maya/MIOStream.h> // Macros #define MCheckStatus(status, message) \ if( MStatus::kSuccess != status ) { \ cerr << message << "\n"; \ return status; \ } // Unique Node TypeId // See 'vcgNodeTypeIds.h', add a definition. MTypeId vcgMeshStatsNode::id(VCG_MESH_STATS_NODE_ID); // Use a unique ID. // Node attributes MObject vcgMeshStatsNode::inMesh; MObject vcgMeshStatsNode::outMesh; MObject vcgMeshStatsNode::aEnable; MObject vcgMeshStatsNode::aOutCentreOfMass; MObject vcgMeshStatsNode::aOutMass; vcgMeshStatsNode::vcgMeshStatsNode() {} vcgMeshStatsNode::~vcgMeshStatsNode() {} MStatus vcgMeshStatsNode::compute(const MPlug &plug, MDataBlock &data) // // Description: // This method computes the value of the given output plug based // on the values of the input attributes. // // Arguments: // plug - the plug to compute // data - object that provides access to the attributes for this node // { MStatus status = MS::kSuccess; MDataHandle stateData = data.outputValue(state, &status); MCheckStatus(status, "ERROR getting state"); INFO("vcgMeshStats plug: " << plug.name()); // Check for the HasNoEffect/PassThrough flag on the node. // // (stateData is an enumeration standard in all depend nodes) // // (0 = Normal) // (1 = HasNoEffect/PassThrough) // (2 = Blocking) // ... // if (stateData.asShort() == 1) { MDataHandle inputData = data.inputValue(inMesh, &status); MCheckStatus(status, "ERROR getting inMesh"); MDataHandle outputData = data.outputValue(outMesh, &status); MCheckStatus(status, "ERROR getting outMesh"); // Simply redirect the inMesh to the outMesh for the PassThrough effect outputData.set(inputData.asMesh()); } else { // Check which output attribute we have been asked to // compute. If this node doesn't know how to compute it, // we must return MS::kUnknownParameter if (plug == outMesh || plug == aOutCentreOfMass || plug == aOutMass) { MDataHandle inputData = data.inputValue(inMesh, &status); MCheckStatus(status, "ERROR getting inMesh"); MDataHandle outputData = data.outputValue(outMesh, &status); MCheckStatus(status, "ERROR getting outMesh"); // Copy the inMesh to the outMesh, so you can // perform operations directly on outMesh outputData.set(inputData.asMesh()); // Return if the node is not enabled. MDataHandle enableData = data.inputValue(aEnable, &status); MCheckStatus(status, "ERROR getting aEnable"); if (!enableData.asBool()) { return MS::kSuccess; } // Get Mesh object MObject mesh = outputData.asMesh(); // Set the mesh object and component List on the factory fFactory.setMesh(mesh); // Now, perform the vcgMeshStats status = fFactory.doIt(); // Centre Of Mass Output MVector centreOfMass(fFactory.getCentreOfMass()); INFO("compute centre of mass X:" << centreOfMass[0]); INFO("compute centre of mass Y:" << centreOfMass[1]); INFO("compute centre of mass Z:" << centreOfMass[2]); MDataHandle centreOfMassData = data.outputValue(aOutCentreOfMass, &status); MCheckStatus(status, "ERROR getting aOutCentreOfMass"); centreOfMassData.setMVector(centreOfMass); // Mass Output float mass = fFactory.getMass(); INFO("compute mass:" << mass); MDataHandle massData = data.outputValue(aOutMass, &status); MCheckStatus(status, "ERROR getting aOutMass"); massData.setFloat(mass); // Mark the output mesh as clean outputData.setClean(); centreOfMassData.setClean(); massData.setClean(); } // else if // { // MDataHandle inputData = data.inputValue(inMesh, &status); // MCheckStatus(status, "ERROR getting inMesh"); // // // Return if the node is not enabled. // MDataHandle enableData = data.inputValue(aEnable, &status); // MCheckStatus(status, "ERROR getting aEnable"); // if (!enableData.asBool()) // { // return MS::kSuccess; // } // // // Get Mesh object // MObject mesh = inputData.asMesh(); // // // Set the mesh object and component List on the factory // fFactory.setMesh(mesh); // // // Now, perform the vcgMeshStats // status = fFactory.doIt(); // // // Centre Of Mass Output // MVector centreOfMass(fFactory.getCentreOfMass()); // MDataHandle centreOfMassData = data.outputValue(aOutCentreOfMass, &status); // MCheckStatus(status, "ERROR getting aOutCentreOfMass"); // centreOfMassData.setMVector(centreOfMass); // // // Mass Output // float mass = fFactory.getMass(); // MDataHandle massData = data.outputValue(aOutMass, &status); // MCheckStatus(status, "ERROR getting aOutMass"); // massData.setFloat(mass); // // // Mark the output mesh as clean // // } else { status = MS::kUnknownParameter; } } return status; } void *vcgMeshStatsNode::creator() // // Description: // this method exists to give Maya a way to create new objects // of this type. // // Return Value: // a new object of this type // { return new vcgMeshStatsNode(); } MStatus vcgMeshStatsNode::initialize() // // Description: // This method is called to create and initialize all of the attributes // and attribute dependencies for this node type. This is only called // once when the node type is registered with Maya. // // Return Values: // MS::kSuccess // MS::kFailure // { MStatus status; MFnTypedAttribute attrFn; MFnNumericAttribute numFn; aEnable = numFn.create("enable", "enable", MFnNumericData::kBoolean, true, &status); CHECK_MSTATUS(status); status = numFn.setDefault(true); status = numFn.setStorable(true); status = numFn.setKeyable(true); status = numFn.setChannelBox(true); status = numFn.setHidden(false); status = addAttribute(aEnable); CHECK_MSTATUS(status); // Centre of Mass aOutCentreOfMass = numFn.createPoint("outCentreOfMass", "outCentreOfMass", &status); // MFnNumericData::k3Float, 0.0, &status); CHECK_MSTATUS(status); // numFn.setDefault(0.0f, 0.0f, 0.0f); // numFn.setKeyable(false); numFn.setStorable(false); numFn.setWritable(false); status = addAttribute(aOutCentreOfMass); CHECK_MSTATUS(status); // Mass aOutMass = numFn.create("outMass", "outMass", MFnNumericData::kFloat, 0.0, &status); CHECK_MSTATUS(status); numFn.setDefault(0.0f); numFn.setKeyable(false); numFn.setStorable(false); numFn.setWritable(false); status = addAttribute(aOutMass); CHECK_MSTATUS(status); // Input Mesh inMesh = attrFn.create("inMesh", "im", MFnMeshData::kMesh); attrFn.setStorable(true); // To be stored during file-save status = addAttribute(inMesh); CHECK_MSTATUS(status); // Output Mesh // Attribute is read-only because it is an output attribute outMesh = attrFn.create("outMesh", "om", MFnMeshData::kMesh); attrFn.setStorable(false); attrFn.setWritable(false); status = addAttribute(outMesh); CHECK_MSTATUS(status); // Attribute affects status = attributeAffects(inMesh, outMesh); status = attributeAffects(aEnable, outMesh); status = attributeAffects(inMesh, aOutCentreOfMass); status = attributeAffects(aEnable, aOutCentreOfMass); status = attributeAffects(inMesh, aOutMass); status = attributeAffects(aEnable, aOutMass); CHECK_MSTATUS(status); return MS::kSuccess; }
david-cattermole/vcglib-maya
src/vcgNodes/vcgMeshStats/vcgMeshStatsNode.cpp
C++
lgpl-3.0
8,153
 #region Copyrights // // RODI - http://rodi.aisdev.net // Copyright (c) 2012-2016 // by SAS AIS : http://www.aisdev.net // supervised by : Jean-Paul GONTIER (Rotary Club Sophia Antipolis - District 1730) // //GNU LESSER GENERAL PUBLIC LICENSE //Version 3, 29 June 2007 Copyright (C) 2007 //Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. //This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. //0. Additional Definitions. //As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. //"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. //An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library.Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. //A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". //The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. //The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. //1. Exception to Section 3 of the GNU GPL. //You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. //2. Conveying Modified Versions. //If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: //a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or //b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. //3. Object Code Incorporating Material from Library Header Files. //The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates(ten or fewer lines in length), you do both of the following: //a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. //b) Accompany the object code with a copy of the GNU GPL and this license document. //4. Combined Works. //You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: //a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. //b) Accompany the Combined Work with a copy of the GNU GPL and this license document. //c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. //d) Do one of the following: //0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. //1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. //e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) //5. Combined Libraries. //You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: //a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. //b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. //6. Revised Versions of the GNU Lesser General Public License. //The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. //Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. //If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. #endregion Copyrights using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIS { [Serializable] public class General_Attendance { public int id {get; set;} public String name {get; set;} public int nbm {get; set;} public String purcent {get; set;} public String purcentPastYear { get; set; } public String varEff { get; set; } public int month { get; set; } public int year { get; set; } public String varAtt { get; set; } } }
JeanPaulGontier/RODI
ais/General_Attendance.cs
C#
lgpl-3.0
8,179
package org.osmdroid.bonuspack.utils; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import android.util.Log; /** * A "very very simple to use" class for performing http get and post requests. * So many ways to do that, and potential subtle issues. * If complexity should be added to handle even more issues, complexity should be put here and only here. * * Typical usage: * <pre>HttpConnection connection = new HttpConnection(); * connection.doGet("http://www.google.com"); * InputStream stream = connection.getStream(); * if (stream != null) { * //use this stream, for buffer reading, or XML SAX parsing, or whatever... * } * connection.close();</pre> */ public class HttpConnection { private DefaultHttpClient client; private InputStream stream; private HttpEntity entity; private String mUserAgent; private final static int TIMEOUT_CONNECTION=3000; //ms private final static int TIMEOUT_SOCKET=8000; //ms public HttpConnection(){ stream = null; entity = null; HttpParams httpParameters = new BasicHttpParams(); /* useful? HttpProtocolParams.setContentCharset(httpParameters, "UTF-8"); HttpProtocolParams.setHttpElementCharset(httpParameters, "UTF-8"); */ // Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET); client = new DefaultHttpClient(httpParameters); //TODO: created here. Reuse to do for better perfs???... } public void setUserAgent(String userAgent){ mUserAgent = userAgent; } /** * @param sUrl url to get */ public void doGet(String sUrl){ try { HttpGet request = new HttpGet(sUrl); if (mUserAgent != null) request.setHeader("User-Agent", mUserAgent); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString()); } else { entity = response.getEntity(); } } catch (Exception e){ e.printStackTrace(); } } public void doPost(String sUrl, List<NameValuePair> nameValuePairs) { try { HttpPost request = new HttpPost(sUrl); if (mUserAgent != null) request.setHeader("User-Agent", mUserAgent); request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString()); } else { entity = response.getEntity(); } } catch (Exception e) { e.printStackTrace(); } } /** * @return the opened InputStream, or null if creation failed for any reason. */ public InputStream getStream() { try { if (entity != null) stream = entity.getContent(); } catch (IOException e) { e.printStackTrace(); } return stream; } /** * @return the whole content as a String, or null if creation failed for any reason. */ public String getContentAsString(){ try { if (entity != null) { return EntityUtils.toString(entity, "UTF-8"); //setting the charset is important if none found in the entity. } else return null; } catch (IOException e) { e.printStackTrace(); return null; } } /** * Calling close once is mandatory. */ public void close(){ if (stream != null){ try { stream.close(); stream = null; } catch (IOException e) { e.printStackTrace(); } } if (entity != null){ try { entity.consumeContent(); //"finish". Important if we want to reuse the client object one day... entity = null; } catch (IOException e) { e.printStackTrace(); } } if (client != null){ client.getConnectionManager().shutdown(); client = null; } } }
pese-git/osmbonuspack
src/main/java/org/osmdroid/bonuspack/utils/HttpConnection.java
Java
lgpl-3.0
4,625
<?php return array( // Example server configuration. You may have more arrays like this one to // specify multiple server groups (however they should share the same login // server whilst they are allowed to have multiple char/map pairs). array( 'ServerName' => 'FluxRO', // Global database configuration (excludes logs database configuration). 'DbConfig' => array( //'Socket' => '/tmp/mysql.sock', //'Port' => 3306, //'Encoding' => 'utf8', // Connection encoding -- use whatever here your MySQL tables collation is. 'Convert' => 'utf8', // -- 'Convert' option only works when 'Encoding' option is specified and iconv (http://php.net/iconv) is available. // -- It specifies the encoding to convert your MySQL data to on the website (most likely needs to be utf8) 'Hostname' => '127.0.0.1', 'Username' => 'ragnarok', 'Password' => 'ragnarok', 'Database' => 'ragnarok', 'Persistent' => true, 'Timezone' => '-3:00', //null // Example: '+0:00' is UTC. // The possible values of 'Timezone' is as documented from the MySQL website: // "The value can be given as a string indicating an offset from UTC, such as '+10:00' or '-6:00'." // "The value can be given as a named time zone, such as 'Europe/Helsinki', 'US/Eastern', or 'MET'." (see below continuation!) // **"Named time zones can be used only if the time zone information tables in the mysql database have been created and populated." ), // This is kept separate because many people choose to have their logs // database accessible under different credentials, and often on a // different server entirely to ensure the reliability of the log data. 'LogsDbConfig' => array( //'Socket' => '/tmp/mysql.sock', //'Port' => 3306, //'Encoding' => null, // Connection encoding -- use whatever here your MySQL tables collation is. 'Convert' => 'utf8', // -- 'Convert' option only works when 'Encoding' option is specified and iconv (http://php.net/iconv) is available. // -- It specifies the encoding to convert your MySQL data to on the website (most likely needs to be utf8) 'Hostname' => '127.0.0.1', 'Username' => 'ragnarok', 'Password' => 'ragnarok', 'Database' => 'ragnarok', 'Persistent' => true, 'Timezone' => null // Possible values is as described in the comment in DbConfig. ), // Login server configuration. 'LoginServer' => array( 'Address' => '127.0.0.1', 'Port' => 6900, 'UseMD5' => true, 'NoCase' => true, // rA account case-sensitivity; Default: Case-INsensitive (true). 'GroupID' => 0, // Default account group ID during registration. //'Database' => 'ragnarok' ), 'CharMapServers' => array( array( 'ServerName' => 'FluxRO', 'Renewal' => true, 'MaxCharSlots' => 9, 'DateTimezone' => 'America/Sao_Paulo', //null, // Specifies game server's timezone for this char/map pair. (See: http://php.net/timezones) 'ResetDenyMaps' => 'prontera', // Defaults to 'sec_pri'. This value can be an array of map names. //'Database' => 'ragnarok', // Defaults to DbConfig.Database 'ExpRates' => array( 'Base' => 100, // Rate at which (base) exp is given 'Job' => 100, // Rate at which job exp is given 'Mvp' => 100 // MVP bonus exp rate ), 'DropRates' => array( // The rate the common items (in the ETC tab, besides card) are dropped 'Common' => 100, 'CommonBoss' => 100, // The rate healing items (that restore HP or SP) are dropped 'Heal' => 100, 'HealBoss' => 100, // The rate usable items (in the item tab other then healing items) are dropped 'Useable' => 100, 'UseableBoss' => 100, // The rate at which equipment is dropped 'Equip' => 100, 'EquipBoss' => 100, // The rate at which cards are dropped 'Card' => 100, 'CardBoss' => 100, // The rate adjustment for the MVP items that the MVP gets directly in their inventory 'MvpItem' => 100 ), 'CharServer' => array( 'Address' => '127.0.0.1', 'Port' => 6121 ), 'MapServer' => array( 'Address' => '127.0.0.1', 'Port' => 5121 ), // -- WoE days and times -- // First parameter: Starding day 0=Sunday / 1=Monday / 2=Tuesday / 3=Wednesday / 4=Thursday / 5=Friday / 6=Saturday // Second parameter: Starting hour in 24-hr format. // Third paramter: Ending day (possible value is same as starting day). // Fourth (final) parameter: Ending hour in 24-hr format. // ** (Note, invalid times are ignored silently.) 'WoeDayTimes' => array( //array(0, '12:00', 0, '14:00'), // Example: Starts Sunday 12:00 PM and ends Sunday 2:00 PM //array(3, '14:00', 3, '15:00') // Example: Starts Wednesday 2:00 PM and ends Wednesday 3:00 PM ), // Modules and/or actions to disallow access to during WoE. 'WoeDisallow' => array( array('module' => 'character', 'action' => 'online'), // Disallow access to "Who's Online" page during WoE. array('module' => 'character', 'action' => 'mapstats') // Disallow access to "Map Statistics" page during WoE. ) ) ) ) ); ?>
JulioCF/Aeon-FluxCP
config/servers.php
PHP
lgpl-3.0
5,436
/* * Copyright (c) 2014-2015 Daniel Hrabovcak * * This file is part of Natural IDE. * * This program 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. * * 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 Lesser General Public License for more * details. **/ #include "Version.hpp" #include <cstdio> #include <cinttypes> #ifdef __MINGW32__ #ifndef SCNu8 #define SCNu8 "hhu" #endif #endif namespace natural { Version::Version() : major_(0) , minor_(0) , patch_(0) {} Version::Version(uint8_t major, uint8_t minor, uint8_t patch) : major_(major) , minor_(minor) , patch_(patch) {} Version::Version(const char *str) { uint8_t major, minor; uint16_t patch; if (sscanf(str, "%" SCNu8 ".%" SCNu8 ".%" SCNu16, &major, &minor, &patch) != 3) { Version(); return; } Version(major, minor, patch); } bool Version::compatible(const Version &other) { return (major_ == other.major_ && (minor_ < other.minor_ || (minor_ == other.minor_ && patch_ <= other.patch_))); } bool Version::forward_compatible(const Version &other) { return (major_ > other.major_ || compatible(other)); } Version Version::version() { // Must be in the `.cpp` file, so it is compiled into the shared library. return Version(NATURAL_VERSION_MAJOR, NATURAL_VERSION_MINOR, NATURAL_VERSION_PATCH); } }
TheSpiritXIII/natural-ide
src/API/Version.cpp
C++
lgpl-3.0
1,644
/* * Copyright (C) 2015 the authors * * This file is part of usb_warrior. * * usb_warrior 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. * * usb_warrior 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 usb_warrior. If not, see <http://www.gnu.org/licenses/>. */ #include "game.h" #include "image_manager.h" #include "loader.h" Loader::Loader(Game* game) : _game(game) { } void Loader::addImage(const std::string& filename) { _imageMap.emplace(filename, nullptr); } void Loader::addSound(const std::string& filename) { _soundMap.emplace(filename, nullptr); } void Loader::addMusic(const std::string& filename) { _musicMap.emplace(filename, nullptr); } void Loader::addFont(const std::string& filename) { _fontMap.emplace(filename, nullptr); } const Image* Loader::getImage(const std::string& filename) { return _imageMap.at(filename); } const Sound* Loader::getSound(const std::string& filename) { return _soundMap.at(filename); } const Music* Loader::getMusic(const std::string& filename) { return _musicMap.at(filename); } Font Loader::getFont(const std::string& filename) { return Font(_fontMap.at(filename)); } unsigned Loader::loadAll() { unsigned err = 0; for(auto& file: _imageMap) { file.second = _game->images()->loadImage(file.first); if(!file.second) { err++; } } for(auto& file: _soundMap) { file.second = _game->sounds()->loadSound(file.first); if(!file.second) { err++; } } for(auto& file: _musicMap) { file.second = _game->sounds()->loadMusic(file.first); if(!file.second) { err++; } } for(auto& file: _fontMap) { file.second = _game->fonts()->loadFont(file.first); if(!file.second) { err++; } } return err; } void Loader::releaseAll() { for(auto& file: _imageMap) { if(file.second) { _game->images()->releaseImage(file.second); file.second = nullptr; } } for(auto& file: _soundMap) { if(file.second) { _game->sounds()->releaseSound(file.second); file.second = nullptr; } } for(auto& file: _musicMap) { if(file.second) { _game->sounds()->releaseMusic(file.second); file.second = nullptr; } } for(auto& file: _fontMap) { if(file.second) { _game->fonts()->releaseFont(file.second); file.second = nullptr; } } }
draklaw/usb_warrior
src/loader.cpp
C++
lgpl-3.0
2,706
/** * Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser Public License as published by the * Free Software Foundation, either version 3.0 of the License, or (at your * option) any later version. * * EvoSuite 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License along * with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.runtime.mock.java.io; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import org.evosuite.runtime.RuntimeSettings; import org.evosuite.runtime.mock.MockFramework; import org.evosuite.runtime.mock.OverrideMock; import org.evosuite.runtime.mock.java.lang.MockIllegalArgumentException; import org.evosuite.runtime.mock.java.net.MockURL; import org.evosuite.runtime.vfs.FSObject; import org.evosuite.runtime.vfs.VFile; import org.evosuite.runtime.vfs.VFolder; import org.evosuite.runtime.vfs.VirtualFileSystem; /** * This class is used in the mocking framework to replace File instances. * * <p> * All files are created in memory, and no access to disk is ever done * * @author arcuri * */ public class MockFile extends File implements OverrideMock { private static final long serialVersionUID = -8217763202925800733L; /* * Constructors, with same inputs as in File. Note: it is not possible to inherit JavaDocs for constructors. */ public MockFile(String pathname) { super(pathname); } public MockFile(String parent, String child) { super(parent,child); } public MockFile(File parent, String child) { this(parent.getPath(),child); } public MockFile(URI uri) { super(uri); } /* * TODO: Java 7 * * there is only one method in File that depends on Java 7: * * public Path toPath() * * * but if we include it here, we will break compatibility with Java 6. * Once we drop such backward compatibility, we will need to override * such method */ /* * --------- static methods ------------------ * * recall: it is not possible to override static methods. * In the SUT, all calls to those static methods of File, eg File.foo(), * will need to be replaced with EvoFile.foo() */ public static File[] listRoots() { if(! MockFramework.isEnabled()){ return File.listRoots(); } File[] roots = File.listRoots(); MockFile[] mocks = new MockFile[roots.length]; for(int i=0; i<roots.length; i++){ mocks[i] = new MockFile(roots[i].getAbsolutePath()); } return mocks; } public static File createTempFile(String prefix, String suffix, File directory) throws IOException{ if(! MockFramework.isEnabled()){ return File.createTempFile(prefix, suffix, directory); } VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(""); String path = VirtualFileSystem.getInstance().createTempFile(prefix, suffix, directory); if(path==null){ throw new MockIOException(); } return new MockFile(path); } public static File createTempFile(String prefix, String suffix) throws IOException { return createTempFile(prefix, suffix, null); } // -------- modified methods ---------------- @Override public int compareTo(File pathname) { if(! MockFramework.isEnabled()){ return super.compareTo(pathname); } return new File(getAbsolutePath()).compareTo(pathname); } @Override public File getParentFile() { if(! MockFramework.isEnabled()){ return super.getParentFile(); } String p = this.getParent(); if (p == null) return null; return new MockFile(p); } @Override public File getAbsoluteFile() { if(! MockFramework.isEnabled()){ return super.getAbsoluteFile(); } String absPath = getAbsolutePath(); return new MockFile(absPath); } @Override public File getCanonicalFile() throws IOException { if(! MockFramework.isEnabled()){ return super.getCanonicalFile(); } String canonPath = getCanonicalPath(); VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath()); return new MockFile(canonPath); } @Override public boolean canRead() { if(! MockFramework.isEnabled()){ return super.canRead(); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } return file.isReadPermission(); } @Override public boolean setReadOnly() { if(! MockFramework.isEnabled()){ return super.setReadOnly(); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } file.setReadPermission(true); file.setExecutePermission(false); file.setWritePermission(false); return true; } @Override public boolean setReadable(boolean readable, boolean ownerOnly) { if(! MockFramework.isEnabled()){ return super.setReadable(readable, ownerOnly); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } file.setReadPermission(readable); return true; } @Override public boolean canWrite() { if(! MockFramework.isEnabled()){ return super.canWrite(); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } return file.isWritePermission(); } @Override public boolean setWritable(boolean writable, boolean ownerOnly) { if(! MockFramework.isEnabled()){ return super.setWritable(writable, ownerOnly); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } file.setWritePermission(writable); return true; } @Override public boolean setExecutable(boolean executable, boolean ownerOnly) { if(! MockFramework.isEnabled()){ return super.setExecutable(executable, ownerOnly); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } file.setExecutePermission(executable); return true; } @Override public boolean canExecute() { if(! MockFramework.isEnabled()){ return super.canExecute(); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } return file.isExecutePermission(); } @Override public boolean exists() { if(! MockFramework.isEnabled()){ return super.exists(); } return VirtualFileSystem.getInstance().exists(getAbsolutePath()); } @Override public boolean isDirectory() { if(! MockFramework.isEnabled()){ return super.isDirectory(); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } return file.isFolder(); } @Override public boolean isFile() { if(! MockFramework.isEnabled()){ return super.isFile(); } return !isDirectory(); } @Override public boolean isHidden() { if(! MockFramework.isEnabled()){ return super.isHidden(); } if(getName().startsWith(".")){ //this is not necessarily true in Windows return true; } else { return false; } } @Override public boolean setLastModified(long time) { if(! MockFramework.isEnabled()){ return super.setLastModified(time); } if (time < 0){ throw new MockIllegalArgumentException("Negative time"); } FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(target==null){ return false; } return target.setLastModified(time); } @Override public long lastModified() { if(! MockFramework.isEnabled()){ return super.lastModified(); } FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(target==null){ return 0; } return target.getLastModified(); } @Override public long length() { if(! MockFramework.isEnabled()){ return super.length(); } FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(target==null){ return 0; } if(target.isFolder() || target.isDeleted()){ return 0; } VFile file = (VFile) target; return file.getDataSize(); } //following 3 methods are never used in SF110 @Override public long getTotalSpace() { if(! MockFramework.isEnabled()){ return super.getTotalSpace(); } return 0; //TODO } @Override public long getFreeSpace() { if(! MockFramework.isEnabled()){ return super.getFreeSpace(); } return 0; //TODO } @Override public long getUsableSpace() { if(! MockFramework.isEnabled()){ return super.getUsableSpace(); } return 0; //TODO } @Override public boolean createNewFile() throws IOException { if(! MockFramework.isEnabled()){ return super.createNewFile(); } VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath()); return VirtualFileSystem.getInstance().createFile(getAbsolutePath()); } @Override public boolean delete() { if(! MockFramework.isEnabled()){ return super.delete(); } return VirtualFileSystem.getInstance().deleteFSObject(getAbsolutePath()); } @Override public boolean renameTo(File dest) { if(! MockFramework.isEnabled()){ return super.renameTo(dest); } boolean renamed = VirtualFileSystem.getInstance().rename( this.getAbsolutePath(), dest.getAbsolutePath()); return renamed; } @Override public boolean mkdir() { if(! MockFramework.isEnabled()){ return super.mkdir(); } String parent = this.getParent(); if(parent==null || !VirtualFileSystem.getInstance().exists(parent)){ return false; } return VirtualFileSystem.getInstance().createFolder(getAbsolutePath()); } @Override public void deleteOnExit() { if(! MockFramework.isEnabled()){ super.deleteOnExit(); } /* * do nothing, as anyway no actual file is created */ } @Override public String[] list() { if(! MockFramework.isEnabled()){ return super.list(); } if(!isDirectory() || !exists()){ return null; } else { VFolder dir = (VFolder) VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); return dir.getChildrenNames(); } } @Override public File[] listFiles() { if(! MockFramework.isEnabled()){ return super.listFiles(); } String[] ss = list(); if (ss == null) return null; int n = ss.length; MockFile[] fs = new MockFile[n]; for (int i = 0; i < n; i++) { fs[i] = new MockFile(this,ss[i]); } return fs; } @Override public File[] listFiles(FileFilter filter) { if(! MockFramework.isEnabled()){ return super.listFiles(filter); } String ss[] = list(); if (ss == null) return null; ArrayList<File> files = new ArrayList<File>(); for (String s : ss) { File f = new MockFile(this,s); if ((filter == null) || filter.accept(f)) files.add(f); } return files.toArray(new File[files.size()]); } @Override public String getCanonicalPath() throws IOException { if(! MockFramework.isEnabled()){ return super.getCanonicalPath(); } VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath()); return super.getCanonicalPath(); } @Override public URL toURL() throws MalformedURLException { if(! MockFramework.isEnabled() || !RuntimeSettings.useVNET){ return super.toURL(); } URL url = super.toURL(); return MockURL.URL(url.toString()); } // -------- unmodified methods -------------- @Override public String getName(){ return super.getName(); } @Override public String getParent() { return super.getParent(); } @Override public String getPath() { return super.getPath(); } @Override public boolean isAbsolute() { return super.isAbsolute(); } @Override public String getAbsolutePath() { return super.getAbsolutePath(); } @Override public URI toURI() { return super.toURI(); //no need of VNET here } @Override public String[] list(FilenameFilter filter) { //no need to mock it, as it uses the mocked list() return super.list(filter); } @Override public boolean mkdirs() { //no need to mock it, as all methods it calls are mocked return super.mkdirs(); } @Override public boolean setWritable(boolean writable) { return super.setWritable(writable); // it calls mocked method } @Override public boolean setReadable(boolean readable) { return super.setReadable(readable); //it calls mocked method } @Override public boolean setExecutable(boolean executable) { return super.setExecutable(executable); // it calls mocked method } // ------- Object methods ----------- @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } @Override public String toString() { return super.toString(); } }
SoftwareEngineeringToolDemos/FSE-2011-EvoSuite
runtime/src/main/java/org/evosuite/runtime/mock/java/io/MockFile.java
Java
lgpl-3.0
13,402
""" Copyright (C) 2013 Matthew Woodruff This script 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. This script is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this script. If not, see <http://www.gnu.org/licenses/>. =========================================================== Coming in: one of 36 algo/problem combinations. 50 seeds in one file. Also the _Sobol file specifying the parameterization for each row, as well as the parameters file itself. Going out: stats: mean, quantile, variance grouped by parameterization grouped by some or all 2d combinations of parameters """ import argparse import pandas import numpy import re import os import copy def is_quantile(stat): return re.match("q[0-9][0-9]?$", stat) def is_stat(stat): if stat in ["mean", "variance", "min", "max", "q100"]: return stat elif is_quantile(stat): return stat else: raise argparse.ArgumentTypeError( "Invalid statistic {0}".format(stat)) def get_args(): parser = argparse.ArgumentParser() parser.add_argument("data", type=argparse.FileType("r"), help="data file to be summarized." "Should have columns seed, "\ "set, and metrics columns.") parser.add_argument("parameterizations", type=argparse.FileType("r"), help="file containing parameter"\ "izations. Number of param"\ "eterizations should be the "\ "same as number of rows per "\ "seed in the data file." ) parser.add_argument("parameters", type=argparse.FileType("r"), help="file describing parameters. "\ "Should have as many rows as "\ "parameterizations file has "\ "columns." ) stats = ["mean", "variance", "q10", "q50", "q90"] parser.add_argument("-s", "--stats", nargs="+", default = stats, type = is_stat, help="statistics to compute") parser.add_argument("-g", "--group", nargs="+", help="parameters by which to "\ "group. Names should be "\ "found in the parameters "\ "file. " ) parser.add_argument("-d", "--deltas", help="If group is specified, "\ "deltas may be used to impose "\ "grid boxes on the summary "\ "rather than using point "\ "values.", nargs="+", type = float ) parser.add_argument("-o", "--output-directory", default="/gpfs/scratch/mjw5407/" "task1/stats/" ) return parser.parse_args() def compute(data, stat): if stat == "mean": return data.mean() if stat == "variance": return data.var() if is_quantile(stat): quantile = float(stat[1:]) / 100.0 if quantile == 0.0: return data.min() return data.quantile(quantile) if stat == "max" or stat == "q100": return data.max() if stat == "min": return data.min() def analyze(data, stats, group=None, deltas=None): results = [] if group is None: group = ["Set"] togroupby = copy.copy(group) ii = 0 if deltas is None: togroupby = group else: while ii < len(group) and ii < len(deltas): colname = "grid_{0}".format(group[ii]) gridnumbers = numpy.floor(data[group[ii]].apply( lambda val: val / deltas[ii])) data[colname] = gridnumbers.apply( lambda val: val * deltas[ii]) togroupby[ii] = colname ii += 1 print "analyzing grouped by {0}".format(group) gb = data.groupby(togroupby) for stat in stats: print "computing {0}".format(stat) tag = "{0}_{1}".format("_".join(group), stat) results.append((tag, compute(gb, stat))) return results def write_result(infn, result, outputdir): fn = "_".join([result[0], os.path.basename(infn)]) fn = re.sub("\.hv$", "", fn) fn = os.path.join(outputdir, fn) print "writing {0}".format(fn) result[1].to_csv(fn, sep=" ", index=True) def cli(): args = get_args() data = pandas.read_table(args.data, sep=" ") parameters = pandas.read_table( args.parameters, sep=" ", names=["name","low","high"], header=None) param_names = parameters["name"].values parameterizations = pandas.read_table( args.parameterizations, sep=" ", names = param_names, header = None) data = data.join(parameterizations, on=["Set"], how="outer") if args.deltas is not None: deltas = args.deltas else: deltas = [] results = analyze(data, args.stats, args.group, deltas) for result in results: write_result(args.data.name, result, args.output_directory) if __name__ == "__main__": cli() # vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
matthewjwoodruff/moeasensitivity
statistics/statistics.py
Python
lgpl-3.0
6,225
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package optas.gui.wizard; /** * * @author chris */ public class ComponentWrapper { public String componentName; public String componentContext; public boolean contextComponent; public ComponentWrapper(String componentName, String componentContext, boolean contextComponent) { this.componentContext = componentContext; this.componentName = componentName; this.contextComponent = contextComponent; } @Override public String toString() { if (contextComponent) { return componentName; } return /*componentContext + "." + */ componentName; } }
kralisch/jams
JAMSOptas/src/optas/gui/wizard/ComponentWrapper.java
Java
lgpl-3.0
738
package org.jta.testspringhateoas.hello; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*; @RestController public class GreetingController { private static final String TEMPLATE = "Hello, %s!"; @RequestMapping("/greeting") public HttpEntity<Greeting> greeting( @RequestParam(value = "name", required = false, defaultValue = "World") String name) { Greeting greeting = new Greeting(String.format(TEMPLATE, name)); greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)).withSelfRel()); return new ResponseEntity<Greeting>(greeting, HttpStatus.OK); } }
javiertoja/SpringBoot
testSpringHateoas/src/main/java/org/jta/testspringhateoas/hello/GreetingController.java
Java
lgpl-3.0
970
/* * This file is part of RskJ * Copyright (C) 2019 RSK Labs Ltd. * (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>) * * This program 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. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.rsk.pcc.blockheader; import co.rsk.pcc.ExecutionEnvironment; import org.ethereum.core.Block; import org.ethereum.core.CallTransaction; /** * This implements the "getCoinbaseAddress" method * that belongs to the BlockHeaderContract native contract. * * @author Diego Masini */ public class GetCoinbaseAddress extends BlockHeaderContractMethod { private final CallTransaction.Function function = CallTransaction.Function.fromSignature( "getCoinbaseAddress", new String[]{"int256"}, new String[]{"bytes"} ); public GetCoinbaseAddress(ExecutionEnvironment executionEnvironment, BlockAccessor blockAccessor) { super(executionEnvironment, blockAccessor); } @Override public CallTransaction.Function getFunction() { return function; } @Override protected Object internalExecute(Block block, Object[] arguments) { return block.getCoinbase().getBytes(); } }
rsksmart/rskj
rskj-core/src/main/java/co/rsk/pcc/blockheader/GetCoinbaseAddress.java
Java
lgpl-3.0
1,780
/** * Copyright (C) 2010-2017 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite 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.0 of the License, or * (at your option) any later version. * * EvoSuite 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 Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.symbolic.vm; import org.evosuite.symbolic.expr.fp.RealValue; /** * * @author galeotti * */ public final class Fp64Operand implements DoubleWordOperand, RealOperand { private final RealValue realExpr; public Fp64Operand(RealValue realExpr) { this.realExpr = realExpr; } public RealValue getRealExpression() { return realExpr; } @Override public String toString() { return realExpr.toString(); } }
sefaakca/EvoSuite-Sefa
client/src/main/java/org/evosuite/symbolic/vm/Fp64Operand.java
Java
lgpl-3.0
1,222
<?php /* * Copyright (c) 2012-2016, Hofmänner New Media. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This file is part of the N2N FRAMEWORK. * * The N2N FRAMEWORK 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 2.1 of the License, or (at your option) any later version. * * N2N 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: http://www.gnu.org/licenses/ * * The following people participated in this project: * * Andreas von Burg.....: Architect, Lead Developer * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing * Thomas Günther.......: Developer, Hangar */ namespace n2n\web\dispatch\target; class PropertyPathMissmatchException extends DispatchTargetException { }
n2n/n2n-web
src/app/n2n/web/dispatch/target/PropertyPathMissmatchException.php
PHP
lgpl-3.0
1,080
/******************************************************************************** ** ** Copyright (C) 2016-2021 Pavel Pavlov. ** ** ** This file is part of SprintTimer. ** ** SprintTimer 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. ** ** SprintTimer 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 SprintTimer. If not, see <http://www.gnu.org/licenses/>. ** *********************************************************************************/ #include "core/use_cases/SprintMapper.h" namespace sprint_timer::use_cases { SprintDTO makeDTO(const entities::Sprint& sprint) { const auto& tagsEnt = sprint.tags(); std::vector<std::string> tags(tagsEnt.size()); std::transform(cbegin(tagsEnt), cend(tagsEnt), begin(tags), [](const auto& elem) { return elem.name(); }); return SprintDTO{sprint.uuid(), sprint.taskUuid(), sprint.name(), tags, sprint.timeSpan()}; } entities::Sprint fromDTO(const SprintDTO& dto) { const auto& tagStr = dto.tags; std::list<entities::Tag> tags(tagStr.size()); std::transform(cbegin(tagStr), cend(tagStr), begin(tags), [](const auto& elem) { return entities::Tag{elem}; }); return entities::Sprint{ dto.taskName, dto.timeRange, tags, dto.uuid, dto.taskUuid}; } std::vector<SprintDTO> makeDTOs(const std::vector<entities::Sprint>& sprints) { std::vector<SprintDTO> res; res.reserve(sprints.size()); makeDTOs(cbegin(sprints), cend(sprints), std::back_inserter(res)); return res; } std::vector<entities::Sprint> fromDTOs(const std::vector<SprintDTO>& dtos) { std::vector<entities::Sprint> res; res.reserve(dtos.size()); fromDTOs(cbegin(dtos), cend(dtos), std::back_inserter(res)); return res; } } // namespace sprint_timer::use_cases
ravenvz/SprintTimer
src/core/src/use_cases/SprintMapper.cpp
C++
lgpl-3.0
2,408
package org.toughradius.handler; public interface RadiusConstant { public final static String VENDOR_TOUGHSOCKS = "18168"; public final static String VENDOR_MIKROTIK = "14988"; public final static String VENDOR_IKUAI = "10055"; public final static String VENDOR_HUAWEI = "2011"; public final static String VENDOR_ZTE = "3902"; public final static String VENDOR_H3C = "25506"; public final static String VENDOR_RADBACK = "2352"; public final static String VENDOR_CISCO = "9"; }
talkincode/ToughRADIUS
src/main/java/org/toughradius/handler/RadiusConstant.java
Java
lgpl-3.0
512
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program 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. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ /** * Task scheduling related classes */ namespace pocketmine\scheduler; use pocketmine\plugin\Plugin; use pocketmine\Server; use pocketmine\utils\MainLogger; use pocketmine\utils\PluginException; use pocketmine\utils\ReversePriorityQueue; class ServerScheduler{ public static $WORKERS = 2; /** * @var ReversePriorityQueue<Task> */ protected $queue; /** * @var TaskHandler[] */ protected $tasks = []; /** @var AsyncPool */ protected $asyncPool; /** @var int */ private $ids = 1; /** @var int */ protected $currentTick = 0; public function __construct(){ $this->queue = new ReversePriorityQueue(); $this->asyncPool = new AsyncPool(Server::getInstance(), self::$WORKERS); } /** * @param Task $task * * @return null|TaskHandler */ public function scheduleTask(Task $task){ return $this->addTask($task, -1, -1); } /** * Submits an asynchronous task to the Worker Pool * * @param AsyncTask $task * * @return void */ public function scheduleAsyncTask(AsyncTask $task){ $id = $this->nextId(); $task->setTaskId($id); $this->asyncPool->submitTask($task); } /** * Submits an asynchronous task to a specific Worker in the Pool * * @param AsyncTask $task * @param int $worker * * @return void */ public function scheduleAsyncTaskToWorker(AsyncTask $task, $worker){ $id = $this->nextId(); $task->setTaskId($id); $this->asyncPool->submitTaskToWorker($task, $worker); } public function getAsyncTaskPoolSize(){ return $this->asyncPool->getSize(); } public function increaseAsyncTaskPoolSize($newSize){ $this->asyncPool->increaseSize($newSize); } /** * @param Task $task * @param int $delay * * @return null|TaskHandler */ public function scheduleDelayedTask(Task $task, $delay){ return $this->addTask($task, (int) $delay, -1); } /** * @param Task $task * @param int $period * * @return null|TaskHandler */ public function scheduleRepeatingTask(Task $task, $period){ return $this->addTask($task, -1, (int) $period); } /** * @param Task $task * @param int $delay * @param int $period * * @return null|TaskHandler */ public function scheduleDelayedRepeatingTask(Task $task, $delay, $period){ return $this->addTask($task, (int) $delay, (int) $period); } /** * @param int $taskId */ public function cancelTask($taskId){ if($taskId !== \null and isset($this->tasks[$taskId])){ $this->tasks[$taskId]->cancel(); unset($this->tasks[$taskId]); } } /** * @param Plugin $plugin */ public function cancelTasks(Plugin $plugin){ foreach($this->tasks as $taskId => $task){ $ptask = $task->getTask(); if($ptask instanceof PluginTask and $ptask->getOwner() === $plugin){ $task->cancel(); unset($this->tasks[$taskId]); } } } public function cancelAllTasks(){ foreach($this->tasks as $task){ $task->cancel(); } $this->tasks = []; $this->asyncPool->removeTasks(); $this->queue = new ReversePriorityQueue(); $this->ids = 1; } /** * @param int $taskId * * @return bool */ public function isQueued($taskId){ return isset($this->tasks[$taskId]); } /** * @param Task $task * @param $delay * @param $period * * @return null|TaskHandler * * @throws PluginException */ private function addTask(Task $task, $delay, $period){ if($task instanceof PluginTask){ if(!($task->getOwner() instanceof Plugin)){ throw new PluginException("Invalid owner of PluginTask " . \get_class($task)); }elseif(!$task->getOwner()->isEnabled()){ throw new PluginException("Plugin '" . $task->getOwner()->getName() . "' attempted to register a task while disabled"); } }elseif($task instanceof CallbackTask and Server::getInstance()->getProperty("settings.deprecated-verbose", \true)){ $callable = $task->getCallable(); if(\is_array($callable)){ if(\is_object($callable[0])){ $taskName = "Callback#" . \get_class($callable[0]) . "::" . $callable[1]; }else{ $taskName = "Callback#" . $callable[0] . "::" . $callable[1]; } }else{ $taskName = "Callback#" . $callable; } Server::getInstance()->getLogger()->warning("A plugin attempted to register a deprecated CallbackTask ($taskName)"); } if($delay <= 0){ $delay = -1; } if($period <= -1){ $period = -1; }elseif($period < 1){ $period = 1; } return $this->handle(new TaskHandler(\get_class($task), $task, $this->nextId(), $delay, $period)); } private function handle(TaskHandler $handler){ if($handler->isDelayed()){ $nextRun = $this->currentTick + $handler->getDelay(); }else{ $nextRun = $this->currentTick; } $handler->setNextRun($nextRun); $this->tasks[$handler->getTaskId()] = $handler; $this->queue->insert($handler, $nextRun); return $handler; } /** * @param int $currentTick */ public function mainThreadHeartbeat($currentTick){ $this->currentTick = $currentTick; while($this->isReady($this->currentTick)){ /** @var TaskHandler $task */ $task = $this->queue->extract(); if($task->isCancelled()){ unset($this->tasks[$task->getTaskId()]); continue; }else{ $task->timings->startTiming(); try{ $task->run($this->currentTick); }catch(\Exception $e){ Server::getInstance()->getLogger()->critical("Could not execute task " . $task->getTaskName() . ": " . $e->getMessage()); $logger = Server::getInstance()->getLogger(); if($logger instanceof MainLogger){ $logger->logException($e); } } $task->timings->stopTiming(); } if($task->isRepeating()){ $task->setNextRun($this->currentTick + $task->getPeriod()); $this->queue->insert($task, $this->currentTick + $task->getPeriod()); }else{ $task->remove(); unset($this->tasks[$task->getTaskId()]); } } $this->asyncPool->collectTasks(); } private function isReady($currentTicks){ return \count($this->tasks) > 0 and $this->queue->current()->getNextRun() <= $currentTicks; } /** * @return int */ private function nextId(){ return $this->ids++; } }
ZenaGamingsky/PocketBox
src/pocketmine/scheduler/ServerScheduler.php
PHP
lgpl-3.0
6,789
// 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 contains data types related to Ethereum consensus. package types import ( "encoding/binary" "encoding/json" "errors" "fmt" "io" "math/big" "sort" "sync/atomic" "time" "github.com/kejace/go-ethereum/common" "github.com/kejace/go-ethereum/crypto/sha3" "github.com/kejace/go-ethereum/rlp" ) var ( EmptyRootHash = DeriveSha(Transactions{}) EmptyUncleHash = CalcUncleHash(nil) ) var ( errMissingHeaderMixDigest = errors.New("missing mixHash in JSON block header") errMissingHeaderFields = errors.New("missing required JSON block header fields") errBadNonceSize = errors.New("invalid block nonce size, want 8 bytes") ) // A BlockNonce is a 64-bit hash which proves (combined with the // mix-hash) that a sufficient amount of computation has been carried // out on a block. type BlockNonce [8]byte // EncodeNonce converts the given integer to a block nonce. func EncodeNonce(i uint64) BlockNonce { var n BlockNonce binary.BigEndian.PutUint64(n[:], i) return n } // Uint64 returns the integer value of a block nonce. func (n BlockNonce) Uint64() uint64 { return binary.BigEndian.Uint64(n[:]) } // MarshalJSON implements json.Marshaler func (n BlockNonce) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf(`"0x%x"`, n)), nil } // UnmarshalJSON implements json.Unmarshaler func (n *BlockNonce) UnmarshalJSON(input []byte) error { var b hexBytes if err := b.UnmarshalJSON(input); err != nil { return err } if len(b) != 8 { return errBadNonceSize } copy((*n)[:], b) return nil } // Header represents a block header in the Ethereum blockchain. type Header struct { ParentHash common.Hash // Hash to the previous block UncleHash common.Hash // Uncles of this block Coinbase common.Address // The coin base address Root common.Hash // Block Trie state TxHash common.Hash // Tx sha ReceiptHash common.Hash // Receipt sha Bloom Bloom // Bloom Difficulty *big.Int // Difficulty for the current block Number *big.Int // The block number GasLimit *big.Int // Gas limit GasUsed *big.Int // Gas used Time *big.Int // Creation time Extra []byte // Extra data MixDigest common.Hash // for quick difficulty verification Nonce BlockNonce } type jsonHeader struct { ParentHash *common.Hash `json:"parentHash"` UncleHash *common.Hash `json:"sha3Uncles"` Coinbase *common.Address `json:"miner"` Root *common.Hash `json:"stateRoot"` TxHash *common.Hash `json:"transactionsRoot"` ReceiptHash *common.Hash `json:"receiptsRoot"` Bloom *Bloom `json:"logsBloom"` Difficulty *hexBig `json:"difficulty"` Number *hexBig `json:"number"` GasLimit *hexBig `json:"gasLimit"` GasUsed *hexBig `json:"gasUsed"` Time *hexBig `json:"timestamp"` Extra *hexBytes `json:"extraData"` MixDigest *common.Hash `json:"mixHash"` Nonce *BlockNonce `json:"nonce"` } // Hash returns the block hash of the header, which is simply the keccak256 hash of its // RLP encoding. func (h *Header) Hash() common.Hash { return rlpHash(h) } // HashNoNonce returns the hash which is used as input for the proof-of-work search. func (h *Header) HashNoNonce() common.Hash { return rlpHash([]interface{}{ h.ParentHash, h.UncleHash, h.Coinbase, h.Root, h.TxHash, h.ReceiptHash, h.Bloom, h.Difficulty, h.Number, h.GasLimit, h.GasUsed, h.Time, h.Extra, }) } // MarshalJSON encodes headers into the web3 RPC response block format. func (h *Header) MarshalJSON() ([]byte, error) { return json.Marshal(&jsonHeader{ ParentHash: &h.ParentHash, UncleHash: &h.UncleHash, Coinbase: &h.Coinbase, Root: &h.Root, TxHash: &h.TxHash, ReceiptHash: &h.ReceiptHash, Bloom: &h.Bloom, Difficulty: (*hexBig)(h.Difficulty), Number: (*hexBig)(h.Number), GasLimit: (*hexBig)(h.GasLimit), GasUsed: (*hexBig)(h.GasUsed), Time: (*hexBig)(h.Time), Extra: (*hexBytes)(&h.Extra), MixDigest: &h.MixDigest, Nonce: &h.Nonce, }) } // UnmarshalJSON decodes headers from the web3 RPC response block format. func (h *Header) UnmarshalJSON(input []byte) error { var dec jsonHeader if err := json.Unmarshal(input, &dec); err != nil { return err } // Ensure that all fields are set. MixDigest is checked separately because // it is a recent addition to the spec (as of August 2016) and older RPC server // implementations might not provide it. if dec.MixDigest == nil { return errMissingHeaderMixDigest } if dec.ParentHash == nil || dec.UncleHash == nil || dec.Coinbase == nil || dec.Root == nil || dec.TxHash == nil || dec.ReceiptHash == nil || dec.Bloom == nil || dec.Difficulty == nil || dec.Number == nil || dec.GasLimit == nil || dec.GasUsed == nil || dec.Time == nil || dec.Extra == nil || dec.Nonce == nil { return errMissingHeaderFields } // Assign all values. h.ParentHash = *dec.ParentHash h.UncleHash = *dec.UncleHash h.Coinbase = *dec.Coinbase h.Root = *dec.Root h.TxHash = *dec.TxHash h.ReceiptHash = *dec.ReceiptHash h.Bloom = *dec.Bloom h.Difficulty = (*big.Int)(dec.Difficulty) h.Number = (*big.Int)(dec.Number) h.GasLimit = (*big.Int)(dec.GasLimit) h.GasUsed = (*big.Int)(dec.GasUsed) h.Time = (*big.Int)(dec.Time) h.Extra = *dec.Extra h.MixDigest = *dec.MixDigest h.Nonce = *dec.Nonce return nil } func rlpHash(x interface{}) (h common.Hash) { hw := sha3.NewKeccak256() rlp.Encode(hw, x) hw.Sum(h[:0]) return h } // Body is a simple (mutable, non-safe) data container for storing and moving // a block's data contents (transactions and uncles) together. type Body struct { Transactions []*Transaction Uncles []*Header } // Block represents an entire block in the Ethereum blockchain. type Block struct { header *Header uncles []*Header transactions Transactions // caches hash atomic.Value size atomic.Value // Td is used by package core to store the total difficulty // of the chain up to and including the block. td *big.Int // These fields are used by package eth to track // inter-peer block relay. ReceivedAt time.Time ReceivedFrom interface{} } // DeprecatedTd is an old relic for extracting the TD of a block. It is in the // code solely to facilitate upgrading the database from the old format to the // new, after which it should be deleted. Do not use! func (b *Block) DeprecatedTd() *big.Int { return b.td } // [deprecated by eth/63] // StorageBlock defines the RLP encoding of a Block stored in the // state database. The StorageBlock encoding contains fields that // would otherwise need to be recomputed. type StorageBlock Block // "external" block encoding. used for eth protocol, etc. type extblock struct { Header *Header Txs []*Transaction Uncles []*Header } // [deprecated by eth/63] // "storage" block encoding. used for database. type storageblock struct { Header *Header Txs []*Transaction Uncles []*Header TD *big.Int } // NewBlock creates a new block. The input data is copied, // changes to header and to the field values will not affect the // block. // // The values of TxHash, UncleHash, ReceiptHash and Bloom in header // are ignored and set to values derived from the given txs, uncles // and receipts. func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt) *Block { b := &Block{header: CopyHeader(header), td: new(big.Int)} // TODO: panic if len(txs) != len(receipts) if len(txs) == 0 { b.header.TxHash = EmptyRootHash } else { b.header.TxHash = DeriveSha(Transactions(txs)) b.transactions = make(Transactions, len(txs)) copy(b.transactions, txs) } if len(receipts) == 0 { b.header.ReceiptHash = EmptyRootHash } else { b.header.ReceiptHash = DeriveSha(Receipts(receipts)) b.header.Bloom = CreateBloom(receipts) } if len(uncles) == 0 { b.header.UncleHash = EmptyUncleHash } else { b.header.UncleHash = CalcUncleHash(uncles) b.uncles = make([]*Header, len(uncles)) for i := range uncles { b.uncles[i] = CopyHeader(uncles[i]) } } return b } // NewBlockWithHeader creates a block with the given header data. The // header data is copied, changes to header and to the field values // will not affect the block. func NewBlockWithHeader(header *Header) *Block { return &Block{header: CopyHeader(header)} } // CopyHeader creates a deep copy of a block header to prevent side effects from // modifying a header variable. func CopyHeader(h *Header) *Header { cpy := *h if cpy.Time = new(big.Int); h.Time != nil { cpy.Time.Set(h.Time) } if cpy.Difficulty = new(big.Int); h.Difficulty != nil { cpy.Difficulty.Set(h.Difficulty) } if cpy.Number = new(big.Int); h.Number != nil { cpy.Number.Set(h.Number) } if cpy.GasLimit = new(big.Int); h.GasLimit != nil { cpy.GasLimit.Set(h.GasLimit) } if cpy.GasUsed = new(big.Int); h.GasUsed != nil { cpy.GasUsed.Set(h.GasUsed) } if len(h.Extra) > 0 { cpy.Extra = make([]byte, len(h.Extra)) copy(cpy.Extra, h.Extra) } return &cpy } // DecodeRLP decodes the Ethereum func (b *Block) DecodeRLP(s *rlp.Stream) error { var eb extblock _, size, _ := s.Kind() if err := s.Decode(&eb); err != nil { return err } b.header, b.uncles, b.transactions = eb.Header, eb.Uncles, eb.Txs b.size.Store(common.StorageSize(rlp.ListSize(size))) return nil } // EncodeRLP serializes b into the Ethereum RLP block format. func (b *Block) EncodeRLP(w io.Writer) error { return rlp.Encode(w, extblock{ Header: b.header, Txs: b.transactions, Uncles: b.uncles, }) } // [deprecated by eth/63] func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error { var sb storageblock if err := s.Decode(&sb); err != nil { return err } b.header, b.uncles, b.transactions, b.td = sb.Header, sb.Uncles, sb.Txs, sb.TD return nil } // TODO: copies func (b *Block) Uncles() []*Header { return b.uncles } func (b *Block) Transactions() Transactions { return b.transactions } func (b *Block) Transaction(hash common.Hash) *Transaction { for _, transaction := range b.transactions { if transaction.Hash() == hash { return transaction } } return nil } func (b *Block) Number() *big.Int { return new(big.Int).Set(b.header.Number) } func (b *Block) GasLimit() *big.Int { return new(big.Int).Set(b.header.GasLimit) } func (b *Block) GasUsed() *big.Int { return new(big.Int).Set(b.header.GasUsed) } func (b *Block) Difficulty() *big.Int { return new(big.Int).Set(b.header.Difficulty) } func (b *Block) Time() *big.Int { return new(big.Int).Set(b.header.Time) } func (b *Block) NumberU64() uint64 { return b.header.Number.Uint64() } func (b *Block) MixDigest() common.Hash { return b.header.MixDigest } func (b *Block) Nonce() uint64 { return binary.BigEndian.Uint64(b.header.Nonce[:]) } func (b *Block) Bloom() Bloom { return b.header.Bloom } func (b *Block) Coinbase() common.Address { return b.header.Coinbase } func (b *Block) Root() common.Hash { return b.header.Root } func (b *Block) ParentHash() common.Hash { return b.header.ParentHash } func (b *Block) TxHash() common.Hash { return b.header.TxHash } func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash } func (b *Block) UncleHash() common.Hash { return b.header.UncleHash } func (b *Block) Extra() []byte { return common.CopyBytes(b.header.Extra) } func (b *Block) Header() *Header { return CopyHeader(b.header) } // Body returns the non-header content of the block. func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles} } func (b *Block) HashNoNonce() common.Hash { return b.header.HashNoNonce() } func (b *Block) Size() common.StorageSize { if size := b.size.Load(); size != nil { return size.(common.StorageSize) } c := writeCounter(0) rlp.Encode(&c, b) b.size.Store(common.StorageSize(c)) return common.StorageSize(c) } type writeCounter common.StorageSize func (c *writeCounter) Write(b []byte) (int, error) { *c += writeCounter(len(b)) return len(b), nil } func CalcUncleHash(uncles []*Header) common.Hash { return rlpHash(uncles) } // WithMiningResult returns a new block with the data from b // where nonce and mix digest are set to the provided values. func (b *Block) WithMiningResult(nonce uint64, mixDigest common.Hash) *Block { cpy := *b.header binary.BigEndian.PutUint64(cpy.Nonce[:], nonce) cpy.MixDigest = mixDigest return &Block{ header: &cpy, transactions: b.transactions, uncles: b.uncles, } } // WithBody returns a new block with the given transaction and uncle contents. func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block { block := &Block{ header: CopyHeader(b.header), transactions: make([]*Transaction, len(transactions)), uncles: make([]*Header, len(uncles)), } copy(block.transactions, transactions) for i := range uncles { block.uncles[i] = CopyHeader(uncles[i]) } return block } // Hash returns the keccak256 hash of b's header. // The hash is computed on the first call and cached thereafter. func (b *Block) Hash() common.Hash { if hash := b.hash.Load(); hash != nil { return hash.(common.Hash) } v := rlpHash(b.header) b.hash.Store(v) return v } func (b *Block) String() string { str := fmt.Sprintf(`Block(#%v): Size: %v { MinerHash: %x %v Transactions: %v Uncles: %v } `, b.Number(), b.Size(), b.header.HashNoNonce(), b.header, b.transactions, b.uncles) return str } func (h *Header) String() string { return fmt.Sprintf(`Header(%x): [ ParentHash: %x UncleHash: %x Coinbase: %x Root: %x TxSha %x ReceiptSha: %x Bloom: %x Difficulty: %v Number: %v GasLimit: %v GasUsed: %v Time: %v Extra: %s MixDigest: %x Nonce: %x ]`, h.Hash(), h.ParentHash, h.UncleHash, h.Coinbase, h.Root, h.TxHash, h.ReceiptHash, h.Bloom, h.Difficulty, h.Number, h.GasLimit, h.GasUsed, h.Time, h.Extra, h.MixDigest, h.Nonce) } type Blocks []*Block type BlockBy func(b1, b2 *Block) bool func (self BlockBy) Sort(blocks Blocks) { bs := blockSorter{ blocks: blocks, by: self, } sort.Sort(bs) } type blockSorter struct { blocks Blocks by func(b1, b2 *Block) bool } func (self blockSorter) Len() int { return len(self.blocks) } func (self blockSorter) Swap(i, j int) { self.blocks[i], self.blocks[j] = self.blocks[j], self.blocks[i] } func (self blockSorter) Less(i, j int) bool { return self.by(self.blocks[i], self.blocks[j]) } func Number(b1, b2 *Block) bool { return b1.header.Number.Cmp(b2.header.Number) < 0 }
kejace/go-ethereum
core/types/block.go
GO
lgpl-3.0
15,560
<?php $model = new waModel(); try { $model->query("SELECT parent_id FROM contacts_view WHERE 0"); $model->exec("ALTER TABLE contacts_view DROP parent_id"); } catch (waException $e) { }
RomanNosov/convershop
wa-apps/contacts/plugins/pro/lib/updates/dev/1401451115.php
PHP
lgpl-3.0
198
import os import platform from setuptools import setup, Extension from distutils.util import convert_path from Cython.Build import cythonize system = platform.system() ## paths settings # Linux if 'Linux' in system: CLFFT_DIR = r'/home/gregor/devel/clFFT' CLFFT_LIB_DIRS = [r'/usr/local/lib64'] CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'src', 'include'), ] CL_INCL_DIRS = ['/opt/AMDAPPSDK-3.0/include'] EXTRA_COMPILE_ARGS = [] EXTRA_LINK_ARGS = [] #Windows elif 'Windows' in system: CLFFT_DIR = r'C:\Users\admin\Devel\clFFT-Full-2.12.2-Windows-x64' CLFFT_LIB_DIRS = [os.path.join(CLFFT_DIR, 'lib64\import')] CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'include'), ] CL_DIR = os.getenv('AMDAPPSDKROOT') CL_INCL_DIRS = [os.path.join(CL_DIR, 'include')] EXTRA_COMPILE_ARGS = [] EXTRA_LINK_ARGS = [] # macOS elif 'Darwin' in system: CLFFT_DIR = r'/Users/gregor/Devel/clFFT' CLFFT_LIB_DIRS = [r'/Users/gregor/Devel/clFFT/src/library'] CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'src', 'include'), ] CL_INCL_DIRS = [] EXTRA_COMPILE_ARGS = ['-stdlib=libc++'] EXTRA_LINK_ARGS = ['-stdlib=libc++'] import Cython.Compiler.Options Cython.Compiler.Options.generate_cleanup_code = 2 extensions = [ Extension("gpyfft.gpyfftlib", [os.path.join('gpyfft', 'gpyfftlib.pyx')], include_dirs= CLFFT_INCL_DIRS + CL_INCL_DIRS, extra_compile_args=EXTRA_COMPILE_ARGS, extra_link_args=EXTRA_LINK_ARGS, libraries=['clFFT'], library_dirs = CLFFT_LIB_DIRS, language='c++', ) ] def copy_clfftdll_to_package(): import shutil shutil.copy( os.path.join(CLFFT_DIR, 'bin', 'clFFT.dll'), 'gpyfft') shutil.copy( os.path.join(CLFFT_DIR, 'bin', 'StatTimer.dll'), 'gpyfft') print("copied clFFT.dll, StatTimer.dll") package_data = {} if 'Windows' in platform.system(): copy_clfftdll_to_package() package_data.update({'gpyfft': ['clFFT.dll', 'StatTimer.dll']},) def get_version(): main_ns = {} version_path = convert_path('gpyfft/version.py') with open(version_path) as version_file: exec(version_file.read(), main_ns) version = main_ns['__version__'] return version def get_readme(): dirname = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(dirname, "README.md"), "r") as fp: long_description = fp.read() return long_description install_requires = ["numpy", "pyopencl"] setup_requires = ["numpy", "cython"] setup( name='gpyfft', version=get_version(), description='A Python wrapper for the OpenCL FFT library clFFT', long_description=get_readme(), url=r"https://github.com/geggo/gpyfft", maintainer='Gregor Thalhammer', maintainer_email='gregor.thalhammer@gmail.com', license='LGPL', packages=['gpyfft', "gpyfft.test"], ext_modules=cythonize(extensions), package_data=package_data, install_requires=install_requires, setup_requires=setup_requires, )
geggo/gpyfft
setup.py
Python
lgpl-3.0
3,106
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<vector> #include<algorithm> #define REP(i,a,b) for(int i=a;i<=b;++i) #define FOR(i,a,b) for(int i=a;i<b;++i) #define uREP(i,a,b) for(int i=a;i>=b;--i) #define ECH(i,x) for(__typeof(x.begin()) i=x.begin();i!=x.end();++i) #define CPY(a,b) memcpy(a,b,sizeof(a)) #define CLR(a,b) memset(a,b,sizeof(a)) #pragma GCC optimize("O2") //#pragma comment(linker,"/STACK:36777216") #define endl '\n' #define sf scanf #define pf printf #define maxn 3000 using namespace std; struct bign{ int len,v[maxn+2]; bign(){len=0,CLR(v,0);} void print(){uREP(i,len,1)pf("%d",v[i]);} bign operator*(int b){ REP(i,1,len)v[i]*=b; REP(i,1,len){ v[i+1]+=v[i]/10; v[i]%=10; if(v[i+1])len=max(len,i+1); } return *this; } }; int main(){ //freopen("input.txt","r",stdin); int n; while(~sf("%d",&n)){ bign ans; ans.v[1]=ans.len=1; REP(i,1,n)ans=ans*i; pf("%d!\n",n); ans.print();pf("\n"); } return 0; }
metowolf/ACM
UVa/volume006/623 - 500!.cpp
C++
lgpl-3.0
991
<import resource="classpath:alfresco/site-webscripts/org/alfresco/components/workflow/workflow.lib.js"> var workflowDefinitions = getWorkflowDefinitions(), filters = []; if (workflowDefinitions) { for (var i = 0, il = workflowDefinitions.length; i < il; i++) { filters.push( { id: "workflowType", data: workflowDefinitions[i].name, label: workflowDefinitions[i].title }); } } model.filters = filters;
loftuxab/community-edition-old
projects/slingshot/config/alfresco/site-webscripts/org/alfresco/components/workflow/filter/workflow-type.get.js
JavaScript
lgpl-3.0
458
/******************************************************************** Export *********************************************************************/ /** @private */ vs.util.extend (exports, { Animation: Animation, Trajectory: Trajectory, Vector1D: Vector1D, Vector2D: Vector2D, Circular2D: Circular2D, Pace: Pace, Chronometer: Chronometer, generateCubicBezierFunction: generateCubicBezierFunction, createTransition: createTransition, freeTransition: freeTransition, animateTransitionBis: animateTransitionBis, attachTransition: attachTransition, removeTransition: removeTransition });
vinisketch/VSToolkit
src/ext/fx/Exports.js
JavaScript
lgpl-3.0
840
/* * Copyright (C) 2015-2016 Didier Villevalois. * * This file is part of JLaTo. * * JLaTo 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. * * JLaTo 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 JLaTo. If not, see <http://www.gnu.org/licenses/>. */ package org.jlato.internal.td.decl; import org.jlato.internal.bu.coll.SNodeList; import org.jlato.internal.bu.decl.SAnnotationDecl; import org.jlato.internal.bu.name.SName; import org.jlato.internal.td.TDLocation; import org.jlato.internal.td.TDTree; import org.jlato.tree.Kind; import org.jlato.tree.NodeList; import org.jlato.tree.Trees; import org.jlato.tree.decl.AnnotationDecl; import org.jlato.tree.decl.ExtendedModifier; import org.jlato.tree.decl.MemberDecl; import org.jlato.tree.decl.TypeDecl; import org.jlato.tree.name.Name; import org.jlato.util.Mutation; /** * An annotation type declaration. */ public class TDAnnotationDecl extends TDTree<SAnnotationDecl, TypeDecl, AnnotationDecl> implements AnnotationDecl { /** * Returns the kind of this annotation type declaration. * * @return the kind of this annotation type declaration. */ public Kind kind() { return Kind.AnnotationDecl; } /** * Creates an annotation type declaration for the specified tree location. * * @param location the tree location. */ public TDAnnotationDecl(TDLocation<SAnnotationDecl> location) { super(location); } /** * Creates an annotation type declaration with the specified child trees. * * @param modifiers the modifiers child tree. * @param name the name child tree. * @param members the members child tree. */ public TDAnnotationDecl(NodeList<ExtendedModifier> modifiers, Name name, NodeList<MemberDecl> members) { super(new TDLocation<SAnnotationDecl>(SAnnotationDecl.make(TDTree.<SNodeList>treeOf(modifiers), TDTree.<SName>treeOf(name), TDTree.<SNodeList>treeOf(members)))); } /** * Returns the modifiers of this annotation type declaration. * * @return the modifiers of this annotation type declaration. */ public NodeList<ExtendedModifier> modifiers() { return location.safeTraversal(SAnnotationDecl.MODIFIERS); } /** * Replaces the modifiers of this annotation type declaration. * * @param modifiers the replacement for the modifiers of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withModifiers(NodeList<ExtendedModifier> modifiers) { return location.safeTraversalReplace(SAnnotationDecl.MODIFIERS, modifiers); } /** * Mutates the modifiers of this annotation type declaration. * * @param mutation the mutation to apply to the modifiers of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withModifiers(Mutation<NodeList<ExtendedModifier>> mutation) { return location.safeTraversalMutate(SAnnotationDecl.MODIFIERS, mutation); } /** * Returns the name of this annotation type declaration. * * @return the name of this annotation type declaration. */ public Name name() { return location.safeTraversal(SAnnotationDecl.NAME); } /** * Replaces the name of this annotation type declaration. * * @param name the replacement for the name of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withName(Name name) { return location.safeTraversalReplace(SAnnotationDecl.NAME, name); } /** * Mutates the name of this annotation type declaration. * * @param mutation the mutation to apply to the name of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withName(Mutation<Name> mutation) { return location.safeTraversalMutate(SAnnotationDecl.NAME, mutation); } /** * Replaces the name of this annotation type declaration. * * @param name the replacement for the name of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withName(String name) { return location.safeTraversalReplace(SAnnotationDecl.NAME, Trees.name(name)); } /** * Returns the members of this annotation type declaration. * * @return the members of this annotation type declaration. */ public NodeList<MemberDecl> members() { return location.safeTraversal(SAnnotationDecl.MEMBERS); } /** * Replaces the members of this annotation type declaration. * * @param members the replacement for the members of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withMembers(NodeList<MemberDecl> members) { return location.safeTraversalReplace(SAnnotationDecl.MEMBERS, members); } /** * Mutates the members of this annotation type declaration. * * @param mutation the mutation to apply to the members of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withMembers(Mutation<NodeList<MemberDecl>> mutation) { return location.safeTraversalMutate(SAnnotationDecl.MEMBERS, mutation); } }
ptitjes/jlato
src/main/java/org/jlato/internal/td/decl/TDAnnotationDecl.java
Java
lgpl-3.0
5,671
// Copyright (C) 2018 go-nebulas authors // // This file is part of the go-nebulas library. // // the go-nebulas library 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 go-nebulas 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with the go-nebulas library. If not, see // <http://www.gnu.org/licenses/>. // #include "cmd/dummy_neb/generator/transaction_generator.h" transaction_generator::transaction_generator(all_accounts *accounts, generate_block *block, int new_account_num, int tx_num) : generator_base(accounts, block, new_account_num, tx_num), m_new_addresses(), m_last_used_address_index(0) {} transaction_generator::~transaction_generator() {} std::shared_ptr<corepb::Account> transaction_generator::gen_account() { auto ret = m_block->gen_user_account(100_nas); m_new_addresses.push_back(neb::to_address(ret->address())); return ret; } std::shared_ptr<corepb::Transaction> transaction_generator::gen_tx() { auto from_addr = neb::to_address(m_all_accounts->random_user_account()->address()); address_t to_addr; if (m_last_used_address_index < m_new_addresses.size()) { to_addr = m_new_addresses[m_last_used_address_index]; m_last_used_address_index++; } else { to_addr = neb::to_address(m_all_accounts->random_user_account()->address()); } return m_block->add_binary_transaction(from_addr, to_addr, 1_nas); } checker_tasks::task_container_ptr_t transaction_generator::gen_tasks() { return nullptr; }
nebulasio/go-nebulas
nbre/cmd/dummy_neb/generator/transaction_generator.cpp
C++
lgpl-3.0
2,026
# BlenderBIM Add-on - OpenBIM Blender Add-on # Copyright (C) 2021 Dion Moult <dion@thinkmoult.com> # # This file is part of BlenderBIM Add-on. # # BlenderBIM Add-on 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. # # BlenderBIM Add-on 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 BlenderBIM Add-on. If not, see <http://www.gnu.org/licenses/>. import os import re import bpy import pytest import webbrowser import blenderbim import ifcopenshell import ifcopenshell.util.representation from blenderbim.bim.ifc import IfcStore from mathutils import Vector # Monkey-patch webbrowser opening since we want to test headlessly webbrowser.open = lambda x: True variables = {"cwd": os.getcwd(), "ifc": "IfcStore.get_file()"} class NewFile: @pytest.fixture(autouse=True) def setup(self): IfcStore.purge() bpy.ops.wm.read_homefile(app_template="") if bpy.data.objects: bpy.data.batch_remove(bpy.data.objects) bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) blenderbim.bim.handler.setDefaultProperties(None) class NewIfc: @pytest.fixture(autouse=True) def setup(self): IfcStore.purge() bpy.ops.wm.read_homefile(app_template="") bpy.data.batch_remove(bpy.data.objects) bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) blenderbim.bim.handler.setDefaultProperties(None) bpy.ops.bim.create_project() def scenario(function): def subfunction(self): run(function(self)) return subfunction def scenario_debug(function): def subfunction(self): run_debug(function(self)) return subfunction def an_empty_ifc_project(): bpy.ops.bim.create_project() def i_add_a_cube(): bpy.ops.mesh.primitive_cube_add() def i_add_a_cube_of_size_size_at_location(size, location): bpy.ops.mesh.primitive_cube_add(size=float(size), location=[float(co) for co in location.split(",")]) def the_object_name_is_selected(name): i_deselect_all_objects() additionally_the_object_name_is_selected(name) def additionally_the_object_name_is_selected(name): obj = bpy.context.scene.objects.get(name) if not obj: assert False, 'The object "{name}" could not be selected' bpy.context.view_layer.objects.active = obj obj.select_set(True) def i_deselect_all_objects(): bpy.context.view_layer.objects.active = None bpy.ops.object.select_all(action="DESELECT") def i_am_on_frame_number(number): bpy.context.scene.frame_set(int(number)) def i_set_prop_to_value(prop, value): try: eval(f"bpy.context.{prop}") except: assert False, "Property does not exist" try: exec(f'bpy.context.{prop} = "{value}"') except: exec(f"bpy.context.{prop} = {value}") def prop_is_value(prop, value): is_value = False try: exec(f'assert bpy.context.{prop} == "{value}"') is_value = True except: try: exec(f"assert bpy.context.{prop} == {value}") is_value = True except: try: exec(f"assert list(bpy.context.{prop}) == {value}") is_value = True except: pass if not is_value: actual_value = eval(f"bpy.context.{prop}") assert False, f"Value is {actual_value}" def i_enable_prop(prop): exec(f"bpy.context.{prop} = True") def i_press_operator(operator): if "(" in operator: exec(f"bpy.ops.{operator}") else: exec(f"bpy.ops.{operator}()") def i_rename_the_object_name1_to_name2(name1, name2): the_object_name_exists(name1).name = name2 def the_object_name_exists(name): obj = bpy.data.objects.get(name) if not obj: assert False, f'The object "{name}" does not exist' return obj def an_ifc_file_exists(): ifc = IfcStore.get_file() if not ifc: assert False, "No IFC file is available" return ifc def an_ifc_file_does_not_exist(): ifc = IfcStore.get_file() if ifc: assert False, "An IFC is available" def the_object_name_does_not_exist(name): assert bpy.data.objects.get(name) is None, "Object exists" def the_object_name_is_an_ifc_class(name, ifc_class): ifc = an_ifc_file_exists() element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id) assert element.is_a(ifc_class), f'Object "{name}" is an {element.is_a()}' def the_object_name_is_not_an_ifc_element(name): id = the_object_name_exists(name).BIMObjectProperties.ifc_definition_id assert id == 0, f"The ID is {id}" def the_object_name_is_in_the_collection_collection(name, collection): assert collection in [c.name for c in the_object_name_exists(name).users_collection] def the_object_name_is_not_in_the_collection_collection(name, collection): assert collection not in [c.name for c in the_object_name_exists(name).users_collection] def the_object_name_has_a_body_of_value(name, value): assert the_object_name_exists(name).data.body == value def the_collection_name1_is_in_the_collection_name2(name1, name2): assert bpy.data.collections.get(name2).children.get(name1) def the_collection_name1_is_not_in_the_collection_name2(name1, name2): assert not bpy.data.collections.get(name2).children.get(name1) def the_object_name_is_placed_in_the_collection_collection(name, collection): obj = the_object_name_exists(name) [c.objects.unlink(obj) for c in obj.users_collection] bpy.data.collections.get(collection).objects.link(obj) def the_object_name_has_a_type_representation_of_context(name, type, context): ifc = an_ifc_file_exists() element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id) context, subcontext, target_view = context.split("/") assert ifcopenshell.util.representation.get_representation( element, context, subcontext or None, target_view or None ) def the_object_name_is_contained_in_container_name(name, container_name): ifc = an_ifc_file_exists() element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id) container = ifcopenshell.util.element.get_container(element) if not container: assert False, f'Object "{name}" is not in any container' assert container.Name == container_name, f'Object "{name}" is in {container}' def i_duplicate_the_selected_objects(): bpy.ops.object.duplicate_move() blenderbim.bim.handler.active_object_callback() def i_delete_the_selected_objects(): bpy.ops.object.delete() blenderbim.bim.handler.active_object_callback() def the_object_name1_and_name2_are_different_elements(name1, name2): ifc = an_ifc_file_exists() element1 = ifc.by_id(the_object_name_exists(name1).BIMObjectProperties.ifc_definition_id) element2 = ifc.by_id(the_object_name_exists(name2).BIMObjectProperties.ifc_definition_id) assert element1 != element2, f"Objects {name1} and {name2} have same elements {element1} and {element2}" def the_file_name_should_contain_value(name, value): with open(name, "r") as f: assert value in f.read() def the_object_name1_has_a_boolean_difference_by_name2(name1, name2): obj = the_object_name_exists(name1) for modifier in obj.modifiers: if modifier.type == "BOOLEAN" and modifier.object and modifier.object.name == name2: return True assert False, "No boolean found" def the_object_name1_has_no_boolean_difference_by_name2(name1, name2): obj = the_object_name_exists(name1) for modifier in obj.modifiers: if modifier.type == "BOOLEAN" and modifier.object and modifier.object.name == name2: assert False, "A boolean was found" def the_object_name_is_voided_by_void(name, void): ifc = IfcStore.get_file() element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id) for rel in element.HasOpenings: if rel.RelatedOpeningElement.Name == void: return True assert False, "No void found" def the_object_name_is_not_voided_by_void(name, void): ifc = IfcStore.get_file() element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id) for rel in element.HasOpenings: if rel.RelatedOpeningElement.Name == void: assert False, "A void was found" def the_object_name_is_not_voided(name): ifc = IfcStore.get_file() element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id) if any(element.HasOpenings): assert False, "An opening was found" def the_object_name_is_not_a_void(name): ifc = IfcStore.get_file() element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id) if any(element.VoidsElements): assert False, "A void was found" def the_void_name_is_filled_by_filling(name, filling): ifc = IfcStore.get_file() element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id) if any(rel.RelatedBuildingElement.Name == filling for rel in element.HasFillings): return True assert False, "No filling found" def the_void_name_is_not_filled_by_filling(name, filling): ifc = IfcStore.get_file() element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id) if any(rel.RelatedBuildingElement.Name == filling for rel in element.HasFillings): assert False, "A filling was found" def the_object_name_is_not_a_filling(name): ifc = IfcStore.get_file() element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id) if any(element.FillsVoids): assert False, "A filling was found" def the_object_name_should_display_as_mode(name, mode): assert the_object_name_exists(name).display_type == mode def the_object_name_has_number_vertices(name, number): total = len(the_object_name_exists(name).data.vertices) assert total == int(number), f"We found {total} vertices" def the_object_name_is_at_location(name, location): obj_location = the_object_name_exists(name).location assert ( obj_location - Vector([float(co) for co in location.split(",")]) ).length < 0.1, f"Object is at {obj_location}" def the_variable_key_is_value(key, value): variables[key] = eval(value) definitions = { 'the variable "(.*)" is "(.*)"': the_variable_key_is_value, "an empty IFC project": an_empty_ifc_project, "I add a cube": i_add_a_cube, 'I add a cube of size "([0-9]+)" at "(.*)"': i_add_a_cube_of_size_size_at_location, 'the object "(.*)" is selected': the_object_name_is_selected, 'additionally the object "(.*)" is selected': additionally_the_object_name_is_selected, "I deselect all objects": i_deselect_all_objects, 'I am on frame "([0-9]+)"': i_am_on_frame_number, 'I set "(.*)" to "(.*)"': i_set_prop_to_value, '"(.*)" is "(.*)"': prop_is_value, 'I enable "(.*)"': i_enable_prop, 'I press "(.*)"': i_press_operator, 'I rename the object "(.*)" to "(.*)"': i_rename_the_object_name1_to_name2, 'the object "(.*)" exists': the_object_name_exists, 'the object "(.*)" does not exist': the_object_name_does_not_exist, 'the object "(.*)" is an "(.*)"': the_object_name_is_an_ifc_class, 'the object "(.*)" is not an IFC element': the_object_name_is_not_an_ifc_element, 'the object "(.*)" is in the collection "(.*)"': the_object_name_is_in_the_collection_collection, 'the object "(.*)" is not in the collection "(.*)"': the_object_name_is_not_in_the_collection_collection, 'the object "(.*)" has a body of "(.*)"': the_object_name_has_a_body_of_value, 'the collection "(.*)" is in the collection "(.*)"': the_collection_name1_is_in_the_collection_name2, 'the collection "(.*)" is not in the collection "(.*)"': the_collection_name1_is_not_in_the_collection_name2, "an IFC file exists": an_ifc_file_exists, "an IFC file does not exist": an_ifc_file_does_not_exist, 'the object "(.*)" has a "(.*)" representation of "(.*)"': the_object_name_has_a_type_representation_of_context, 'the object "(.*)" is placed in the collection "(.*)"': the_object_name_is_placed_in_the_collection_collection, 'the object "(.*)" is contained in "(.*)"': the_object_name_is_contained_in_container_name, "I duplicate the selected objects": i_duplicate_the_selected_objects, "I delete the selected objects": i_delete_the_selected_objects, 'the object "(.*)" and "(.*)" are different elements': the_object_name1_and_name2_are_different_elements, 'the file "(.*)" should contain "(.*)"': the_file_name_should_contain_value, 'the object "(.*)" has a boolean difference by "(.*)"': the_object_name1_has_a_boolean_difference_by_name2, 'the object "(.*)" has no boolean difference by "(.*)"': the_object_name1_has_no_boolean_difference_by_name2, 'the object "(.*)" is voided by "(.*)"': the_object_name_is_voided_by_void, 'the object "(.*)" is not voided by "(.*)"': the_object_name_is_not_voided_by_void, 'the object "(.*)" is not a void': the_object_name_is_not_a_void, 'the object "(.*)" is not voided': the_object_name_is_not_voided, 'the object "(.*)" should display as "(.*)"': the_object_name_should_display_as_mode, 'the object "(.*)" has "([0-9]+)" vertices': the_object_name_has_number_vertices, 'the object "(.*)" is at "(.*)"': the_object_name_is_at_location, "nothing interesting happens": lambda: None, 'the void "(.*)" is filled by "(.*)"': the_void_name_is_filled_by_filling, 'the void "(.*)" is not filled by "(.*)"': the_void_name_is_not_filled_by_filling, 'the object "(.*)" is not a filling': the_object_name_is_not_a_filling, } # Super lightweight Gherkin implementation def run(scenario): keywords = ["Given", "When", "Then", "And", "But"] for line in scenario.split("\n"): for key, value in variables.items(): line = line.replace("{" + key + "}", str(value)) for keyword in keywords: line = line.replace(keyword, "") line = line.strip() if not line: continue match = None for definition, callback in definitions.items(): match = re.search("^" + definition + "$", line) if match: try: callback(*match.groups()) except AssertionError as e: assert False, f"Failed: {line}, with error: {e}" break if not match: assert False, f"Definition not implemented: {line}" return True def run_debug(scenario, blend_filepath=None): try: result = run(scenario) except Exception as e: if blend_filepath: bpy.ops.wm.save_as_mainfile(filepath=blend_filepath) assert False, e if blend_filepath: bpy.ops.wm.save_as_mainfile(filepath=blend_filepath) return result
IfcOpenShell/IfcOpenShell
src/blenderbim/test/bim/bootstrap.py
Python
lgpl-3.0
15,500
<?php namespace page\model; use n2n\util\ex\err\FancyErrorException; class PageErrorException extends FancyErrorException { }
n2n/page
src/app/page/model/PageErrorException.php
PHP
lgpl-3.0
133
package org.orchestra.sm; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Runner { private final Logger logger = LoggerFactory.getLogger(Runner.class); private List<String> command = new ArrayList<String>(); private Map<String, String> env; private String workDir; private Process process; public Map<String, String> getEnv() { return env; } public void setEnv(Map<String, String> env) { this.env = env; } public Runner(String command, List<String> args) { this.command.add(command); if(args != null) this.command.addAll(args); } public Runner(String command, List<String> args, Map<String, String> env) { this.command.add(command); if(args != null) this.command.addAll(args); this.env = env; } public Runner(String command, List<String> args, Map<String, String> env, String workDir) { this.command.add(command); if(args != null) this.command.addAll(args); this.env = env; this.workDir = workDir; } public int run(String arg) throws IOException, InterruptedException { List<String> cmd = new ArrayList<String>(command); if(arg != null) cmd.add(arg); new StringBuffer(); ProcessBuilder pb = new ProcessBuilder(cmd); if(env != null) pb.environment().putAll(env); if(workDir != null) pb.directory(new File(workDir)); logger.debug("Environment variables:"); for(Entry<String, String> e : pb.environment().entrySet()) { logger.debug(e.getKey() + "=" + e.getValue()); } process = pb.start(); return process.waitFor(); } public InputStream getInputStream() { return process.getInputStream(); } public BufferedReader getSystemOut() { BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); return input; } public BufferedReader getSystemError() { BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); return error; } public void setStandardInput(String filename) { } }
bigorc/orchestra
src/main/java/org/orchestra/sm/Runner.java
Java
lgpl-3.0
2,212
package org.datacleaner.kettle.ui; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.plugins.JobEntryPluginType; import org.pentaho.di.core.plugins.PluginRegistry; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.job.entry.JobEntryDialog; import org.pentaho.di.ui.trans.step.BaseStepDialog; import plugin.DataCleanerJobEntry; public abstract class AbstractJobEntryDialog extends JobEntryDialog implements JobEntryDialogInterface, DisposeListener { private final String initialJobName; private Text jobNameField; private Button okButton; private Button cancelButton; private List<Object> resources = new ArrayList<Object>(); public AbstractJobEntryDialog(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) { super(parent, jobEntry, rep, jobMeta); initialJobName = (jobEntry.getName() == null ? DataCleanerJobEntry.NAME : jobEntry.getName()); } protected void initializeShell(Shell shell) { String id = PluginRegistry.getInstance().getPluginId(JobEntryPluginType.class, jobMeta); if (id != null) { shell.setImage(GUIResource.getInstance().getImagesStepsSmall().get(id)); } } /** * @wbp.parser.entryPoint */ @Override public final JobEntryInterface open() { final Shell parent = getParent(); final Display display = parent.getDisplay(); // initialize shell { shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX); initializeShell(shell); FormLayout shellLayout = new FormLayout(); shellLayout.marginTop = 0; shellLayout.marginLeft = 0; shellLayout.marginRight = 0; shellLayout.marginBottom = 0; shellLayout.marginWidth = 0; shellLayout.marginHeight = 0; shell.setLayout(shellLayout); shell.setText(DataCleanerJobEntry.NAME + ": " + initialJobName); } final int middle = Const.MIDDLE_PCT; final int margin = Const.MARGIN; // DC banner final DataCleanerBanner banner = new DataCleanerBanner(shell); { final FormData bannerLayoutData = new FormData(); bannerLayoutData.left = new FormAttachment(0, 0); bannerLayoutData.right = new FormAttachment(100, 0); bannerLayoutData.top = new FormAttachment(0, 0); banner.setLayoutData(bannerLayoutData); } // Step name { final Label stepNameLabel = new Label(shell, SWT.RIGHT); stepNameLabel.setText("Step name:"); final FormData stepNameLabelLayoutData = new FormData(); stepNameLabelLayoutData.left = new FormAttachment(0, margin); stepNameLabelLayoutData.right = new FormAttachment(middle, -margin); stepNameLabelLayoutData.top = new FormAttachment(banner, margin * 2); stepNameLabel.setLayoutData(stepNameLabelLayoutData); jobNameField = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); jobNameField.setText(initialJobName); final FormData stepNameFieldLayoutData = new FormData(); stepNameFieldLayoutData.left = new FormAttachment(middle, 0); stepNameFieldLayoutData.right = new FormAttachment(100, -margin); stepNameFieldLayoutData.top = new FormAttachment(banner, margin * 2); jobNameField.setLayoutData(stepNameFieldLayoutData); } // Properties Group final Group propertiesGroup = new Group(shell, SWT.SHADOW_ETCHED_IN); propertiesGroup.setText("Step configuration"); final FormData propertiesGroupLayoutData = new FormData(); propertiesGroupLayoutData.left = new FormAttachment(0, margin); propertiesGroupLayoutData.right = new FormAttachment(100, -margin); propertiesGroupLayoutData.top = new FormAttachment(jobNameField, margin); propertiesGroup.setLayoutData(propertiesGroupLayoutData); final GridLayout propertiesGroupLayout = new GridLayout(2, false); propertiesGroup.setLayout(propertiesGroupLayout); addConfigurationFields(propertiesGroup, margin, middle); okButton = new Button(shell, SWT.PUSH); Image saveImage = new Image(shell.getDisplay(), AbstractJobEntryDialog.class.getResourceAsStream("save.png")); resources.add(saveImage); okButton.setImage(saveImage); okButton.setText("OK"); okButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { ok(); final String jobEntryName = jobNameField.getText(); if (jobEntryName != null && jobEntryName.length() > 0 && !initialJobName.equals(jobEntryName)) { jobEntryInt.setName(jobEntryName); } jobEntryInt.setChanged(); shell.close(); } }); cancelButton = new Button(shell, SWT.PUSH); Image cancelImage = new Image(shell.getDisplay(), AbstractJobEntryDialog.class.getResourceAsStream("cancel.png")); resources.add(cancelImage); cancelButton.setImage(cancelImage); cancelButton.setText("Cancel"); cancelButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event arg0) { cancel(); jobNameField.setText(""); shell.close(); } }); BaseStepDialog.positionBottomButtons(shell, new Button[] { okButton, cancelButton }, margin, propertiesGroup); // HI banner final DataCleanerFooter footer = new DataCleanerFooter(shell); { final FormData footerLayoutData = new FormData(); footerLayoutData.left = new FormAttachment(0, 0); footerLayoutData.right = new FormAttachment(100, 0); footerLayoutData.top = new FormAttachment(okButton, margin * 2); footer.setLayoutData(footerLayoutData); } shell.addDisposeListener(this); shell.setSize(getDialogSize()); // center the dialog in the middle of the screen final Rectangle screenSize = shell.getDisplay().getPrimaryMonitor().getBounds(); shell.setLocation((screenSize.width - shell.getBounds().width) / 2, (screenSize.height - shell.getBounds().height) / 2); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return jobEntryInt; } @Override public void widgetDisposed(DisposeEvent event) { for (Object resource : resources) { if (resource instanceof Image) { ((Image) resource).dispose(); } } } protected Point getDialogSize() { Point clientAreaSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT); int frameX = shell.getSize().x - shell.getClientArea().width; int frameY = shell.getSize().y - shell.getClientArea().height; return new Point(frameX + clientAreaSize.x, frameY + clientAreaSize.y); } protected abstract void addConfigurationFields(Group propertiesGroup, int margin, int middle); public void cancel() { // do nothing } public abstract void ok(); protected void showWarning(String message) { MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.OK); messageBox.setText("EasyDataQuality - Warning"); messageBox.setMessage(message); messageBox.open(); } protected String getStepDescription() { return null; } }
datacleaner/pdi-datacleaner
src/main/java/org/datacleaner/kettle/ui/AbstractJobEntryDialog.java
Java
lgpl-3.0
8,903