repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
BrianRickardMason/TheUltimateStrategy
Game/GameServerUT/Resource/ResourceWithVolumeTest.cpp
3334
// Copyright (C) 2010, 2011 and 2012 Marcin Arkadiusz Skrobiranda. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. 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. // 3. Neither the name of the project 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 PROJECT 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 PROJECT 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. #include <Game/GameServer/Resource/Key.hpp> #include <Game/GameServer/Resource/ResourceWithVolume.hpp> #include <Server/include/Context.hpp> #include <gmock/gmock.h> using namespace GameServer::Common; using namespace GameServer::Resource; using namespace std; /** * @brief A test class. */ class ResourceWithVolumeTest : public testing::Test { protected: /** * @brief Constructs a test class. */ ResourceWithVolumeTest() : m_context(new Server::Context), m_resource_with_volume(m_context, KEY_RESOURCE_COAL, 2), m_model_key(KEY_RESOURCE_COAL) { } Server::IContextShrPtr m_context; /** * @brief A resource with volume to be tested. */ ResourceWithVolume m_resource_with_volume; /** * @brief A model key. */ string m_model_key; }; TEST_F(ResourceWithVolumeTest, ResourceWithVolume_BasedOnArguments) { ResourceWithVolume resource_with_volume(m_context, KEY_RESOURCE_COAL, 2); ASSERT_TRUE(m_model_key == resource_with_volume.getResource()->getKey()); ASSERT_EQ(2, resource_with_volume.getVolume()); } TEST_F(ResourceWithVolumeTest, ResourceWithVolume_BasedOnRecord) { ResourceWithVolumeRecord resource_with_volume_record(IDHolder(ID_HOLDER_CLASS_SETTLEMENT, "Settlement"), KEY_RESOURCE_COAL, 2); ResourceWithVolume resource_with_volume(m_context, resource_with_volume_record); ASSERT_TRUE(m_model_key == resource_with_volume.getResource()->getKey()); ASSERT_EQ(2, resource_with_volume.getVolume()); } TEST_F(ResourceWithVolumeTest, GetResourceResourceIsNotEmpty) { ASSERT_TRUE(m_resource_with_volume.getResource()); } TEST_F(ResourceWithVolumeTest, getVolume) { ASSERT_EQ(2, m_resource_with_volume.getVolume()); }
bsd-3-clause
jguittard/zf-doctrine-mapping
src/QueryBuilder/Filter/ORM/NotEquals.php
1751
<?php namespace ZF\Doctrine\QueryBuilder\Filter\ORM; use Doctrine\ORM\Mapping\ClassMetadataInfo; use Doctrine\ORM\QueryBuilder; /** * Class NotEquals * * @package ZF\Doctrine\QueryBuilder\Filter\ORM * @version 1.0 * @author Julien Guittard <julien.guittard@me.com> * @see http://github.com/jguittard/zf-doctrine-mapping for the canonical source repository * @link https://doctrine-mapping.io Doctrine Mapping Website * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2016 Zend Technologies USA Inc. (http://www.zend.com) */ class NotEquals extends AbstractFilter { /** * @param QueryBuilder $queryBuilder * @param ClassMetadataInfo $metadata * @param array $option */ public function filter(QueryBuilder $queryBuilder, ClassMetadataInfo $metadata, array $option) { if (isset($option['where'])) { if ($option['where'] === 'and') { $queryType = 'andWhere'; } elseif ($option['where'] === 'or') { $queryType = 'orWhere'; } } if (! isset($queryType)) { $queryType = 'andWhere'; } if (! isset($option['alias'])) { $option['alias'] = 'row'; } $format = isset($option['format']) ? $option['format'] : null; $value = $this->typeCastField($metadata, $option['field'], $option['value'], $format); $parameter = uniqid('a'); $queryBuilder->$queryType( $queryBuilder ->expr() ->neq($option['alias'] . '.' . $option['field'], ':' . $parameter) ); $queryBuilder->setParameter($parameter, $value); } }
bsd-3-clause
ngrodzitski/json_dto-0.1
dev/sample/tutorial4/prj.rb
205
gem 'Mxx_ru', '>= 1.3.0' require 'mxx_ru/cpp' MxxRu::Cpp::exe_target { # Define your target name here. target 'sample.tutorial4' required_prj 'rapidjson_mxxru/prj.rb' cpp_source 'main.cpp' }
bsd-3-clause
dineshkummarc/zf2
library/Zend/GData/Calendar/ListFeed.php
2864
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Calendar * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\GData\Calendar; use Zend\GData\Calendar; /** * Represents the meta-feed list of calendars * * @uses \Zend\GData\Calendar * @uses Zend_Gdata_Extension_Timezone * @uses \Zend\GData\Feed * @category Zend * @package Zend_Gdata * @subpackage Calendar * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class ListFeed extends \Zend\GData\Feed { protected $_timezone = null; /** * The classname for individual feed elements. * * @var string */ protected $_entryClassName = 'Zend\GData\Calendar\ListEntry'; /** * The classname for the feed. * * @var string */ protected $_feedClassName = 'Zend\GData\Calendar\ListFeed'; public function __construct($element = null) { $this->registerAllNamespaces(Calendar::$namespaces); parent::__construct($element); } public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_timezone != null) { $element->appendChild($this->_timezone->getDOM($element->ownerDocument)); } return $element; } protected function takeChildFromDOM($child) { $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; switch ($absoluteNodeName) { case $this->lookupNamespace('gCal') . ':' . 'timezone'; $timezone = new Extension\Timezone(); $timezone->transferFromDOM($child); $this->_timezone = $timezone; break; default: parent::takeChildFromDOM($child); break; } } public function getTimezone() { return $this->_timezone; } /** * @param \Zend\GData\Calendar\Extension\Timezone $value * @return Zend_Gdata_Extension_ListEntry Provides a fluent interface */ public function setTimezone($value) { $this->_timezone = $value; return $this; } }
bsd-3-clause
pdhwi/hwizfms
module/Hwi/src/Hwi/Model/ProductTable.php
2760
<?php namespace Hwi\Model; use Zend\Db\TableGateway\TableGateway; class ProductTable { protected $tableGateway; public function __construct(TableGateway $tableGateway) { $this->tableGateway = $tableGateway; } public function fetchAll($where='',$order='',$limit='',$paginated='') { if($paginated){ $select = new \Zend\Db\Sql\Select('hwi_product'); if(is_array($where)){ $select->where($where); } if(is_array($order)){ foreach ($order as $key => $value) { $select->order($value); } } $rs = new \Zend\Db\ResultSet\ResultSet(); $rs->setArrayObjectPrototype(new product()); $pageAdapter = new \Zend\Paginator\Adapter\DbSelect($select,$this->tableGateway->getAdapter(),$rs); $paginator = new \Zend\Paginator\Paginator($pageAdapter); return $paginator; } $resultSet = $this->tableGateway->select($where,$order,$limit); return $resultSet; } public function getartPro($id) { $id = (int) $id; $rowset = $this->tableGateway->select(array('product_id' => $id)); $row = $rowset->current(); if (!$row) { throw new \Exception("Could not find row $id"); } return $row; } public function saveBanner(Banner $album) { $data = array( 'product_id' => $this->product_id, 'product_name' => $this->product_name, 'product_proCat' => $this->product_proCat, 'product_feature' => $this->product_feature, 'product_desc' => $this->product_desc, 'product_PCimg' => $this->product_PCimg, 'product_MBimg' => $this->product_MBimg, 'product_price' => $this->product_price, 'product_orderBy' => $this->product_orderBy, 'product_show' => $this->product_show, 'product_addtime' => $this->product_addtime, ); $id = (int) $album->id; if ($id == 0) { $this->tableGateway->insert($data); } else { if ($this->getAlbum($id)) { $this->tableGateway->update($data, array('banner_id' => $id)); } else { throw new \Exception('Banner id does not exist'); } } } public function deleteBanner($id) { $this->tableGateway->delete(array('banner_id' => (int) $id)); } function checksql(){ return $this->tableGateway->getLastInsertValue(); } } ?>
bsd-3-clause
jwend/p_points2grid
include/pct/Grid.hpp
1305
/************************************************************ * Grid.hpp * A basic grid implementation for uniform meshing * Used/for binning Points for outcore map-reduce ***********************************************************/ #ifndef GRID_HPP #define GRID_HPP #include <vector> #include <iostream> #include <iomanip> #include "pct/Point.hpp" #include "pct/DTypes.hpp" #include "pct/Pixel.hpp" using namespace std; typedef struct Grid { int cols; int rows; struct Point* origin; double resX; double resY; DType datatype; // Currently unused,need to parameterize this Pixel* data; Grid(); Grid(const struct Point *origin, int cols, int rows, DType datatype, double resX, double resY); ~Grid(); void * alloc(); // Allocate memory for grid pixels void dealloc(); // Free memory taken by grid's pixels int cellCount(); // Return the number of cells (cols * rows) size_t getSize(); // Get size of grid in bytes int getCol(double coord); int getRow(double coord); int write(char* outPath, int epsg); int within(const struct Point *pt); double getMaxX(); double getMinY(); int set(const struct Point *pt); Pixel* get(int col, int row); float* getSumArr(); // Return array representing the sum for each pixel int getCell(const struct Point *pt, int* idx); } Grid; #endif
bsd-3-clause
oddt/oddt
tests/test_rdkitfixer.py
22042
import os import tempfile from numpy.testing import assert_array_equal, assert_almost_equal import pytest try: import rdkit from rdkit import Chem except ImportError: rdkit = None if rdkit is not None: from oddt.toolkits.extras.rdkit.fixer import (AtomListToSubMol, PreparePDBMol, ExtractPocketAndLigand, IsResidueConnected, FetchStructure, PrepareComplexes) test_data_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.join(test_data_dir, 'data', 'pdb') @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_atom_list_to_submol(): mol = Chem.MolFromSmiles('CCCCC(=O)O') submol = AtomListToSubMol(mol, range(3, 7)) assert submol.GetNumAtoms() == 4 assert submol.GetNumAtoms() == 4 assert submol.GetNumBonds() == 3 assert submol.GetBondBetweenAtoms(1, 2).GetBondType() == rdkit.Chem.rdchem.BondType.DOUBLE molfile = os.path.join(test_dir, '2qwe_Sbridge.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) assert mol.GetConformer().Is3D() submol = AtomListToSubMol(mol, range(6), includeConformer=True) assert submol.GetConformer().Is3D() # submol has residue info atom = submol.GetAtomWithIdx(0) info = atom.GetPDBResidueInfo() assert info.GetResidueName() == 'CYS' assert info.GetResidueNumber() == 92 # test multiple conformers mol.AddConformer(mol.GetConformer()) assert mol.GetNumConformers() == 2 submol = AtomListToSubMol(mol, range(6), includeConformer=True) assert submol.GetNumConformers() == 2 # FIXME: Newer RDKit has GetPositions, 2016.03 does not mol_conf = mol.GetConformer() submol_conf = submol.GetConformer() assert_array_equal([submol_conf.GetAtomPosition(i) for i in range(submol_conf.GetNumAtoms())], [mol_conf.GetAtomPosition(i) for i in range(6)]) submol2 = AtomListToSubMol(submol, range(3), includeConformer=True) submol2_conf = submol2.GetConformer() assert submol2.GetNumConformers() == 2 assert_array_equal([submol2_conf.GetAtomPosition(i) for i in range(submol2_conf.GetNumAtoms())], [mol_conf.GetAtomPosition(i) for i in range(3)]) @pytest.mark.skipif(rdkit is None or rdkit.__version__ < '2017.03', reason="RDKit required") def test_multivalent_Hs(): """Test if fixer deals with multivalent Hs""" # TODO: require mol without Hs in the future (rdkit v. 2018) molfile = os.path.join(test_dir, '2c92_hypervalentH.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol, residue_whitelist=[], removeHs=False) atom = mol.GetAtomWithIdx(84) assert atom.GetAtomicNum() == 1 # is it H assert atom.GetDegree() == 1 # H should have 1 bond for n in atom.GetNeighbors(): # Check if neighbor is from the same residue assert atom.GetPDBResidueInfo().GetResidueName() == n.GetPDBResidueInfo().GetResidueName() # mol can be sanitized assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_HOH_bonding(): """Test if fixer unbinds HOH""" molfile = os.path.join(test_dir, '2vnf_bindedHOH.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) # don't use templates and don't remove waters mol = PreparePDBMol(mol, removeHOHs=False) atom = mol.GetAtomWithIdx(5) assert atom.GetPDBResidueInfo().GetResidueName() == 'HOH' assert atom.GetDegree() == 0 # HOH should have no bonds # mol can be sanitized assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_metal_bonding(): """Test if fixer disconnects metals""" molfile = os.path.join(test_dir, '1ps3_zn.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol) atom = mol.GetAtomWithIdx(36) assert atom.GetAtomicNum() == 30 # is it Zn assert atom.GetDegree() == 0 # Zn should have no bonds assert atom.GetFormalCharge() == 2 assert atom.GetNumExplicitHs() == 0 # mol can be sanitized assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_interresidue_bonding(): """Test if fixer removes wrong connections between residues""" molfile = os.path.join(test_dir, '4e6d_residues.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol) # check if O from PRO atom1 = mol.GetAtomWithIdx(11) assert atom1.GetAtomicNum() == 8 assert atom1.GetPDBResidueInfo().GetResidueName() == 'PRO' # ...and N from GLN atom2 = mol.GetAtomWithIdx(22) assert atom2.GetAtomicNum() == 7 assert atom2.GetPDBResidueInfo().GetResidueName() == 'GLN' # ...are not connected assert mol.GetBondBetweenAtoms(11, 22) is None # mol can be sanitized assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_intraresidue_bonding(): """Test if fixer removes wrong connections within single residue""" molfile = os.path.join(test_dir, '1idg_connectivity.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol) # check if N and C from GLU20 are not connected atom1 = mol.GetAtomWithIdx(11) assert atom1.GetAtomicNum() == 7 assert atom1.GetPDBResidueInfo().GetResidueName() == 'GLU' assert atom1.GetPDBResidueInfo().GetResidueNumber() == 20 atom2 = mol.GetAtomWithIdx(13) assert atom2.GetAtomicNum() == 6 assert atom2.GetPDBResidueInfo().GetResidueName() == 'GLU' assert atom2.GetPDBResidueInfo().GetResidueNumber() == 20 assert mol.GetBondBetweenAtoms(11, 13) is None # mol can be sanitized assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_bondtype(): """Test if fixer deals with non-standard residue and fixes bond types""" molfile = os.path.join(test_dir, '3rsb_bondtype.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol) # check if there is double bond between N and C from MSE atom1 = mol.GetAtomWithIdx(13) assert atom1.GetAtomicNum() == 6 assert atom1.GetPDBResidueInfo().GetResidueName() == 'MSE' atom2 = mol.GetAtomWithIdx(14) assert atom2.GetAtomicNum() == 8 assert atom2.GetPDBResidueInfo().GetResidueName() == 'MSE' # there is a bond and it is double bond = mol.GetBondBetweenAtoms(13, 14) assert bond is not None assert_almost_equal(bond.GetBondTypeAsDouble(), 2.0) # mol can be sanitized assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_ring(): """Test if fixer adds missing bond in ring""" molfile = os.path.join(test_dir, '4yzm_ring.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol) # check if there is double bond between N and C from MSE atom1 = mol.GetAtomWithIdx(12) assert atom1.GetAtomicNum() == 6 assert atom1.GetPDBResidueInfo().GetResidueName() == 'PHE' atom2 = mol.GetAtomWithIdx(13) assert atom2.GetAtomicNum() == 6 assert atom2.GetPDBResidueInfo().GetResidueName() == 'PHE' # there is a bond and it is aromatic bond = mol.GetBondBetweenAtoms(12, 13) assert bond is not None assert_almost_equal(bond.GetBondTypeAsDouble(), 1.5) # mol can be sanitized assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_sulphur_bridge(): """Test sulphur bridges retention""" molfile = os.path.join(test_dir, '2qwe_Sbridge.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol) atom1 = mol.GetAtomWithIdx(5) atom2 = mol.GetAtomWithIdx(11) bond = mol.GetBondBetweenAtoms(atom1.GetIdx(), atom2.GetIdx()) assert atom1.GetPDBResidueInfo().GetName().strip() == 'SG' assert atom1.GetPDBResidueInfo().GetResidueNumber() == 92 assert atom2.GetPDBResidueInfo().GetName().strip() == 'SG' assert atom2.GetPDBResidueInfo().GetResidueNumber() == 417 assert bond is not None @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_pocket_extractor(): """Test extracting pocket and ligand""" molfile = os.path.join(test_dir, '5ar7.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) # there should be no pocket at 1A pocket, ligand = ExtractPocketAndLigand(mol, cutoff=1.) assert pocket.GetNumAtoms() == 0 assert ligand.GetNumAtoms() == 26 # small pocket of 5A pocket, ligand = ExtractPocketAndLigand(mol, cutoff=12.) assert pocket.GetNumAtoms() == 928 assert ligand.GetNumAtoms() == 26 # check if HOH is in pocket atom = pocket.GetAtomWithIdx(910) assert atom.GetAtomicNum() == 8 assert atom.GetPDBResidueInfo().GetResidueName() == 'HOH' # Prepare and sanitize pocket and ligand pocket = PreparePDBMol(pocket) ligand = PreparePDBMol(ligand) assert Chem.SanitizeMol(pocket) == Chem.SanitizeFlags.SANITIZE_NONE assert Chem.SanitizeMol(ligand) == Chem.SanitizeFlags.SANITIZE_NONE # Check atom/bond properies for both molecules bond = pocket.GetBondWithIdx(39) assert bond.GetIsAromatic() assert bond.GetBeginAtom().GetPDBResidueInfo().GetResidueName() == 'TYR' atom = ligand.GetAtomWithIdx(22) assert atom.GetAtomicNum() == 7 assert atom.GetIsAromatic() assert atom.GetPDBResidueInfo().GetResidueName() == 'SR8' # test if metal is in pocket molfile = os.path.join(test_dir, '4p6p_lig_zn.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) assert mol.GetNumAtoms() == 176 pocket, ligand = ExtractPocketAndLigand(mol, cutoff=5.) assert pocket.GetNumAtoms() == 162 assert ligand.GetNumAtoms() == 14 atom = pocket.GetAtomWithIdx(153) assert atom.GetPDBResidueInfo().GetResidueName().strip() == 'ZN' atom = pocket.GetAtomWithIdx(160) assert atom.GetPDBResidueInfo().GetResidueName() == 'HOH' pocket, ligand = ExtractPocketAndLigand(mol, cutoff=5., expandResidues=False) assert pocket.GetNumAtoms() == 74 assert ligand.GetNumAtoms() == 14 atom = pocket.GetAtomWithIdx(65) assert atom.GetPDBResidueInfo().GetResidueName().strip() == 'ZN' atom = pocket.GetAtomWithIdx(73) assert atom.GetPDBResidueInfo().GetResidueName() == 'HOH' # ligand and protein white/blacklist molfile = os.path.join(test_dir, '1dy3_2LIG.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) # by default the largest ligand - ATP pocket, ligand = ExtractPocketAndLigand(mol, cutoff=20.) assert pocket.GetNumAtoms() == 304 assert ligand.GetNumAtoms() == 31 atom = ligand.GetAtomWithIdx(0) assert atom.GetPDBResidueInfo().GetResidueName() == 'ATP' # blacklist APT to get other largest ligand - 87Y pocket, ligand = ExtractPocketAndLigand(mol, cutoff=20., ligand_residue_blacklist=['ATP']) assert pocket.GetNumAtoms() == 304 assert ligand.GetNumAtoms() == 23 atom = ligand.GetAtomWithIdx(0) assert atom.GetPDBResidueInfo().GetResidueName() == '87Y' # point to 87Y explicitly pocket, ligand = ExtractPocketAndLigand(mol, cutoff=20., ligand_residue='87Y') assert pocket.GetNumAtoms() == 304 assert ligand.GetNumAtoms() == 23 atom = ligand.GetAtomWithIdx(0) assert atom.GetPDBResidueInfo().GetResidueName() == '87Y' # include APT in pocket to get other largest ligand - 87Y pocket, ligand = ExtractPocketAndLigand(mol, cutoff=20., append_residues=['ATP']) assert pocket.GetNumAtoms() == 304+31 assert ligand.GetNumAtoms() == 23 atom = ligand.GetAtomWithIdx(0) assert atom.GetPDBResidueInfo().GetResidueName() == '87Y' atom = pocket.GetAtomWithIdx(310) assert atom.GetPDBResidueInfo().GetResidueName() == 'ATP' @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_aromatic_ring(): """Test aromaticity for partial matches""" # ring is complete and should be aromatic molfile = os.path.join(test_dir, '5ar7_HIS.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol) atom = mol.GetAtomWithIdx(6) assert atom.GetAtomicNum() == 7 info = atom.GetPDBResidueInfo() assert info.GetResidueName() == 'HIS' assert info.GetResidueNumber() == 246 assert info.GetName().strip() == 'ND1' assert atom.GetIsAromatic() atom = mol.GetAtomWithIdx(9) assert atom.GetAtomicNum() == 7 info = atom.GetPDBResidueInfo() assert info.GetResidueName() == 'HIS' assert info.GetResidueNumber() == 246 assert info.GetName().strip() == 'NE2' assert atom.GetIsAromatic() assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE # there is only one atom from the ring and it shouldn't be aromatic molfile = os.path.join(test_dir, '3cx9_TYR.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol) atom = mol.GetAtomWithIdx(14) assert atom.GetAtomicNum() == 6 info = atom.GetPDBResidueInfo() assert info.GetResidueName() == 'TYR' assert info.GetResidueNumber() == 138 assert info.GetName().strip() == 'CG' assert not atom.GetIsAromatic() assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_many_missing(): """Test parsing residues with **many** missing atoms and bonds""" molfile = os.path.join(test_dir, '2wb5_GLN.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol) assert mol.GetNumAtoms() == 5 assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE assert mol.GetAtomWithIdx(4).GetDegree() == 0 # test if removal works mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol, remove_incomplete=True) assert mol.GetNumAtoms() == 0 assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_remove_incomplete(): """Test removing residues with missing atoms""" molfile = os.path.join(test_dir, '3cx9_TYR.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) # keep all residues new_mol = PreparePDBMol(mol, remove_incomplete=False) assert new_mol.GetNumAtoms() == 23 residues = set() for atom in new_mol.GetAtoms(): residues.add(atom.GetPDBResidueInfo().GetResidueNumber()) assert residues, {137, 138 == 139} assert Chem.SanitizeMol(new_mol) == Chem.SanitizeFlags.SANITIZE_NONE # remove residue with missing sidechain new_mol = PreparePDBMol(mol, remove_incomplete=True) assert new_mol.GetNumAtoms() == 17 residues = set() for atom in new_mol.GetAtoms(): residues.add(atom.GetPDBResidueInfo().GetResidueNumber()) assert residues, {137 == 139} assert Chem.SanitizeMol(new_mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_custom_templates(): """Test using custom templates""" molfile = os.path.join(test_dir, '3cx9_TYR.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) templates = { 'TYR': 'CCC(N)C=O', 'LYS': 'NC(C(O)=O)CCCCN', 'LEU': 'CC(C)CC(N)C(=O)O', } mol_templates = {resname: Chem.MolFromSmiles(smi) for resname, smi in templates.items()} for kwargs in ({'custom_templates': {'TYR': 'CCC(N)C=O'}}, {'custom_templates': {'TYR': Chem.MolFromSmiles('CCC(N)C=O')}}, {'custom_templates': templates, 'replace_default_templates': True}, {'custom_templates': mol_templates, 'replace_default_templates': True}): # use TYR without sidechain - all matches should be complete new_mol = PreparePDBMol(mol, remove_incomplete=True, **kwargs) assert new_mol.GetNumAtoms() == 23 residues = set() for atom in new_mol.GetAtoms(): residues.add(atom.GetPDBResidueInfo().GetResidueNumber()) assert residues, {137, 138 == 139} assert Chem.SanitizeMol(new_mol) == Chem.SanitizeFlags.SANITIZE_NONE @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_add_missing_atoms(): # add missing atom at tryptophan molfile = os.path.join(test_dir, '5dhh_missingatomTRP.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=True) mol = Chem.RemoveHs(mol, sanitize=False) assert mol.GetNumAtoms() == 26 mol = PreparePDBMol(mol, add_missing_atoms=True) assert mol.GetNumAtoms() == 27 atom = mol.GetAtomWithIdx(21) assert atom.GetAtomicNum() == 6 info = atom.GetPDBResidueInfo() assert info.GetResidueName() == 'TRP' assert info.GetResidueNumber() == 175 assert info.GetName().strip() == 'C9' assert atom.IsInRing() assert atom.GetIsAromatic() assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE # add whole ring to tyrosine molfile = os.path.join(test_dir, '3cx9_TYR.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=True) mol = Chem.RemoveHs(mol, sanitize=False) assert mol.GetNumAtoms() == 23 mol = PreparePDBMol(mol, add_missing_atoms=True) assert mol.GetNumAtoms() == 29 atom = mol.GetAtomWithIdx(17) assert atom.GetAtomicNum() == 6 info = atom.GetPDBResidueInfo() assert info.GetResidueName() == 'TYR' assert info.GetResidueNumber() == 138 assert info.GetName().strip() == 'C6' assert atom.IsInRing() assert atom.GetIsAromatic() assert Chem.SanitizeMol(mol) == Chem.SanitizeFlags.SANITIZE_NONE # missing protein backbone atoms molfile = os.path.join(test_dir, '5ar7_HIS.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False) mol = Chem.RemoveHs(mol, sanitize=False) assert mol.GetNumAtoms() == 21 assert mol.GetNumBonds() == 19 mol = PreparePDBMol(mol, add_missing_atoms=True) assert mol.GetNumAtoms() == 25 assert mol.GetNumBonds() == 25 # missing nucleotide backbone atoms molfile = os.path.join(test_dir, '1bpx_missingBase.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False) mol = Chem.RemoveHs(mol, sanitize=False) assert mol.GetNumAtoms() == 301 assert mol.GetNumBonds() == 333 mol = PreparePDBMol(mol, add_missing_atoms=True) assert mol.GetNumAtoms() == 328 assert mol.GetNumBonds() == 366 @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_connected_residues(): molfile = os.path.join(test_dir, '4p6p_lig_zn.pdb') mol = Chem.MolFromPDBFile(molfile, sanitize=False, removeHs=False) mol = PreparePDBMol(mol) # we need to use fixer with rdkit < 2018 # residue which has neighbours assert IsResidueConnected(mol, range(120, 127)) # ligand assert not IsResidueConnected(mol, range(153, 167)) # fragments of two residues with pytest.raises(ValueError): IsResidueConnected(mol, range(5, 15)) @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_fetch_structures(): pdbid = '3ws8' tmpdir = tempfile.mkdtemp() mol1 = FetchStructure(pdbid) mol2 = FetchStructure(pdbid, cache_dir=tmpdir) mol3 = FetchStructure(pdbid, cache_dir=tmpdir) assert mol1.GetNumAtoms() == mol2.GetNumAtoms() assert mol1.GetNumAtoms() == mol3.GetNumAtoms() @pytest.mark.skipif(rdkit is None, reason="RDKit required") def test_prepare_complexes(): ids = [ '3WS9', # simple case with everything fine '3HLJ', # ligand not in report '3BYM', # non-existing ligand and backbone residue in report '2PIN', # two ligands with binding affinities '3CYU', # can't parse ligands properly '1A28', # multiple affinity types ] tmpdir = tempfile.mkdtemp() complexes = PrepareComplexes(ids, cache_dir=tmpdir) expected_values = { '3WS9': {'X4D': {'IC50': 92.0}}, '3BYM': {'AM0': {'IC50': 6.0}}, '2PIN': {'LEG': {'IC50': 1500.0}}, '3CYU': {'0CR': {'Kd': 60.0}}, '1A28': {'STR': {'Ki': 5.1}}, } values = {} for pdbid, pairs in complexes.items(): values[pdbid] = {} for resname, (_, ligand) in pairs.items(): values[pdbid][resname] = {k: float(v) for k, v in ligand.GetPropsAsDict().items()} assert expected_values.keys() == values.keys() for pdbid in expected_values: assert values[pdbid].keys() == expected_values[pdbid].keys() for resname in values[pdbid]: assert values[pdbid][resname].keys() == expected_values[pdbid][resname].keys() for key, val in values[pdbid][resname].items(): assert key in expected_values[pdbid][resname] assert_almost_equal(expected_values[pdbid][resname][key], val) for idx in expected_values: assert os.path.exists(os.path.join(tmpdir, idx, '%s.pdb' % idx))
bsd-3-clause
EmilioHerrera/OLV
views/user/login.php
1765
<?php /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model app\models\LoginForm */ use yii\bootstrap\ActiveForm; use yii\helpers\Html; $this->title = 'Login'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="user-login"> <div class="page-wrap"> <div class="col-md-6 col-md-offset-3"> <div class="panel"> <div class="panel-body"> <h1><?= Html::encode($this->title) ?></h1> <p>Please fill out the following fields to login:</p> <p>Your username is your email!</p> <?php $form = ActiveForm::begin([ 'id' => 'login-form', 'layout' => 'horizontal', 'fieldConfig' => [ 'template' => "{label}\n<div class=\"col-lg-9\">{input}</div>\n<div class=\"col-lg-12\">{error}</div>", 'labelOptions' => ['class' => 'col-lg-3 control-label text-center'], ], ]); ?> <?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?> <?= $form->field($model, 'password')->passwordInput() ?> <?= $form->field($model, 'rememberMe')->checkbox([ 'template' => "<div class=\"col-lg-offset-1 col-lg-12\">{input} {label}</div>\n<div class=\"col-lg-12\">{error}</div>", ]) ?> <div class="form-group"> <div class="col-lg-offset-1 col-lg-11"> <?= Html::submitButton('Login', ['class' => 'btn btn-success btn-raised', 'name' => 'login-button']) ?> </div> </div> <?php ActiveForm::end(); ?> </div> </div> </div> </div> </div>
bsd-3-clause
ethz-asl/elevation_mapping
elevation_mapping/include/elevation_mapping/sensor_processors/PerfectSensorProcessor.hpp
1436
/* * PerfectSensorProcessor.hpp * * Created on: Sep 28, 2014 * Author: Péter Fankhauser * Institute: ETH Zurich, ANYbotics */ #pragma once #include <elevation_mapping/sensor_processors/SensorProcessorBase.hpp> namespace elevation_mapping { /*! * Sensor processor for laser range sensors. */ class PerfectSensorProcessor : public SensorProcessorBase { public: /*! * Constructor. * @param nodeHandle the ROS node handle. * @param transformListener the ROS transform listener. */ PerfectSensorProcessor(ros::NodeHandle& nodeHandle, tf::TransformListener& transformListener); /*! * Destructor. */ virtual ~PerfectSensorProcessor(); private: /*! * Reads and verifies the parameters. * @return true if successful. */ bool readParameters(); /*! * Computes the elevation map height variances for each point in a point cloud with the * sensor model and the robot pose covariance. * @param[in] pointCloud the point cloud for which the variances are computed. * @param[in] robotPoseCovariance the robot pose covariance matrix. * @param[out] variances the elevation map height variances. * @return true if successful. */ virtual bool computeVariances( const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr pointCloud, const Eigen::Matrix<double, 6, 6>& robotPoseCovariance, Eigen::VectorXf& variances); }; } /* namespace elevation_mapping */
bsd-3-clause
danielga/gmsv_xconsole
source/IOStream.cpp
1988
/************************************************************************* * MultiLibrary - danielga.bitbucket.org/multilibrary * A C++ library that covers multiple low level systems. *------------------------------------------------------------------------ * Copyright (c) 2015, Daniel Almeida * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 * HOLDER 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. * *************************************************************************/ #include <IOStream.hpp> namespace MultiLibrary { } // namespace MultiLibrary
bsd-3-clause
fschulze/ploy
setup.py
1478
from setuptools import setup import os version = "1.0.4.dev0" here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() HISTORY = open(os.path.join(here, 'HISTORY.rst')).read() install_requires = [ 'lazy', 'paramiko', 'setuptools'] try: import argparse argparse # make pyflakes happy... except ImportError: install_requires.append('argparse >= 1.1') setup( version=version, description="A tool to manage servers through a central configuration. Plugins allow provisioning, configuration and other management tasks.", long_description=README + "\n\n" + HISTORY, name="ploy", author='Florian Schulze', author_email='florian.schulze@gmx.net', license="BSD 3-Clause License", url='http://github.com/ployground/ploy', classifiers=[ 'Environment :: Console', 'Intended Audience :: System Administrators', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Systems Administration'], include_package_data=True, zip_safe=False, packages=['ploy', 'ploy.tests'], install_requires=install_requires, entry_points=""" [console_scripts] ploy = ploy:ploy ploy-ssh = ploy:ploy_ssh [ploy.plugins] plain = ploy.plain:plugin """)
bsd-3-clause
fraunhoferfokus/particity
lib_data/src/main/java/de/fraunhofer/fokus/oefit/particity/service/persistence/AHSubscriptionActionableDynamicQuery.java
848
package de.fraunhofer.fokus.oefit.particity.service.persistence; import com.liferay.portal.kernel.dao.orm.BaseActionableDynamicQuery; import com.liferay.portal.kernel.exception.SystemException; import de.fraunhofer.fokus.oefit.particity.model.AHSubscription; import de.fraunhofer.fokus.oefit.particity.service.AHSubscriptionLocalServiceUtil; /** * @author Brian Wing Shun Chan * @generated */ public abstract class AHSubscriptionActionableDynamicQuery extends BaseActionableDynamicQuery { public AHSubscriptionActionableDynamicQuery() throws SystemException { setBaseLocalService(AHSubscriptionLocalServiceUtil.getService()); setClass(AHSubscription.class); setClassLoader(de.fraunhofer.fokus.oefit.particity.service.ClpSerializer.class.getClassLoader()); setPrimaryKeyPropertyName("subId"); } }
bsd-3-clause
Clinical-Genomics/scout
tests/server/blueprints/institutes/test_institute_controllers.py
2286
import copy from werkzeug.datastructures import MultiDict from scout.server.blueprints.institutes.controllers import cases, phenomodel_checkgroups_filter from scout.server.extensions import store def test_phenomodel_checkgroups_filter(app, institute_obj, hpo_checkboxes, omim_checkbox): """Test the controllers function that updates the phenotype model based on the model preview checkbox preferences""" # GIVEN a database with the required HPO terms (one parent term and one child term) store.hpo_term_collection.insert_many(hpo_checkboxes) # GIVEN a phenotype model with one panel and 3 checkboxes (checkbox2 nested inside checkbox1) hpo_id1 = hpo_checkboxes[0]["_id"] hpo_id2 = hpo_checkboxes[1]["_id"] omim_id = omim_checkbox["_id"] checkbox2 = dict( name=hpo_id2, description=hpo_checkboxes[1]["description"], ) checkbox1 = dict( name=hpo_id1, description=hpo_checkboxes[1]["description"], children=[checkbox2], # nested checkbox with HPO term 2 ) checkbox3 = {"name": omim_id, "description": omim_checkbox["description"]} test_model = dict( institute=institute_obj["_id"], name="Test model", subpanels=dict(panel1=dict(checkboxes={hpo_id1: checkbox1, omim_id: checkbox3})), ) store.phenomodel_collection.insert_one(test_model) model_obj = store.phenomodel_collection.find_one() # THEN 2 checkboxes should show at the top level assert model_obj["subpanels"]["panel1"]["checkboxes"][hpo_id1] assert model_obj["subpanels"]["panel1"]["checkboxes"][omim_id] assert hpo_id2 not in model_obj["subpanels"]["panel1"]["checkboxes"] with app.app_context(): # WHEN phenotype checkboxes are updated to keep only the nested checkbox2 checked_terms = MultiDict({"cheked_terms": [".".join(["panel1", hpo_id1, hpo_id2])]}) updated_model = phenomodel_checkgroups_filter(model_obj, checked_terms) # THEN the right checkbox should be present in submodel checkboxes dictionary assert updated_model["subpanels"]["panel1"]["checkboxes"][hpo_id2] assert hpo_id1 not in updated_model["subpanels"]["panel1"]["checkboxes"] assert omim_id not in updated_model["subpanels"]["panel1"]["checkboxes"]
bsd-3-clause
vinpel/gaspSync
tests/acceptance/tokenServerCept.php
1039
<?php //\Codeception\Util\Debug::debug($hawk); $email=time().'test@exemple.com'; $I = new AcceptanceTester($scenario); $I->wantTo('ensure that the token server works'); //get valid hawk / browserid for testing $I->wantTo('grab test hawk & assertion for testing'); $I->sendGET('/index-test.php/token/test-get-assertion',['email'=>$email]); $assertion=$I->grabDataFromJsonResponse("assertion"); $I->wantTo('test rejection without an assertion'); $I->sendGET('/index-test.php/tokenServer/1.0/sync/1.5'); $I->seeResponseContainsJson([ 'error' => 'Unauthorized', ] ); $I->seeResponseCodeIs(401); $I->wantTo('get an authToken'); $I->haveHttpHeader('authorization',$assertion); $I->sendGET('/index-test.php/tokenServer/1.0/sync/1.5',array()); $I->seeResponseCodeIs(200); $I->seeResponseContainsJson(['status' => 'okay']); $uid=$I->grabDataFromJsonResponse("uid"); $api_endpoint=$I->grabDataFromJsonResponse("api_endpoint"); $id=$I->grabDataFromJsonResponse("id"); $key=$I->grabDataFromJsonResponse("key"); ?>
bsd-3-clause
CartoDB/cartodb
app/models/carto/map.rb
6900
require 'active_record' require_relative './carto_json_serializer' require_dependency 'common/map_common' require_dependency 'carto/bounding_box_utils' class Carto::Map < ActiveRecord::Base include Carto::MapBoundaries has_many :layers_maps, dependent: :destroy has_many :layers, -> { order(:order) }, class_name: 'Carto::Layer', through: :layers_maps, after_add: Proc.new { |map, layer| layer.after_added_to_map(map) } has_many :base_layers, -> { order(:order) }, class_name: 'Carto::Layer', through: :layers_maps, source: :layer # autosave must be explicitly disabled due to https://github.com/rails/rails/issues/9336 has_one :user_table, class_name: Carto::UserTable, inverse_of: :map, dependent: :destroy, autosave: false belongs_to :user # Autosave disabled because this caused the `inverse_of` to break (visualization.map != self) until `reload` # Fixed in Rails 5 https://github.com/rails/rails/pull/23197 has_one :visualization, class_name: Carto::Visualization, inverse_of: :map, autosave: false # bounding_box_sw, bounding_box_new and center should probably be JSON serialized fields # However, many callers expect to get an string (and do the JSON deserialization themselves), mainly in presenters # So for now, we are just treating them as strings (see the .to_s in the constant below), but this could be improved DEFAULT_OPTIONS = { zoom: 3, bounding_box_sw: [Carto::BoundingBoxUtils::DEFAULT_BOUNDS[:miny], Carto::BoundingBoxUtils::DEFAULT_BOUNDS[:minx]].to_s, bounding_box_ne: [Carto::BoundingBoxUtils::DEFAULT_BOUNDS[:maxy], Carto::BoundingBoxUtils::DEFAULT_BOUNDS[:maxx]].to_s, provider: 'leaflet', center: [30, 0].to_s }.freeze serialize :options, ::Carto::CartoJsonSerializer validates :options, carto_json_symbolizer: true validate :validate_options after_initialize :ensure_options after_save :notify_map_change after_save :save_table # Manual save, since autosave is disabled def data_layers layers.select(&:data_layer?) end def carto_layers layers.select(&:carto?) end def user_layers layers.select(&:user_layer?) end def torque_layers layers.select(&:torque?) end def other_layers layers.reject(&:carto?) .reject(&:tiled?) .reject(&:background?) .reject(&:gmapsbase?) .reject(&:wms?) end def named_map_layers layers.select(&:named_map_layer?) end def viz_updated_at latest_mapcap = visualization.latest_mapcap latest_mapcap ? latest_mapcap.created_at : get_the_last_time_tiles_have_changed_to_render_it_in_vizjsons end def self.provider_for_baselayer_kind(kind) kind == 'tiled' ? 'leaflet' : 'googlemaps' end # (lat,lon) points on all map data def center_data (center.nil? || center == '') ? DEFAULT_OPTIONS[:center] : center.gsub(/\[|\]|\s*/, '').split(',') end def view_bounds_data if view_bounds_sw.nil? || view_bounds_sw == '' bbox_sw = DEFAULT_OPTIONS[:bounding_box_sw] else bbox_sw = view_bounds_sw.gsub(/\[|\]|\s*/, '').split(',').map(&:to_f) end if view_bounds_ne.nil? || view_bounds_ne == '' bbox_ne = DEFAULT_OPTIONS[:bounding_box_ne] else bbox_ne = view_bounds_ne.gsub(/\[|\]|\s*/, '').split(',').map(&:to_f) end { # LowerCorner longitude, in decimal degrees west: bbox_sw[1], # LowerCorner latitude, in decimal degrees south: bbox_sw[0], # UpperCorner longitude, in decimal degrees east: bbox_ne[1], # UpperCorner latitude, in decimal degrees north: bbox_ne[0] } end def writable_by_user?(user) visualization.writable_by?(user) end def contains_layer?(layer) return false unless layer layers_maps.map(&:layer_id).include?(layer.id) end def notify_map_change visualization.try(:invalidate_after_commit) end alias :force_notify_map_change :notify_map_change def update_dataset_dependencies data_layers.each(&:register_table_dependencies) end def dashboard_menu=(value) options[:dashboard_menu] = value end def dashboard_menu options[:dashboard_menu] end def layer_selector=(value) options[:layer_selector] = value end def layer_selector options[:layer_selector] end def admits_layer?(layer) return admits_more_torque_layers? if layer.torque? return admits_more_data_layers? if layer.data_layer? return admits_more_base_layers?(layer) if layer.base_layer? end def can_add_layer?(user, layer) return true if layer.base_layer? return false if user.max_layers && user.max_layers <= data_layers.count visualization.writable_by?(user) end def process_privacy_in(layer) if layer.uses_private_tables? && visualization.can_be_private? visualization.privacy = Carto::Visualization::PRIVACY_PRIVATE visualization.save end end private def save_table if user_table && !user_table.persisted? user_table.map = self user_table.save! end end def admits_more_data_layers? !visualization.canonical? || data_layers.empty? end def admits_more_torque_layers? !visualization.canonical? || torque_layers.empty? end def admits_more_base_layers?(layer) # no basemap layer, always allow return true if user_layers.empty? # have basemap? then allow only if comes on top (for labels) layer.order >= layers.last.order end def ensure_options self.zoom ||= DEFAULT_OPTIONS[:zoom] self.bounding_box_sw ||= DEFAULT_OPTIONS[:bounding_box_sw] self.bounding_box_ne ||= DEFAULT_OPTIONS[:bounding_box_ne] self.center ||= DEFAULT_OPTIONS[:center] self.provider ||= DEFAULT_OPTIONS[:provider] self.options ||= {} options[:dashboard_menu] = true if options[:dashboard_menu].nil? options[:layer_selector] = false if options[:layer_selector].nil? options[:legends] = legends if options[:legends].nil? options[:scrollwheel] = scrollwheel if options[:scrollwheel].nil? options end def validate_options location = "#{Rails.root}/lib/formats/map/options.json" schema = Carto::Definition.instance.load_from_file(location) options_wia = options.with_indifferent_access json_errors = JSON::Validator.fully_validate(schema, options_wia) errors.add(:options, json_errors.join(', ')) if json_errors.any? end def get_the_last_time_tiles_have_changed_to_render_it_in_vizjsons from_table = user_table.service.data_last_modified if user_table [from_table, data_layers.map(&:updated_at)].flatten.compact.max end def table_name user_table.try(:name) end end
bsd-3-clause
bgwines/project-euler
src/solved/problem479/problem479.cpp
2649
/* Note: this solution requires FLINT (http://www.flintlib.org/) Problem solved together with Alex Quach */ #include <cmath> #include <stdlib.h> #include <stdio.h> #include "flint.h" #include "fmpz.h" #include "fmpz_mat.h" #include "arith.h" const long K = 1000000007; const long N = pow(10, 6); ////////////////////////////////////////// void fmpz_mul_mod(fmpz_t& result, const fmpz_t& a, const fmpz_t& b) { fmpz_mul(result, a, b); fmpz_mod_ui(result, result, K); } bool geq_ui(fmpz_t& a, long b) { return fmpz_cmp_ui(a, b) >= 0; } bool leq_ui(fmpz_t& a, long b) { return fmpz_cmp_ui(a, b) <= 0; } void fmpz_add_mod(fmpz_t& result, const fmpz_t& a, const fmpz_t& b) { fmpz_add(result, a, b); if (geq_ui(result, K)) { fmpz_sub_ui(result, result, K); } } void fmpz_sub_mod(fmpz_t& result, const fmpz_t& a, const fmpz_t& b) { fmpz_sub(result, a, b); if (leq_ui(result, 0)) { fmpz_add_ui(result, result, K); } } long div(long numerator_long, long denominator_long) { fmpz_t numerator; fmpz_init(numerator); fmpz_set_ui(numerator, numerator_long); fmpz_t denominator; fmpz_init(denominator); fmpz_set_ui(denominator, denominator_long); fmpz_t KK; fmpz_init(KK); fmpz_set_ui(KK, K); fmpz_invmod(denominator, denominator, KK); fmpz_t result; fmpz_init(result); fmpz_mul_mod(result, numerator, denominator); return fmpz_get_ui(result); } const int ADD = 0; const int SUB = 1; const int MUL = 2; const int POW = 3; long op(long a_long, long b_long, int op) { fmpz_t KK; fmpz_init(KK); fmpz_set_ui(KK, K); fmpz_t a; fmpz_init(a); fmpz_set_ui(a, a_long); fmpz_t b; fmpz_init(b); fmpz_set_ui(b, b_long); if (op == ADD) fmpz_add_mod(a, a, b); if (op == SUB) fmpz_sub_mod(a, a, b); if (op == MUL) fmpz_mul_mod(a, a, b); if (op == POW) fmpz_powm_ui(a, a, fmpz_get_ui(b), KK); return fmpz_get_ui(a); } long mul(long a, long b) { return op(a, b, MUL); } long add(long a, long b) { return op(a, b, ADD); } long sub(long a, long b) { return op(a, b, SUB); } long mul3(long a, long b, long c) { return mul(mul(a, b), c); } long pow_mod(long base, long exp) { return op(base, exp, POW); } //////////////////////////////////////////////// // Z(k) = (a_k + b_k) * (b_k + c_k) * (c_k + a_k) long Z(long k) { return sub(1, mul(k, k)); } long geosum(long k, long n) { long numerator = sub(1, pow_mod(Z(k), n+1)); long denominator = sub(1, Z(k)); return div(numerator, denominator); } long S(long n) { long sum = 0; for (int k=1; k<=n; k++) { sum = add(sum, geosum(k, n)); } return sub(sum, n); } int main(int argc, char const *argv[]) { printf("S(%lu) = %lu\n", N, S(N)); return 0; }
bsd-3-clause
jchavanton/webrtc
modules/bitrate_controller/bitrate_controller_unittest.cc
16165
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <algorithm> #include <vector> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/bitrate_controller/include/bitrate_controller.h" #include "webrtc/modules/pacing/mock/mock_paced_sender.h" #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h" using ::testing::Exactly; using ::testing::Return; using webrtc::BitrateController; using webrtc::BitrateObserver; using webrtc::PacedSender; using webrtc::RtcpBandwidthObserver; uint8_t WeightedLoss(int num_packets1, uint8_t fraction_loss1, int num_packets2, uint8_t fraction_loss2) { int weighted_sum = num_packets1 * fraction_loss1 + num_packets2 * fraction_loss2; int total_num_packets = num_packets1 + num_packets2; return (weighted_sum + total_num_packets / 2) / total_num_packets; } webrtc::RTCPReportBlock CreateReportBlock( uint32_t remote_ssrc, uint32_t source_ssrc, uint8_t fraction_lost, uint32_t extended_high_sequence_number) { return webrtc::RTCPReportBlock(remote_ssrc, source_ssrc, fraction_lost, 0, extended_high_sequence_number, 0, 0, 0); } class TestBitrateObserver: public BitrateObserver { public: TestBitrateObserver() : last_bitrate_(0), last_fraction_loss_(0), last_rtt_(0) { } virtual void OnNetworkChanged(uint32_t bitrate, uint8_t fraction_loss, int64_t rtt) { last_bitrate_ = static_cast<int>(bitrate); last_fraction_loss_ = fraction_loss; last_rtt_ = rtt; } int last_bitrate_; uint8_t last_fraction_loss_; int64_t last_rtt_; }; class BitrateControllerTest : public ::testing::Test { protected: BitrateControllerTest() : clock_(0) {} ~BitrateControllerTest() {} virtual void SetUp() { controller_ = BitrateController::CreateBitrateController(&clock_, &bitrate_observer_); controller_->SetStartBitrate(kStartBitrateBps); EXPECT_EQ(kStartBitrateBps, bitrate_observer_.last_bitrate_); controller_->SetMinMaxBitrate(kMinBitrateBps, kMaxBitrateBps); EXPECT_EQ(kStartBitrateBps, bitrate_observer_.last_bitrate_); bandwidth_observer_ = controller_->CreateRtcpBandwidthObserver(); } virtual void TearDown() { delete bandwidth_observer_; delete controller_; } const int kMinBitrateBps = 100000; const int kStartBitrateBps = 200000; const int kMaxBitrateBps = 300000; const int kDefaultMinBitrateBps = 10000; const int kDefaultMaxBitrateBps = 1000000000; webrtc::SimulatedClock clock_; TestBitrateObserver bitrate_observer_; BitrateController* controller_; RtcpBandwidthObserver* bandwidth_observer_; }; TEST_F(BitrateControllerTest, DefaultMinMaxBitrate) { // Receive successively lower REMBs, verify the reserved bitrate is deducted. controller_->SetMinMaxBitrate(0, 0); EXPECT_EQ(kStartBitrateBps, bitrate_observer_.last_bitrate_); bandwidth_observer_->OnReceivedEstimatedBitrate(kDefaultMinBitrateBps / 2); EXPECT_EQ(kDefaultMinBitrateBps, bitrate_observer_.last_bitrate_); bandwidth_observer_->OnReceivedEstimatedBitrate(2 * kDefaultMaxBitrateBps); clock_.AdvanceTimeMilliseconds(1000); controller_->Process(); EXPECT_EQ(kDefaultMaxBitrateBps, bitrate_observer_.last_bitrate_); } TEST_F(BitrateControllerTest, OneBitrateObserverOneRtcpObserver) { // First REMB applies immediately. int64_t time_ms = 1001; webrtc::ReportBlockList report_blocks; report_blocks.push_back(CreateReportBlock(1, 2, 0, 1)); bandwidth_observer_->OnReceivedEstimatedBitrate(200000); EXPECT_EQ(200000, bitrate_observer_.last_bitrate_); EXPECT_EQ(0, bitrate_observer_.last_fraction_loss_); EXPECT_EQ(0, bitrate_observer_.last_rtt_); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); report_blocks.clear(); time_ms += 2000; // Receive a high remb, test bitrate inc. bandwidth_observer_->OnReceivedEstimatedBitrate(400000); // Test bitrate increase 8% per second. report_blocks.push_back(CreateReportBlock(1, 2, 0, 21)); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_EQ(217000, bitrate_observer_.last_bitrate_); EXPECT_EQ(0, bitrate_observer_.last_fraction_loss_); EXPECT_EQ(50, bitrate_observer_.last_rtt_); time_ms += 1000; report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 41)); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_EQ(235360, bitrate_observer_.last_bitrate_); EXPECT_EQ(0, bitrate_observer_.last_fraction_loss_); EXPECT_EQ(50, bitrate_observer_.last_rtt_); time_ms += 1000; report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 61)); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_EQ(255189, bitrate_observer_.last_bitrate_); time_ms += 1000; report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 81)); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_EQ(276604, bitrate_observer_.last_bitrate_); time_ms += 1000; report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 801)); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_EQ(299732, bitrate_observer_.last_bitrate_); time_ms += 1000; // Reach max cap. report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 101)); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_EQ(300000, bitrate_observer_.last_bitrate_); time_ms += 1000; report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 141)); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_EQ(300000, bitrate_observer_.last_bitrate_); // Test that a low delay-based estimate limits the combined estimate. controller_->UpdateDelayBasedEstimate(280000); EXPECT_EQ(280000, bitrate_observer_.last_bitrate_); // Test that a low REMB limits the combined estimate. bandwidth_observer_->OnReceivedEstimatedBitrate(250000); EXPECT_EQ(250000, bitrate_observer_.last_bitrate_); EXPECT_EQ(0, bitrate_observer_.last_fraction_loss_); EXPECT_EQ(50, bitrate_observer_.last_rtt_); bandwidth_observer_->OnReceivedEstimatedBitrate(1000); EXPECT_EQ(100000, bitrate_observer_.last_bitrate_); } TEST_F(BitrateControllerTest, OneBitrateObserverTwoRtcpObservers) { // REMBs during the first 2 seconds apply immediately. int64_t time_ms = 1; webrtc::ReportBlockList report_blocks; report_blocks.push_back(CreateReportBlock(1, 2, 0, 1)); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); report_blocks.clear(); time_ms += 500; RtcpBandwidthObserver* second_bandwidth_observer = controller_->CreateRtcpBandwidthObserver(); // Test start bitrate. report_blocks.push_back(CreateReportBlock(1, 2, 0, 21)); second_bandwidth_observer->OnReceivedRtcpReceiverReport( report_blocks, 100, 1); EXPECT_EQ(217000, bitrate_observer_.last_bitrate_); EXPECT_EQ(0, bitrate_observer_.last_fraction_loss_); EXPECT_EQ(100, bitrate_observer_.last_rtt_); time_ms += 500; // Test bitrate increase 8% per second. report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 21)); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); time_ms += 500; second_bandwidth_observer->OnReceivedRtcpReceiverReport( report_blocks, 100, time_ms); EXPECT_EQ(235360, bitrate_observer_.last_bitrate_); EXPECT_EQ(0, bitrate_observer_.last_fraction_loss_); EXPECT_EQ(100, bitrate_observer_.last_rtt_); time_ms += 500; // Extra report should not change estimate. report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 31)); second_bandwidth_observer->OnReceivedRtcpReceiverReport( report_blocks, 100, time_ms); EXPECT_EQ(235360, bitrate_observer_.last_bitrate_); time_ms += 500; report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 41)); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_EQ(255189, bitrate_observer_.last_bitrate_); // Second report should not change estimate. report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 41)); second_bandwidth_observer->OnReceivedRtcpReceiverReport( report_blocks, 100, time_ms); EXPECT_EQ(255189, bitrate_observer_.last_bitrate_); time_ms += 1000; // Reports from only one bandwidth observer is ok. report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 61)); second_bandwidth_observer->OnReceivedRtcpReceiverReport( report_blocks, 50, time_ms); EXPECT_EQ(276604, bitrate_observer_.last_bitrate_); time_ms += 1000; report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 81)); second_bandwidth_observer->OnReceivedRtcpReceiverReport( report_blocks, 50, time_ms); EXPECT_EQ(299732, bitrate_observer_.last_bitrate_); time_ms += 1000; // Reach max cap. report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 121)); second_bandwidth_observer->OnReceivedRtcpReceiverReport( report_blocks, 50, time_ms); EXPECT_EQ(300000, bitrate_observer_.last_bitrate_); time_ms += 1000; report_blocks.clear(); report_blocks.push_back(CreateReportBlock(1, 2, 0, 141)); second_bandwidth_observer->OnReceivedRtcpReceiverReport( report_blocks, 50, time_ms); EXPECT_EQ(300000, bitrate_observer_.last_bitrate_); // Test that a low REMB trigger immediately. // We don't care which bandwidth observer that delivers the REMB. second_bandwidth_observer->OnReceivedEstimatedBitrate(250000); EXPECT_EQ(250000, bitrate_observer_.last_bitrate_); EXPECT_EQ(0, bitrate_observer_.last_fraction_loss_); EXPECT_EQ(50, bitrate_observer_.last_rtt_); // Min cap. bandwidth_observer_->OnReceivedEstimatedBitrate(1000); EXPECT_EQ(100000, bitrate_observer_.last_bitrate_); delete second_bandwidth_observer; } TEST_F(BitrateControllerTest, OneBitrateObserverMultipleReportBlocks) { uint32_t sequence_number[2] = {0, 0xFF00}; const int kStartBitrate = 200000; const int kMinBitrate = 100000; const int kMaxBitrate = 300000; controller_->SetStartBitrate(kStartBitrate); controller_->SetMinMaxBitrate(kMinBitrate, kMaxBitrate); // REMBs during the first 2 seconds apply immediately. int64_t time_ms = 1001; webrtc::ReportBlockList report_blocks; report_blocks.push_back(CreateReportBlock(1, 2, 0, sequence_number[0])); bandwidth_observer_->OnReceivedEstimatedBitrate(kStartBitrate); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); report_blocks.clear(); time_ms += 2000; // Receive a high REMB, test bitrate increase. bandwidth_observer_->OnReceivedEstimatedBitrate(400000); int last_bitrate = 0; // Ramp up to max bitrate. for (int i = 0; i < 6; ++i) { report_blocks.push_back(CreateReportBlock(1, 2, 0, sequence_number[0])); report_blocks.push_back(CreateReportBlock(1, 3, 0, sequence_number[1])); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_GT(bitrate_observer_.last_bitrate_, last_bitrate); EXPECT_EQ(0, bitrate_observer_.last_fraction_loss_); EXPECT_EQ(50, bitrate_observer_.last_rtt_); last_bitrate = bitrate_observer_.last_bitrate_; time_ms += 1000; sequence_number[0] += 20; sequence_number[1] += 1; report_blocks.clear(); } EXPECT_EQ(kMaxBitrate, bitrate_observer_.last_bitrate_); // Packet loss on the first stream. Verify that bitrate decreases. report_blocks.push_back(CreateReportBlock(1, 2, 50, sequence_number[0])); report_blocks.push_back(CreateReportBlock(1, 3, 0, sequence_number[1])); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_LT(bitrate_observer_.last_bitrate_, last_bitrate); EXPECT_EQ(WeightedLoss(20, 50, 1, 0), bitrate_observer_.last_fraction_loss_); EXPECT_EQ(50, bitrate_observer_.last_rtt_); last_bitrate = bitrate_observer_.last_bitrate_; sequence_number[0] += 20; sequence_number[1] += 20; time_ms += 1000; report_blocks.clear(); // Packet loss on the second stream. Verify that bitrate decreases. report_blocks.push_back(CreateReportBlock(1, 2, 0, sequence_number[0])); report_blocks.push_back(CreateReportBlock(1, 3, 75, sequence_number[1])); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_LT(bitrate_observer_.last_bitrate_, last_bitrate); EXPECT_EQ(WeightedLoss(20, 0, 20, 75), bitrate_observer_.last_fraction_loss_); EXPECT_EQ(50, bitrate_observer_.last_rtt_); last_bitrate = bitrate_observer_.last_bitrate_; sequence_number[0] += 20; sequence_number[1] += 1; time_ms += 1000; report_blocks.clear(); // All packets lost on stream with few packets, no back-off. report_blocks.push_back(CreateReportBlock(1, 2, 1, sequence_number[0])); report_blocks.push_back(CreateReportBlock(1, 3, 255, sequence_number[1])); bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, 50, time_ms); EXPECT_EQ(bitrate_observer_.last_bitrate_, last_bitrate); EXPECT_EQ(WeightedLoss(20, 1, 1, 255), bitrate_observer_.last_fraction_loss_); EXPECT_EQ(50, bitrate_observer_.last_rtt_); last_bitrate = bitrate_observer_.last_bitrate_; sequence_number[0] += 20; sequence_number[1] += 1; report_blocks.clear(); } TEST_F(BitrateControllerTest, SetReservedBitrate) { // Receive successively lower REMBs, verify the reserved bitrate is deducted. controller_->SetReservedBitrate(0); bandwidth_observer_->OnReceivedEstimatedBitrate(400000); EXPECT_EQ(200000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(50000); bandwidth_observer_->OnReceivedEstimatedBitrate(400000); EXPECT_EQ(150000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(0); bandwidth_observer_->OnReceivedEstimatedBitrate(250000); EXPECT_EQ(200000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(50000); bandwidth_observer_->OnReceivedEstimatedBitrate(250000); EXPECT_EQ(150000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(0); bandwidth_observer_->OnReceivedEstimatedBitrate(200000); EXPECT_EQ(200000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(30000); bandwidth_observer_->OnReceivedEstimatedBitrate(200000); EXPECT_EQ(170000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(0); bandwidth_observer_->OnReceivedEstimatedBitrate(160000); EXPECT_EQ(160000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(30000); bandwidth_observer_->OnReceivedEstimatedBitrate(160000); EXPECT_EQ(130000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(0); bandwidth_observer_->OnReceivedEstimatedBitrate(120000); EXPECT_EQ(120000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(10000); bandwidth_observer_->OnReceivedEstimatedBitrate(120000); EXPECT_EQ(110000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(0); bandwidth_observer_->OnReceivedEstimatedBitrate(120000); EXPECT_EQ(120000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(50000); bandwidth_observer_->OnReceivedEstimatedBitrate(120000); // Limited by min bitrate. EXPECT_EQ(100000, bitrate_observer_.last_bitrate_); controller_->SetReservedBitrate(10000); bandwidth_observer_->OnReceivedEstimatedBitrate(1); EXPECT_EQ(100000, bitrate_observer_.last_bitrate_); }
bsd-3-clause
wsldl123292/jodd
jodd-json/src/main/java/jodd/json/impl/FloatArrayJsonSerializer.java
566
// Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved. package jodd.json.impl; import jodd.json.JsonContext; import jodd.json.TypeJsonSerializer; /** * Serializes float arrays. */ public class FloatArrayJsonSerializer implements TypeJsonSerializer<float[]> { public void serialize(JsonContext jsonContext, float[] array) { jsonContext.writeOpenArray(); for (int i = 0; i < array.length; i++) { if (i > 0) { jsonContext.writeComma(); } jsonContext.write(Float.toString(array[i])); } jsonContext.writeCloseArray(); } }
bsd-3-clause
rad8329/Cordillera
layouts/error.php
1246
<?php /* @var string $content Content of buffer */ /* @var \cordillera\middlewares\Layout $this */ ?> <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><?= $this->getProperty('title', 'Error') ?></title> <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="<?= app()->request->base_url ?>media/css/normalize.css"> <link rel="stylesheet" type="text/css" href="<?= app()->request->base_url ?>media/css/cordillera.css"> <script src="//code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js" type="text/javascript"></script> </head> <body class="error"> <h1><?= $this->getProperty('title', 'Error') ?></h1> <div class="alert-danger alert fade in"> <i class="fa fa-exclamation-triangle"></i>&nbsp;<?= $content ?> </div> </body> </html>
bsd-3-clause
zengjichuan/jetuum
src/petuum_ps_common/util/stats.cpp
32829
// Copyright (c) 2014, Sailing Lab // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // 3. Neither the name of the <ORGANIZATION> 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 HOLDER 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. //Author: Jinliang Wei #include <petuum_ps_common/util/stats.hpp> #include <petuum_ps_common/include/constants.hpp> #include <glog/logging.h> #include <sstream> #include <fstream> namespace petuum { TableGroupConfig Stats::table_group_config_; std::string Stats::stats_path_; boost::thread_specific_ptr<ThreadType> Stats::thread_type_; boost::thread_specific_ptr<AppThreadStats> Stats::app_thread_stats_; boost::thread_specific_ptr<BgThreadStats> Stats::bg_thread_stats_; boost::thread_specific_ptr<ServerThreadStats> Stats::server_thread_stats_; boost::thread_specific_ptr<NameNodeThreadStats> Stats::name_node_thread_stats_; std::mutex Stats::stats_mtx_; std::vector<double> Stats::app_thread_life_sec_; std::vector<double> Stats::app_load_data_sec_; std::vector<double> Stats::app_init_sec_; std::vector<double> Stats::app_bootstrap_sec_; std::vector<double> Stats::app_accum_comp_sec_vec_; std::vector<double> Stats::app_accum_comm_block_sec_; double Stats::app_sum_accum_comm_block_sec_ = 0; double Stats::app_sum_approx_ssp_get_hit_sec_ = 0; double Stats::app_sum_approx_inc_sec_ = 0; double Stats::app_sum_approx_batch_inc_sec_ = 0; std::string Stats::app_defined_accum_sec_name_; std::vector<double> Stats::app_defined_accum_sec_vec_; std::string Stats::app_defined_vec_name_; std::vector<double> Stats::app_defined_vec_; std::string Stats::app_defined_accum_val_name_; double Stats::app_defined_accum_val_; boost::unordered_map<int32_t, AppThreadPerTableStats> Stats::table_stats_; double Stats::app_accum_comp_sec_ = 0; double Stats::app_accum_obj_comp_sec_ = 0; double Stats::app_accum_tg_clock_sec_ = 0; double Stats::bg_accum_clock_end_oplog_serialize_sec_ = 0; double Stats::bg_accum_total_oplog_serialize_sec_ = 0; double Stats::bg_accum_server_push_row_apply_sec_ = 0; double Stats::bg_accum_oplog_sent_mb_ = 0; double Stats::bg_accum_server_push_row_recv_mb_ = 0; std::vector<double> Stats::bg_per_clock_oplog_sent_mb_; std::vector<double> Stats::bg_per_clock_server_push_row_recv_mb_; double Stats::server_accum_apply_oplog_sec_; double Stats::server_accum_push_row_sec_; double Stats::server_accum_oplog_recv_mb_; double Stats::server_accum_push_row_mb_; std::vector<double> Stats::server_per_clock_oplog_recv_mb_; std::vector<double> Stats::server_per_clock_push_row_mb_; void Stats::Init(const TableGroupConfig &table_group_config) { table_group_config_ = table_group_config; std::stringstream stats_path_ss; stats_path_ss << table_group_config.stats_path; stats_path_ss << "." << table_group_config.client_id; stats_path_ = stats_path_ss.str(); } void Stats::RegisterThread(ThreadType thread_type) { thread_type_.reset(new ThreadType); *thread_type_ = thread_type; switch (thread_type) { case kAppThread: app_thread_stats_.reset(new AppThreadStats); break; case kBgThread: bg_thread_stats_.reset(new BgThreadStats); break; case kServerThread: server_thread_stats_.reset(new ServerThreadStats); break; case kNameNodeThread: name_node_thread_stats_.reset(new NameNodeThreadStats); break; default: LOG(FATAL) << "Unrecognized thread type " << thread_type; } } void Stats::DeregisterThread() { switch(*thread_type_) { case kAppThread: DeregisterAppThread(); break; case kBgThread: DeregisterBgThread(); break; case kServerThread: DeregisterServerThread(); break; case kNameNodeThread: break; default: LOG(FATAL) << "Unrecognized thread type " << *thread_type_; } } void Stats::DeregisterAppThread() { std::lock_guard<std::mutex> lock(stats_mtx_); app_thread_life_sec_.push_back( app_thread_stats_->thread_life_timer.elapsed()); if (app_thread_stats_->load_data_sec > 0.0) app_load_data_sec_.push_back(app_thread_stats_->load_data_sec); if (app_thread_stats_->init_sec > 0.0) app_init_sec_.push_back(app_thread_stats_->init_sec); if (app_thread_stats_->bootstrap_sec > 0.0) app_bootstrap_sec_.push_back(app_thread_stats_->bootstrap_sec); if (app_thread_stats_->accum_comp_sec > 0.0) app_accum_comp_sec_vec_.push_back(app_thread_stats_->accum_comp_sec); app_defined_accum_sec_vec_.push_back(app_thread_stats_->app_defined_accum_sec); app_defined_accum_val_ += app_thread_stats_->app_defined_accum_val; app_accum_comp_sec_ += app_thread_stats_->accum_comp_sec; app_accum_obj_comp_sec_ += app_thread_stats_->accum_obj_comp_sec; app_accum_tg_clock_sec_ += app_thread_stats_->accum_tg_clock_sec; double my_accum_comm_block_sec = 0.0; for (auto table_stats_iter = app_thread_stats_->table_stats.begin(); table_stats_iter != app_thread_stats_->table_stats.end(); table_stats_iter++) { int32_t table_id = table_stats_iter->first; AppThreadPerTableStats &thread_table_stats = table_stats_iter->second; table_stats_[table_id].num_get += thread_table_stats.num_get; table_stats_[table_id].num_ssp_get_hit += thread_table_stats.num_ssp_get_hit; table_stats_[table_id].num_ssp_get_miss += thread_table_stats.num_ssp_get_miss; table_stats_[table_id].num_ssp_get_hit_sampled += thread_table_stats.num_ssp_get_hit_sampled; table_stats_[table_id].num_ssp_get_miss_sampled += thread_table_stats.num_ssp_get_miss_sampled; table_stats_[table_id].accum_sample_ssp_get_hit_sec += thread_table_stats.accum_sample_ssp_get_hit_sec; table_stats_[table_id].accum_sample_ssp_get_miss_sec += thread_table_stats.accum_sample_ssp_get_miss_sec; table_stats_[table_id].num_ssppush_get_comm_block += thread_table_stats.num_ssppush_get_comm_block; table_stats_[table_id].accum_ssppush_get_comm_block_sec += thread_table_stats.accum_ssppush_get_comm_block_sec; my_accum_comm_block_sec += thread_table_stats.accum_ssppush_get_comm_block_sec; table_stats_[table_id].accum_ssp_get_server_fetch_sec += thread_table_stats.accum_ssp_get_server_fetch_sec; my_accum_comm_block_sec += thread_table_stats.accum_ssp_get_server_fetch_sec; table_stats_[table_id].num_inc += thread_table_stats.num_inc; table_stats_[table_id].num_inc_sampled += thread_table_stats.num_inc_sampled; table_stats_[table_id].accum_sample_inc_sec += thread_table_stats.accum_sample_inc_sec; table_stats_[table_id].num_batch_inc += thread_table_stats.num_batch_inc; table_stats_[table_id].num_batch_inc_sampled += thread_table_stats.num_batch_inc_sampled; table_stats_[table_id].accum_sample_batch_inc_sec += thread_table_stats.accum_sample_batch_inc_sec; table_stats_[table_id].num_thread_get += thread_table_stats.num_thread_get; table_stats_[table_id].accum_sample_thread_get_sec += table_stats_[table_id].accum_sample_thread_get_sec; table_stats_[table_id].num_thread_inc += thread_table_stats.num_thread_inc; table_stats_[table_id].accum_sample_thread_inc_sec += thread_table_stats.accum_sample_thread_inc_sec; table_stats_[table_id].num_thread_batch_inc += thread_table_stats.num_thread_batch_inc; table_stats_[table_id].accum_sample_thread_batch_inc_sec += thread_table_stats.accum_sample_thread_batch_inc_sec; table_stats_[table_id].num_clock += thread_table_stats.num_clock; table_stats_[table_id].num_clock_sampled += thread_table_stats.num_clock_sampled; table_stats_[table_id].accum_sample_clock_sec += thread_table_stats.accum_sample_clock_sec; } app_accum_comm_block_sec_.push_back(my_accum_comm_block_sec); app_sum_accum_comm_block_sec_ += my_accum_comm_block_sec; } void Stats::DeregisterBgThread() { std::lock_guard<std::mutex> lock(stats_mtx_); BgThreadStats &stats = *bg_thread_stats_; bg_accum_clock_end_oplog_serialize_sec_ += stats.accum_clock_end_oplog_serialize_sec; bg_accum_total_oplog_serialize_sec_ += stats.accum_total_oplog_serialize_sec; bg_accum_server_push_row_apply_sec_ += stats.accum_server_push_row_apply_sec; bg_accum_oplog_sent_mb_ += stats.accum_oplog_sent_kb / double(kTwoToPowerTen); bg_accum_server_push_row_recv_mb_ += stats.accum_server_push_row_recv_kb / double(kTwoToPowerTen); size_t vec_size = stats.per_clock_oplog_sent_kb.size(); if (bg_per_clock_oplog_sent_mb_.size() < vec_size) { bg_per_clock_oplog_sent_mb_.resize(vec_size, 0.0); } for (int i = 0; i < vec_size; ++i) { bg_per_clock_oplog_sent_mb_[i] += stats.per_clock_oplog_sent_kb[i] / double(kTwoToPowerTen); } vec_size = stats.per_clock_server_push_row_recv_kb.size(); if (bg_per_clock_server_push_row_recv_mb_.size() < vec_size) { bg_per_clock_server_push_row_recv_mb_.resize(vec_size, 0.0); } for (int i = 0; i < vec_size; ++i) { bg_per_clock_server_push_row_recv_mb_[i] += stats.per_clock_server_push_row_recv_kb[i] / double(kTwoToPowerTen); } } void Stats::DeregisterServerThread() { std::lock_guard<std::mutex> lock(stats_mtx_); ServerThreadStats &stats = *server_thread_stats_; server_accum_apply_oplog_sec_ += stats.accum_apply_oplog_sec; server_accum_push_row_sec_ += stats.accum_push_row_sec; server_accum_oplog_recv_mb_ += stats.accum_oplog_recv_kb / double(kTwoToPowerTen); server_accum_push_row_mb_ += stats.accum_push_row_kb / double(kTwoToPowerTen); size_t vec_size = stats.per_clock_oplog_recv_kb.size(); if (server_per_clock_oplog_recv_mb_.size() < vec_size) { server_per_clock_oplog_recv_mb_.resize(vec_size, 0.0); } for (int i = 0; i < vec_size; ++i) { server_per_clock_oplog_recv_mb_[i] += stats.per_clock_oplog_recv_kb[i] / double(kTwoToPowerTen); } vec_size = stats.per_clock_push_row_kb.size(); if (server_per_clock_push_row_mb_.size() < vec_size) { server_per_clock_push_row_mb_.resize(vec_size, 0.0); } for (int i = 0; i < vec_size; ++i) { server_per_clock_push_row_mb_[i] += stats.per_clock_push_row_kb[i] / double(kTwoToPowerTen); } } void Stats::AppLoadDataBegin() { app_thread_stats_->load_data_timer.restart(); } void Stats::AppLoadDataEnd() { AppThreadStats &stats = *app_thread_stats_; stats.load_data_sec = stats.load_data_timer.elapsed(); } void Stats::AppInitBegin() { app_thread_stats_->init_timer.restart(); } void Stats::AppInitEnd() { AppThreadStats &stats = *app_thread_stats_; stats.init_sec = stats.init_timer.elapsed(); } void Stats::AppBootstrapBegin() { app_thread_stats_->bootstrap_timer.restart(); } void Stats::AppBootstrapEnd() { AppThreadStats &stats = *app_thread_stats_; stats.bootstrap_sec = stats.bootstrap_timer.elapsed(); } void Stats::AppAccumCompBegin() { app_thread_stats_->comp_timer.restart(); } void Stats::AppAccumCompEnd() { AppThreadStats &stats = *app_thread_stats_; stats.accum_comp_sec += stats.comp_timer.elapsed(); } void Stats::AppAccumObjCompBegin() { app_thread_stats_->obj_comp_timer.restart(); } void Stats::AppAccumObjCompEnd() { AppThreadStats &stats = *app_thread_stats_; stats.accum_obj_comp_sec += stats.obj_comp_timer.elapsed(); } void Stats::AppAcuumTgClockBegin() { app_thread_stats_->tg_clock_timer.restart(); } void Stats::AppAccumTgClockEnd() { AppThreadStats &stats = *app_thread_stats_; stats.accum_tg_clock_sec += stats.tg_clock_timer.elapsed(); } void Stats::AppSampleSSPGetBegin(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; if ((stats.table_stats[table_id].num_get < kFirstNGetToSkip) || (stats.table_stats[table_id].num_get % kGetSampleFreq)) return; stats.table_stats[table_id].get_timer.restart(); } void Stats::AppSampleSSPGetEnd(int32_t table_id, bool hit) { AppThreadStats &stats = *app_thread_stats_; uint64_t org_num_get = stats.table_stats[table_id].num_get; ++stats.table_stats[table_id].num_get; if (hit) ++stats.table_stats[table_id].num_ssp_get_hit; else ++stats.table_stats[table_id].num_ssp_get_miss; if ((org_num_get - 1) < kFirstNGetToSkip || ((org_num_get - 1) % kGetSampleFreq)) { return; } if (hit) { stats.table_stats[table_id].accum_sample_ssp_get_hit_sec = stats.table_stats[table_id].get_timer.elapsed(); ++stats.table_stats[table_id].num_ssp_get_hit_sampled; } else { stats.table_stats[table_id].accum_sample_ssp_get_miss_sec = stats.table_stats[table_id].get_timer.elapsed(); ++stats.table_stats[table_id].num_ssp_get_miss_sampled; } } void Stats::AppAccumSSPPushGetCommBlockBegin(int32_t table_id) { app_thread_stats_->table_stats[table_id].ssppush_get_comm_block_timer.restart(); } void Stats::AppAccumSSPPushGetCommBlockEnd(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; stats.table_stats[table_id].accum_ssppush_get_comm_block_sec += stats.table_stats[table_id].ssppush_get_comm_block_timer.elapsed(); ++(stats.table_stats[table_id].num_ssppush_get_comm_block); } void Stats::AppAccumSSPGetServerFetchBegin(int32_t table_id) { app_thread_stats_->table_stats[table_id].ssp_get_server_fetch_timer.restart(); } void Stats::AppAccumSSPGetServerFetchEnd(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; stats.table_stats[table_id].accum_ssp_get_server_fetch_sec += stats.table_stats[table_id].ssp_get_server_fetch_timer.elapsed(); } void Stats::AppSampleIncBegin(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; if (stats.table_stats[table_id].num_inc % kIncSampleFreq) return; stats.table_stats[table_id].inc_timer.restart(); } void Stats::AppSampleIncEnd(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; uint64_t org_num_inc = stats.table_stats[table_id].num_inc; ++stats.table_stats[table_id].num_inc; if (org_num_inc % kIncSampleFreq) return; stats.table_stats[table_id].accum_sample_inc_sec += stats.table_stats[table_id].inc_timer.elapsed(); ++stats.table_stats[table_id].num_inc_sampled; } void Stats::AppSampleBatchIncBegin(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; if (stats.table_stats[table_id].num_batch_inc % kBatchIncSampleFreq) return; stats.table_stats[table_id].batch_inc_timer.restart(); } void Stats::AppSampleBatchIncEnd(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; uint64_t org_num_batch_inc = stats.table_stats[table_id].num_batch_inc; ++stats.table_stats[table_id].num_batch_inc; if (org_num_batch_inc % kBatchIncSampleFreq) return; stats.table_stats[table_id].accum_sample_batch_inc_sec += stats.table_stats[table_id].batch_inc_timer.elapsed(); ++stats.table_stats[table_id].num_batch_inc_sampled; } void Stats::AppSampleTableClockBegin(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; if (stats.table_stats[table_id].num_clock % kClockSampleFreq) return; stats.table_stats[table_id].clock_timer.restart(); } void Stats::AppSampleTableClockEnd(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; uint64_t org_num_clock = stats.table_stats[table_id].num_clock; ++stats.table_stats[table_id].num_clock; if (org_num_clock % kClockSampleFreq) return; stats.table_stats[table_id].accum_sample_clock_sec += stats.table_stats[table_id].clock_timer.elapsed(); ++stats.table_stats[table_id].num_clock_sampled; } void Stats::AppSampleThreadGetBegin(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; if (stats.table_stats[table_id].num_thread_get % kThreadGetSampleFreq) return; stats.table_stats[table_id].thread_get_timer.restart(); } void Stats::AppSampleThreadGetEnd(int32_t table_id) { AppThreadStats &stats = *app_thread_stats_; uint64_t org_num_thread_get = stats.table_stats[table_id].num_thread_get; ++stats.table_stats[table_id].num_thread_get; if (org_num_thread_get % kThreadGetSampleFreq) return; stats.table_stats[table_id].accum_sample_thread_get_sec += stats.table_stats[table_id].thread_get_timer.elapsed(); } void Stats::SetAppDefinedAccumSecName(const std::string &name) { app_defined_accum_sec_name_ = name; } void Stats::AppDefinedAccumSecBegin() { app_thread_stats_->app_defined_accum_timer.restart(); } void Stats::AppDefinedAccumSecEnd() { AppThreadStats &stats = *app_thread_stats_; stats.app_defined_accum_sec += stats.app_defined_accum_timer.elapsed(); } void Stats::SetAppDefinedVecName(const std::string &name) { app_defined_vec_name_ = name; } void Stats::AppendAppDefinedVec(double val) { app_defined_vec_.push_back(val); } void Stats::SetAppDefinedAccumValName(const std::string &name) { app_defined_accum_val_name_ = name; } void Stats::AppDefinedAccumValInc(double val) { app_thread_stats_->app_defined_accum_val += val; } void Stats::BgAccumOpLogSerializeBegin() { bg_thread_stats_->oplog_serialize_timer.restart(); } void Stats::BgAccumOpLogSerializeEnd() { BgThreadStats& stats = *bg_thread_stats_; stats.accum_total_oplog_serialize_sec += stats.oplog_serialize_timer.elapsed(); } void Stats::BgAccumClockEndOpLogSerializeBegin() { bg_thread_stats_->oplog_serialize_timer.restart(); } void Stats::BgAccumClockEndOpLogSerializeEnd() { BgThreadStats& stats = *bg_thread_stats_; double elapsed = stats.oplog_serialize_timer.elapsed(); stats.accum_total_oplog_serialize_sec += elapsed; stats.accum_clock_end_oplog_serialize_sec += elapsed; } void Stats::BgAccumServerPushRowApplyBegin() { bg_thread_stats_->server_push_row_apply_timer.restart(); } void Stats::BgAccumServerPushRowApplyEnd() { BgThreadStats &stats = *bg_thread_stats_; stats.accum_server_push_row_apply_sec += stats.server_push_row_apply_timer.elapsed(); } void Stats::BgClock() { ++(bg_thread_stats_->clock_num); bg_thread_stats_->per_clock_oplog_sent_kb.push_back(0.0); bg_thread_stats_->per_clock_server_push_row_recv_kb.push_back(0.0); } void Stats::BgAddPerClockOpLogSize(size_t oplog_size) { double oplog_size_kb = double(oplog_size) / double(kTwoToPowerTen); BgThreadStats &stats = *bg_thread_stats_; stats.per_clock_oplog_sent_kb[stats.clock_num] += oplog_size_kb; stats.accum_oplog_sent_kb += oplog_size_kb; } void Stats::BgAddPerClockServerPushRowSize(size_t server_push_row_size) { double server_push_row_size_kb = double(server_push_row_size) / double(kTwoToPowerTen); BgThreadStats &stats = *bg_thread_stats_; stats.per_clock_server_push_row_recv_kb[stats.clock_num] += server_push_row_size_kb; stats.accum_server_push_row_recv_kb += server_push_row_size_kb; } void Stats::ServerAccumApplyOpLogBegin() { server_thread_stats_->apply_oplog_timer.restart(); } void Stats::ServerAccumApplyOpLogEnd() { ServerThreadStats &stats = *server_thread_stats_; stats.accum_apply_oplog_sec += stats.apply_oplog_timer.elapsed(); } void Stats::ServerAccumPushRowBegin() { server_thread_stats_->push_row_timer.restart(); } void Stats::ServerAccumPushRowEnd() { ServerThreadStats &stats = *server_thread_stats_; stats.accum_push_row_sec += stats.push_row_timer.elapsed(); } void Stats::ServerClock() { ++server_thread_stats_->clock_num; server_thread_stats_->per_clock_oplog_recv_kb.push_back(0.0); server_thread_stats_->per_clock_push_row_kb.push_back(0.0); } void Stats::ServerAddPerClockOpLogSize(size_t oplog_size) { double oplog_size_kb = double(oplog_size) / double(kTwoToPowerTen); ServerThreadStats &stats = *server_thread_stats_; stats.per_clock_oplog_recv_kb[stats.clock_num] += oplog_size_kb; stats.accum_oplog_recv_kb += oplog_size_kb; } void Stats::ServerAddPerClockPushRowSize(size_t push_row_size) { double push_row_size_kb = double(push_row_size) / double(kTwoToPowerTen); ServerThreadStats &stats = *server_thread_stats_; stats.per_clock_push_row_kb[stats.clock_num] += push_row_size_kb; stats.accum_push_row_kb += push_row_size_kb; } template<typename T> void Stats::YamlPrintSequence(YAML::Emitter *yaml_out, const std::vector<T> &sequence) { *yaml_out << YAML::Flow << YAML::BeginSeq; for (auto seq_iter = sequence.begin(); seq_iter != sequence.end(); seq_iter++) { *yaml_out << *seq_iter; } *yaml_out << YAML::EndSeq; } void Stats::PrintStats() { YAML::Emitter yaml_out; std::lock_guard<std::mutex> lock(stats_mtx_); yaml_out << YAML::BeginMap << YAML::Comment("Table Group Configuration") << YAML::Key << "num_total_server_threads" << YAML::Value << table_group_config_.num_total_server_threads << YAML::Key << "num_tables" << YAML::Value << table_group_config_.num_tables << YAML::Key << "num_total_clients" << YAML::Value << table_group_config_.num_total_clients << YAML::Key << "num_local_server_threads" << YAML::Value << table_group_config_.num_local_server_threads << YAML::Key << "num_local_app_threads" << YAML::Value << table_group_config_.num_local_app_threads << YAML::Key << "num_local_bg_threads" << YAML::Value << table_group_config_.num_local_bg_threads << YAML::Key << "client_id" << YAML::Value << table_group_config_.client_id << YAML::Key << "aggressive_clock" << YAML::Value << table_group_config_.aggressive_clock << YAML::Key << "consistency_model" << YAML::Value << table_group_config_.consistency_model << YAML::Key << "aggressive_cpu" << YAML::Value << table_group_config_.aggressive_cpu << YAML::EndMap; for (auto table_stats_iter = table_stats_.begin(); table_stats_iter != table_stats_.end(); table_stats_iter++) { double approx_ssp_get_hit_sec = 0; if (table_stats_iter->second.num_ssp_get_hit_sampled != 0) { approx_ssp_get_hit_sec = double(table_stats_iter->second.num_ssp_get_hit) / double(table_stats_iter->second.num_ssp_get_hit_sampled) * table_stats_iter->second.accum_sample_ssp_get_hit_sec; } app_sum_approx_ssp_get_hit_sec_ += approx_ssp_get_hit_sec; double approx_inc_sec = 0; if (table_stats_iter->second.num_inc_sampled != 0) { approx_inc_sec = double(table_stats_iter->second.num_inc) / double(table_stats_iter->second.num_inc_sampled) * table_stats_iter->second.accum_sample_inc_sec; } app_sum_approx_inc_sec_ += approx_inc_sec; double approx_batch_inc_sec = 0; if (table_stats_iter->second.num_batch_inc_sampled != 0) { approx_batch_inc_sec = double(table_stats_iter->second.num_batch_inc) / double(table_stats_iter->second.num_batch_inc_sampled) * table_stats_iter->second.accum_sample_batch_inc_sec; } app_sum_approx_batch_inc_sec_ += approx_batch_inc_sec; } yaml_out << YAML::BeginMap << YAML::Comment("Application Statistics"); yaml_out << YAML::Key << "app_thread_life_sec" << YAML::Value; YamlPrintSequence(&yaml_out, app_thread_life_sec_); yaml_out << YAML::Key << "app_load_data_sec" << YAML::Value; YamlPrintSequence(&yaml_out, app_load_data_sec_); yaml_out << YAML::Key << "app_init_sec" << YAML::Value; YamlPrintSequence(&yaml_out, app_init_sec_); yaml_out << YAML::Key << "app_bootstrap_sec" << YAML::Value; YamlPrintSequence(&yaml_out, app_bootstrap_sec_); yaml_out << YAML::Key << "app_accum_comp_sec_vec" << YAML::Value; YamlPrintSequence(&yaml_out, app_accum_comp_sec_vec_); yaml_out << YAML::Key << "app_accum_comm_block_sec" << YAML::Value; YamlPrintSequence(&yaml_out, app_accum_comm_block_sec_); { std::stringstream app_defined_accum_sec_ss; app_defined_accum_sec_ss << "app_defined:"; app_defined_accum_sec_ss << app_defined_accum_sec_name_; yaml_out << YAML::Key << app_defined_accum_sec_ss.str() << YAML::Value; YamlPrintSequence(&yaml_out, app_defined_accum_sec_vec_); } { std::stringstream app_defined_accum_val_ss; app_defined_accum_val_ss << "app_defined:"; app_defined_accum_val_ss << app_defined_accum_val_name_; yaml_out << YAML::Key << app_defined_accum_val_ss.str() << YAML::Value << app_defined_accum_val_; } yaml_out << YAML::Key << "total_comp_thread" << YAML::Value << app_accum_comp_sec_vec_.size(); yaml_out << YAML::Key << "app_accum_comp_sec" << YAML::Value << app_accum_comp_sec_; yaml_out << YAML::Key << "app_sum_accum_comm_block_sec" << YAML::Value << app_sum_accum_comm_block_sec_; yaml_out << YAML::Key << "app_sum_accum_comm_block_sec_percent" << YAML::Value << double(app_sum_accum_comm_block_sec_) / double(app_accum_comp_sec_); yaml_out << YAML::Key << "app_sum_approx_ssp_get_hit_sec" << YAML::Value << app_sum_approx_ssp_get_hit_sec_; yaml_out << YAML::Key << "app_sum_approx_ssp_get_hit_sec_percent" << YAML::Value << double(app_sum_approx_ssp_get_hit_sec_) / double(app_accum_comp_sec_); yaml_out << YAML::Key << "app_sum_approx_inc_sec" << YAML::Value << app_sum_approx_inc_sec_; yaml_out << YAML::Key << "app_sum_approx_inc_sec_percent" << YAML::Value << double(app_sum_approx_inc_sec_) / double(app_accum_comp_sec_); yaml_out << YAML::Key << "app_sum_approx_batch_inc_sec" << YAML::Value << app_sum_approx_batch_inc_sec_; yaml_out << YAML::Key << "app_sum_approx_batch_inc_sec_percent" << YAML::Value << double(app_sum_approx_batch_inc_sec_) / double(app_accum_comp_sec_); yaml_out << YAML::Key << "app_accum_tg_clock_sec" << YAML::Value << app_accum_tg_clock_sec_; yaml_out << YAML::Key << "app_accum_tg_clock_sec_percent" << YAML::Value << double(app_accum_tg_clock_sec_) / double(app_accum_comp_sec_); yaml_out << YAML::Key << "ps_overall_overhead" << YAML::Value << (double(app_sum_accum_comm_block_sec_ + app_sum_approx_ssp_get_hit_sec_ + app_sum_approx_inc_sec_ + app_sum_approx_batch_inc_sec_ + app_accum_tg_clock_sec_) / double(app_accum_comp_sec_)); yaml_out << YAML::EndMap; for (auto table_stats_iter = table_stats_.begin(); table_stats_iter != table_stats_.end(); table_stats_iter++) { std::stringstream ss; ss << "Table." << table_stats_iter->first; yaml_out << YAML::BeginMap << YAML::Comment(ss.str().c_str()) << YAML::Key << "num_get" << YAML::Value << table_stats_iter->second.num_get << YAML::Key << "num_ssp_get_hit" << YAML::Value << table_stats_iter->second.num_ssp_get_hit << YAML::Key << "num_ssp_get_miss" << YAML::Value << table_stats_iter->second.num_ssp_get_miss << YAML::Key << "num_ssp_get_hit_sampled" << YAML::Value << table_stats_iter->second.num_ssp_get_hit_sampled << YAML::Key << "num_ssp_get_miss_sampled" << YAML::Value << table_stats_iter->second.num_ssp_get_miss_sampled << YAML::Key << "accum_sample_ssp_get_hit_sec" << YAML::Value << table_stats_iter->second.accum_sample_ssp_get_hit_sec << YAML::Key << "accum_sample_ssp_get_miss_sec" << YAML::Value << table_stats_iter->second.accum_sample_ssp_get_miss_sec << YAML::Key << "num_ssppush_get_comm_block" << YAML::Value << table_stats_iter->second.num_ssppush_get_comm_block << YAML::Key << "accum_sspppush_get_comm_block_sec" << YAML::Value << table_stats_iter->second.accum_ssppush_get_comm_block_sec << YAML::Key << "accum_ssp_get_server_fetch_sec" << YAML::Value << table_stats_iter->second.accum_ssp_get_server_fetch_sec << YAML::Key << "num_inc" << YAML::Value << table_stats_iter->second.num_inc << YAML::Key << "num_inc_sampled" << YAML::Value << table_stats_iter->second.num_inc_sampled << YAML::Key << "accum_sample_inc_sec" << YAML::Value << table_stats_iter->second.accum_sample_inc_sec << YAML::Key << "num_batch_inc" << YAML::Value << table_stats_iter->second.num_batch_inc << YAML::Key << "num_batch_inc_sampled" << YAML::Value << table_stats_iter->second.num_batch_inc_sampled << YAML::Key << "accum_sample_batch_inc_sec" << YAML::Value << table_stats_iter->second.accum_sample_batch_inc_sec << YAML::Key << "num_clock" << YAML::Value << table_stats_iter->second.num_clock << YAML::Key << "accum_sample_clock_sec" << YAML::Value << table_stats_iter->second.accum_sample_clock_sec << YAML::Key << "num_thread_get" << YAML::Value << table_stats_iter->second.num_thread_get << YAML::Key << "accum_sample_thread_get_sec" << YAML::Value << table_stats_iter->second.accum_sample_thread_get_sec << YAML::EndMap; } yaml_out << YAML::BeginMap << YAML::Comment("BgThread Stats") << YAML::Key << "bg_accum_clock_end_oplog_serialize_sec" << YAML::Value << bg_accum_clock_end_oplog_serialize_sec_ << YAML::Key << "bg_accum_total_oplog_serialize_sec" << YAML::Value << bg_accum_total_oplog_serialize_sec_ << YAML::Key << "bg_accum_server_push_row_apply_sec" << YAML::Value << bg_accum_server_push_row_apply_sec_ << YAML::Key << "bg_accum_oplog_sent_mb" << YAML::Value << bg_accum_oplog_sent_mb_ << YAML::Key << "bg_accum_server_push_row_recv_mb" << YAML::Value << bg_accum_server_push_row_recv_mb_; yaml_out << YAML::Key << "bg_per_clock_oplog_sent_mb" << YAML::Value; YamlPrintSequence(&yaml_out, bg_per_clock_oplog_sent_mb_); yaml_out << YAML::Key << "bg_per_clock_server_push_row_recv_mb" << YAML::Value; YamlPrintSequence(&yaml_out, bg_per_clock_server_push_row_recv_mb_); yaml_out << YAML::EndMap; yaml_out << YAML::BeginMap << YAML::Comment("ServerThread Stats") << YAML::Key << "server_accum_apply_oplog_sec" << YAML::Value << server_accum_apply_oplog_sec_ << YAML::Key << "server_accum_push_row_sec" << YAML::Value << server_accum_push_row_sec_ << YAML::Key << "server_accum_oplog_recv_mb" << YAML::Value << server_accum_oplog_recv_mb_ << YAML::Key << "server_accum_push_row_mb" << YAML::Value << server_accum_push_row_mb_; yaml_out << YAML::Key << "server_per_clock_oplog_recv_mb" << YAML::Value; YamlPrintSequence(&yaml_out, server_per_clock_oplog_recv_mb_); yaml_out << YAML::Key << "server_per_clock_push_row_mb" << YAML::Value; YamlPrintSequence(&yaml_out, server_per_clock_push_row_mb_); yaml_out << YAML::EndMap; std::fstream of_stream(stats_path_, std::ios_base::out | std::ios_base::trunc); of_stream << yaml_out.c_str(); of_stream.close(); std::stringstream app_defined_vec_ss; app_defined_vec_ss << stats_path_ << ".app-def-" << app_defined_vec_name_; std::fstream app_defined_vec_of(app_defined_vec_ss.str(), std::ios_base::out | std::ios_base::trunc); int i = 1; for (auto vec_iter = app_defined_vec_.begin(); vec_iter != app_defined_vec_.end(); ++vec_iter) { app_defined_vec_of << i << "\t" << *vec_iter << "\n"; ++i; } app_defined_vec_of.close(); } }
bsd-3-clause
futurice/futurice-ldap-user-manager
fum/settings/base.py
7379
import django.conf.global_settings as DEFAULT_SETTINGS import os, datetime, copy import getpass from pwd import getpwnam PACKAGE_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..')) PROJECT_ROOT = os.path.normpath(PACKAGE_ROOT) DEPLOYMENT_ROOT = PROJECT_ROOT PROJECT_NAME = 'fum' ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fum', 'USER': '', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', } } OWNER = getpass.getuser() OWNER_UID = getpwnam(OWNER).pw_uid OWNER_GID = getpwnam(OWNER).pw_gid EMAIL_PORT = 25 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' BADGE_URL = "https://fum.futurice.com/dbadge/create/" VIMMA_URL = "https://vimma.futurice.com/vimma/vmm/create/" API_URL = "" # https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['*'] TIME_ZONE = 'Europe/Helsinki' LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = '{PROJECT_ROOT}/media/'.format(**locals()) MEDIA_URL = '/media/' # Location of users' portrait pictures PORTRAIT_THUMB_FOLDER = '%sportraits/thumb/' % MEDIA_ROOT PORTRAIT_THUMB_URL = '%sportraits/thumb/' % MEDIA_URL PORTRAIT_BADGE_FOLDER = os.path.join(MEDIA_ROOT, 'portraits/badge/') PORTRAIT_BADGE_URL = '{}portraits/badge/'.format(MEDIA_URL) PORTRAIT_FULL_FOLDER = '%sportraits/full/' % MEDIA_ROOT PORTRAIT_FULL_URL = '%sportraits/full/' % MEDIA_URL STATIC_ROOT = '{PROJECT_ROOT}/static/'.format(**locals()) STATIC_URL = '/static/' MIDDLEWARE_CLASSES = ( 'fum.common.middleware.ThreadLocals', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'fum.urls' WSGI_APPLICATION = 'fum.wsgi.local.application' TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, 'templates/'), ) TEMPLATE_CONTEXT_PROCESSORS = ( ('fum.common.context_processors.settings_to_context', 'django.core.context_processors.request', )+DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django_extensions', 'crispy_forms', #'haystack', 'djangohistory', 'rest_framework', 'rest_framework_docs', 'rest_framework.authtoken', 'django_js_utils', 'fum', 'fum.common', 'fum.users', 'fum.groups', 'fum.servers', 'fum.projects', 'fum.api', ) AUTHENTICATION_BACKENDS = DEFAULT_SETTINGS.AUTHENTICATION_BACKENDS + ( 'django.contrib.auth.backends.RemoteUserBackend', ) REST_FRAMEWORK = { 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'PAGINATE_BY': 10, 'PAGINATE_BY_PARAM': 'limit', 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework.filters.DjangoFilterBackend', ), } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'verbose': { 'format': '[FUM] %(levelname)s %(asctime)s %(message)s' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'logfile': { 'level':'INFO', 'class':'logging.handlers.RotatingFileHandler', 'filename': '/tmp/fum.log', 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'verbose', }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'fum':{ 'handlers': ['console', 'logfile'], 'level': 'INFO', 'propagate': False } } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' SESSION_COOKIE_NAME = copy.deepcopy(PROJECT_NAME) SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'# TODO: json error in core.signing with JSONSerializer HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://127.0.0.1:8983/solr/', 'TIMEOUT': 2, }, } # TODO: use queue with celery HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' HAYSTACK_MAX_RESULTS = 25 # MIGRATION ENFORCE_PROJECT_NAMING = True # LDAP import ldap USE_TLS = True LDAP_CLASS = 'fum.ldap_helpers.PoolLDAPBridge' LDAP_RETRY_DELAY = 1 LDAP_RETRY_MAX = 3 LDAP_TIMEOUT = 5 LDAP_TRACE_LEVEL = 0 LDAP_CONNECTION_OPTIONS = { ldap.OPT_TIMEOUT: LDAP_TIMEOUT, ldap.OPT_TIMELIMIT: LDAP_TIMEOUT, ldap.OPT_NETWORK_TIMEOUT: float(LDAP_TIMEOUT), ldap.OPT_PROTOCOL_VERSION: ldap.VERSION3, } # CHANGES WEBSOCKET ENDPOINT CHANGES_SOCKET = '/tmp/fum3changes.sock' CHANGES_SOCKET_ENABLED = True CHANGES_FAILED_LOG = '/tmp/changes_failed.json' SUDO_TIMEOUT = 90#in minutes PROJECT_APPS = ['fum'] URLS_JS_GENERATED_FILE = 'fum/common/static/js/dutils.conf.urls.js' URLS_JS_TO_EXPOSE = [ 'api/', 'users/', 'groups/', 'servers/', 'projects/', 'search', 'superuser', 'audit', ] URLS_EXCLUDE_PATTERN = ['.(?P<format>[a-z]+)', '\.(?P<format>[a-z0-9]+)'] URLS_BASE = '/fum/' # fum.futurice.com/fum/ FUM_LAUNCH_DAY = datetime.datetime.now().replace(year=2013, day=20, month=10) CRISPY_TEMPLATE_PACK = 'bootstrap' # According to https://github.com/futurice/futurice-ldap-user-manager/issues/33 # the minimum number of bits required to make a key secure depends on its type. SSH_KEY_MIN_BITS_FOR_TYPE = { 'ssh-ed25519': 256, } # For any key types not given above SSH_KEY_MIN_BITS_DEFAULT = 2048 TEST_RUNNER = 'django.test.runner.DiscoverRunner' DJANGO_HISTORY_SETTINGS = { 'GET_CURRENT_REQUEST': ('fum.common.middleware', 'get_current_request'), } DJANGO_HISTORY_TRACK = False try: # add any secrets here; local_settings needs to be somewhere in PYTHONPATH (eg. project-root, user-root) from local_settings import * except Exception, e: print "No local_settings configured, ignoring..."
bsd-3-clause
tkirsan4ik/yii2_region
frontend/views/bus/bus-route/view.php
4345
<?php use kartik\grid\GridView; use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model frontend\models\bus\BusRoute */ $this->title = $model->name; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Bus Routes'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="bus-route-view"> <div class="row"> <div class="col-sm-8"> <h2><?= Yii::t('app', 'Bus Route') . ' ' . Html::encode($this->title) ?></h2> </div> <div class="col-sm-4" style="margin-top: 15px"> <?= Html::a('<i class="fa glyphicon glyphicon-hand-up"></i> ' . Yii::t('app', 'PDF'), ['pdf', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'target' => '_blank', 'data-toggle' => 'tooltip', 'title' => Yii::t('app', 'Will open the generated PDF file in a new window') ] ) ?> <?= Html::a(Yii::t('app', 'Save As New'), ['save-as-new', 'id' => $model->id], ['class' => 'btn btn-info']) ?> <?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'), 'method' => 'post', ], ]) ?> </div> </div> <div class="row"> <?php $gridColumn = [ ['attribute' => 'id', 'hidden' => true], 'name:ntext', 'date', 'date_begin', 'date_end', 'date_add', 'date_edit', ]; echo DetailView::widget([ 'model' => $model, 'attributes' => $gridColumn ]); ?> </div> <div class="row"> <?php if ($providerBusRouteHasBusRoutePoint->totalCount) { $gridColumnBusRouteHasBusRoutePoint = [ ['class' => 'yii\grid\SerialColumn'], [ 'attribute' => 'busRoutePoint.name', 'label' => Yii::t('app', 'Bus Route Point') ], 'first_point', 'end_point', 'position', 'date_point_forward', 'time_pause:datetime', 'date_point_reverse', 'date_add', 'date_edit', ]; echo Gridview::widget([ 'dataProvider' => $providerBusRouteHasBusRoutePoint, 'pjax' => true, 'pjaxSettings' => ['options' => ['id' => 'kv-pjax-container-bus-route-has-bus-route-point']], 'panel' => [ 'type' => GridView::TYPE_PRIMARY, 'heading' => '<span class="glyphicon glyphicon-book"></span> ' . Html::encode(Yii::t('app', 'Bus Route Has Bus Route Point')), ], 'columns' => $gridColumnBusRouteHasBusRoutePoint ]); } ?> </div> <div class="row"> <?php if ($providerBusWay->totalCount) { $gridColumnBusWay = [ ['class' => 'yii\grid\SerialColumn'], 'name:ntext', [ 'attribute' => 'busInfo.name', 'label' => Yii::t('app', 'Bus Info') ], 'date_create', 'date_begin', 'date_end', 'active', 'ended', 'path_time', ]; echo Gridview::widget([ 'dataProvider' => $providerBusWay, 'pjax' => true, 'pjaxSettings' => ['options' => ['id' => 'kv-pjax-container-bus-way']], 'panel' => [ 'type' => GridView::TYPE_PRIMARY, 'heading' => '<span class="glyphicon glyphicon-book"></span> ' . Html::encode(Yii::t('app', 'Bus Way')), ], 'columns' => $gridColumnBusWay ]); } ?> </div> </div>
bsd-3-clause
jupyterhub/oauthenticator
oauthenticator/tests/test_auth0.py
2602
from unittest.mock import Mock from pytest import fixture from tornado import web from ..auth0 import Auth0OAuthenticator from ..oauth2 import OAuthLogoutHandler from .mocks import mock_handler from .mocks import setup_oauth_mock auth0_subdomain = "jupyterhub-test" def user_model(email, nickname=None): """Return a user model""" return { 'email': email, 'nickname': nickname if nickname else email, 'name': 'Hoban Washburn', } @fixture def auth0_client(client): setup_oauth_mock( client, host='%s.auth0.com' % auth0_subdomain, access_token_path='/oauth/token', user_path='/userinfo', token_request_style='json', ) return client async def test_auth0(auth0_client): authenticator = Auth0OAuthenticator(auth0_subdomain=auth0_subdomain) handler = auth0_client.handler_for_user(user_model('kaylee@serenity.now')) user_info = await authenticator.authenticate(handler) assert sorted(user_info) == ['auth_state', 'name'] name = user_info['name'] assert name == 'kaylee@serenity.now' auth_state = user_info['auth_state'] assert 'access_token' in auth_state assert 'auth0_user' in auth_state async def test_username_key(auth0_client): authenticator = Auth0OAuthenticator(auth0_subdomain=auth0_subdomain) authenticator.username_key = 'nickname' handler = auth0_client.handler_for_user(user_model('kaylee@serenity.now', 'kayle')) user_info = await authenticator.authenticate(handler) assert user_info['name'] == 'kayle' async def test_custom_logout(monkeypatch): auth0_subdomain = 'auth0-domain.org' authenticator = Auth0OAuthenticator() logout_handler = mock_handler(OAuthLogoutHandler, authenticator=authenticator) monkeypatch.setattr(web.RequestHandler, 'redirect', Mock()) logout_handler.clear_login_cookie = Mock() logout_handler.clear_cookie = Mock() logout_handler._jupyterhub_user = Mock() monkeypatch.setitem(logout_handler.settings, 'statsd', Mock()) # Sanity check: Ensure the logout handler and url are set on the hub handlers = [handler for _, handler in authenticator.get_handlers(None)] assert any([h == OAuthLogoutHandler for h in handlers]) assert authenticator.logout_url('http://myhost') == 'http://myhost/logout' # Check redirection to the custom logout url authenticator.auth0_subdomain = auth0_subdomain await logout_handler.get() custom_logout_url = f'https://{auth0_subdomain}.auth0.com/v2/logout' logout_handler.redirect.assert_called_with(custom_logout_url)
bsd-3-clause
IG-Group/ig-webapi-dotnet-sample
IGWebApiClient/Model/dto/endpoint/marketdetails/v2/DepositBanding.cs
404
using System.Collections.Generic; using dto.endpoint.auth.session; namespace dto.endpoint.marketdetails.v2 { public class DepositBanding{ ///<Summary> ///Boundaries ///</Summary> public List<string> boundaries { get; set; } ///<Summary> ///Margin factor ///</Summary> public List<string> factors { get; set; } ///<Summary> ///Currency ///</Summary> public string currency { get; set; } } }
bsd-3-clause
godoctor/godoctor
refactoring/testdata/extractfunc/037-passing-structure-by-reference/main.go
193
//<<<<<extract,14,2,15,23,foo,pass package main import "fmt" type Pt struct { x, y int } func main() { p := &Pt{3, 4} fmt.Println("Old Pt", p) p.x = 5 p.y = 6 fmt.Print("New Pt", p) }
bsd-3-clause
madphysicist/numpy
numpy/typing/tests/test_typing.py
11391
import importlib.util import itertools import os import re import shutil from collections import defaultdict from typing import Optional, IO, Dict, List import pytest import numpy as np from numpy.typing.mypy_plugin import _PRECISION_DICT, _EXTENDED_PRECISION_LIST try: from mypy import api except ImportError: NO_MYPY = True else: NO_MYPY = False DATA_DIR = os.path.join(os.path.dirname(__file__), "data") PASS_DIR = os.path.join(DATA_DIR, "pass") FAIL_DIR = os.path.join(DATA_DIR, "fail") REVEAL_DIR = os.path.join(DATA_DIR, "reveal") MISC_DIR = os.path.join(DATA_DIR, "misc") MYPY_INI = os.path.join(DATA_DIR, "mypy.ini") CACHE_DIR = os.path.join(DATA_DIR, ".mypy_cache") #: A dictionary with file names as keys and lists of the mypy stdout as values. #: To-be populated by `run_mypy`. OUTPUT_MYPY: Dict[str, List[str]] = {} def _key_func(key: str) -> str: """Split at the first occurance of the ``:`` character. Windows drive-letters (*e.g.* ``C:``) are ignored herein. """ drive, tail = os.path.splitdrive(key) return os.path.join(drive, tail.split(":", 1)[0]) @pytest.mark.slow @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed") @pytest.fixture(scope="module", autouse=True) def run_mypy() -> None: """Clears the cache and run mypy before running any of the typing tests. The mypy results are cached in `OUTPUT_MYPY` for further use. """ if os.path.isdir(CACHE_DIR): shutil.rmtree(CACHE_DIR) for directory in (PASS_DIR, REVEAL_DIR, FAIL_DIR, MISC_DIR): # Run mypy stdout, stderr, _ = api.run([ "--config-file", MYPY_INI, "--cache-dir", CACHE_DIR, directory, ]) assert not stderr, directory stdout = stdout.replace('*', '') # Parse the output iterator = itertools.groupby(stdout.split("\n"), key=_key_func) OUTPUT_MYPY.update((k, list(v)) for k, v in iterator if k) def get_test_cases(directory): for root, _, files in os.walk(directory): for fname in files: if os.path.splitext(fname)[-1] == ".py": fullpath = os.path.join(root, fname) # Use relative path for nice py.test name relpath = os.path.relpath(fullpath, start=directory) yield pytest.param( fullpath, # Manually specify a name for the test id=relpath, ) @pytest.mark.slow @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed") @pytest.mark.parametrize("path", get_test_cases(PASS_DIR)) def test_success(path): # Alias `OUTPUT_MYPY` so that it appears in the local namespace output_mypy = OUTPUT_MYPY if path in output_mypy: raise AssertionError("\n".join(v for v in output_mypy[path].values())) @pytest.mark.slow @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed") @pytest.mark.parametrize("path", get_test_cases(FAIL_DIR)) def test_fail(path): __tracebackhide__ = True with open(path) as fin: lines = fin.readlines() errors = defaultdict(lambda: "") output_mypy = OUTPUT_MYPY assert path in output_mypy for error_line in output_mypy[path]: match = re.match( r"^.+\.py:(?P<lineno>\d+): (error|note): .+$", error_line, ) if match is None: raise ValueError(f"Unexpected error line format: {error_line}") lineno = int(match.group('lineno')) errors[lineno] += error_line for i, line in enumerate(lines): lineno = i + 1 if line.startswith('#') or (" E:" not in line and lineno not in errors): continue target_line = lines[lineno - 1] if "# E:" in target_line: marker = target_line.split("# E:")[-1].strip() expected_error = errors.get(lineno) _test_fail(path, marker, expected_error, lineno) else: pytest.fail(f"Error {repr(errors[lineno])} not found") _FAIL_MSG1 = """Extra error at line {} Extra error: {!r} """ _FAIL_MSG2 = """Error mismatch at line {} Expected error: {!r} Observed error: {!r} """ def _test_fail(path: str, error: str, expected_error: Optional[str], lineno: int) -> None: if expected_error is None: raise AssertionError(_FAIL_MSG1.format(lineno, error)) elif error not in expected_error: raise AssertionError(_FAIL_MSG2.format(lineno, expected_error, error)) def _construct_format_dict(): dct = {k.split(".")[-1]: v.replace("numpy", "numpy.typing") for k, v in _PRECISION_DICT.items()} return { "uint8": "numpy.unsignedinteger[numpy.typing._8Bit]", "uint16": "numpy.unsignedinteger[numpy.typing._16Bit]", "uint32": "numpy.unsignedinteger[numpy.typing._32Bit]", "uint64": "numpy.unsignedinteger[numpy.typing._64Bit]", "uint128": "numpy.unsignedinteger[numpy.typing._128Bit]", "uint256": "numpy.unsignedinteger[numpy.typing._256Bit]", "int8": "numpy.signedinteger[numpy.typing._8Bit]", "int16": "numpy.signedinteger[numpy.typing._16Bit]", "int32": "numpy.signedinteger[numpy.typing._32Bit]", "int64": "numpy.signedinteger[numpy.typing._64Bit]", "int128": "numpy.signedinteger[numpy.typing._128Bit]", "int256": "numpy.signedinteger[numpy.typing._256Bit]", "float16": "numpy.floating[numpy.typing._16Bit]", "float32": "numpy.floating[numpy.typing._32Bit]", "float64": "numpy.floating[numpy.typing._64Bit]", "float80": "numpy.floating[numpy.typing._80Bit]", "float96": "numpy.floating[numpy.typing._96Bit]", "float128": "numpy.floating[numpy.typing._128Bit]", "float256": "numpy.floating[numpy.typing._256Bit]", "complex64": "numpy.complexfloating[numpy.typing._32Bit, numpy.typing._32Bit]", "complex128": "numpy.complexfloating[numpy.typing._64Bit, numpy.typing._64Bit]", "complex160": "numpy.complexfloating[numpy.typing._80Bit, numpy.typing._80Bit]", "complex192": "numpy.complexfloating[numpy.typing._96Bit, numpy.typing._96Bit]", "complex256": "numpy.complexfloating[numpy.typing._128Bit, numpy.typing._128Bit]", "complex512": "numpy.complexfloating[numpy.typing._256Bit, numpy.typing._256Bit]", "ubyte": f"numpy.unsignedinteger[{dct['_NBitByte']}]", "ushort": f"numpy.unsignedinteger[{dct['_NBitShort']}]", "uintc": f"numpy.unsignedinteger[{dct['_NBitIntC']}]", "uintp": f"numpy.unsignedinteger[{dct['_NBitIntP']}]", "uint": f"numpy.unsignedinteger[{dct['_NBitInt']}]", "ulonglong": f"numpy.unsignedinteger[{dct['_NBitLongLong']}]", "byte": f"numpy.signedinteger[{dct['_NBitByte']}]", "short": f"numpy.signedinteger[{dct['_NBitShort']}]", "intc": f"numpy.signedinteger[{dct['_NBitIntC']}]", "intp": f"numpy.signedinteger[{dct['_NBitIntP']}]", "int_": f"numpy.signedinteger[{dct['_NBitInt']}]", "longlong": f"numpy.signedinteger[{dct['_NBitLongLong']}]", "half": f"numpy.floating[{dct['_NBitHalf']}]", "single": f"numpy.floating[{dct['_NBitSingle']}]", "double": f"numpy.floating[{dct['_NBitDouble']}]", "longdouble": f"numpy.floating[{dct['_NBitLongDouble']}]", "csingle": f"numpy.complexfloating[{dct['_NBitSingle']}, {dct['_NBitSingle']}]", "cdouble": f"numpy.complexfloating[{dct['_NBitDouble']}, {dct['_NBitDouble']}]", "clongdouble": f"numpy.complexfloating[{dct['_NBitLongDouble']}, {dct['_NBitLongDouble']}]", # numpy.typing "_NBitInt": dct['_NBitInt'], } #: A dictionary with all supported format keys (as keys) #: and matching values FORMAT_DICT: Dict[str, str] = _construct_format_dict() def _parse_reveals(file: IO[str]) -> List[str]: """Extract and parse all ``" # E: "`` comments from the passed file-like object. All format keys will be substituted for their respective value from `FORMAT_DICT`, *e.g.* ``"{float64}"`` becomes ``"numpy.floating[numpy.typing._64Bit]"``. """ string = file.read().replace("*", "") # Grab all `# E:`-based comments comments_array = np.char.partition(string.split("\n"), sep=" # E: ")[:, 2] comments = "/n".join(comments_array) # Only search for the `{*}` pattern within comments, # otherwise there is the risk of accidently grabbing dictionaries and sets key_set = set(re.findall(r"\{(.*?)\}", comments)) kwargs = { k: FORMAT_DICT.get(k, f"<UNRECOGNIZED FORMAT KEY {k!r}>") for k in key_set } fmt_str = comments.format(**kwargs) return fmt_str.split("/n") @pytest.mark.slow @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed") @pytest.mark.parametrize("path", get_test_cases(REVEAL_DIR)) def test_reveal(path): __tracebackhide__ = True with open(path) as fin: lines = _parse_reveals(fin) output_mypy = OUTPUT_MYPY assert path in output_mypy for error_line in output_mypy[path]: match = re.match( r"^.+\.py:(?P<lineno>\d+): note: .+$", error_line, ) if match is None: raise ValueError(f"Unexpected reveal line format: {error_line}") lineno = int(match.group('lineno')) - 1 assert "Revealed type is" in error_line marker = lines[lineno] _test_reveal(path, marker, error_line, 1 + lineno) _REVEAL_MSG = """Reveal mismatch at line {} Expected reveal: {!r} Observed reveal: {!r} """ def _test_reveal(path: str, reveal: str, expected_reveal: str, lineno: int) -> None: if reveal not in expected_reveal: raise AssertionError(_REVEAL_MSG.format(lineno, expected_reveal, reveal)) @pytest.mark.slow @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed") @pytest.mark.parametrize("path", get_test_cases(PASS_DIR)) def test_code_runs(path): path_without_extension, _ = os.path.splitext(path) dirname, filename = path.split(os.sep)[-2:] spec = importlib.util.spec_from_file_location(f"{dirname}.{filename}", path) test_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(test_module) LINENO_MAPPING = { 3: "uint128", 4: "uint256", 6: "int128", 7: "int256", 9: "float80", 10: "float96", 11: "float128", 12: "float256", 14: "complex160", 15: "complex192", 16: "complex256", 17: "complex512", } @pytest.mark.slow @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed") def test_extended_precision() -> None: path = os.path.join(MISC_DIR, "extended_precision.py") output_mypy = OUTPUT_MYPY assert path in output_mypy for _msg in output_mypy[path]: *_, _lineno, msg_typ, msg = _msg.split(":") lineno = int(_lineno) msg_typ = msg_typ.strip() assert msg_typ in {"error", "note"} if LINENO_MAPPING[lineno] in _EXTENDED_PRECISION_LIST: if msg_typ == "error": raise ValueError(f"Unexpected reveal line format: {lineno}") else: marker = FORMAT_DICT[LINENO_MAPPING[lineno]] _test_reveal(path, marker, msg, lineno) else: if msg_typ == "error": marker = "Module has no attribute" _test_fail(path, marker, msg, lineno)
bsd-3-clause
tim-mc/quill
node_modules/webdriverio/lib/commands/getValue.js
1432
/** * * Get the value of a `<textarea>` or text `<input>` found by given selector. * * <example> :index.html <input type="text" value="John Doe" id="username"> :getValueAsync.js client.getValue('#username').then(function(value) { console.log(value); // outputs: "John Doe" }); :getValueSync.js it('should demonstrate the getValue command', function () { var inputUser = browser.element('#username'); var value = inputUser.getValue(); console.log(value); // outputs: "John Doe" }); * </example> * * @alias browser.getValue * @param {String} selector input or textarea element * @returns {String} requested input value * @uses protocol/elements, protocol/elementIdAttribute * @type property * */ import { CommandError } from '../utils/ErrorHandler' let getValue = function (selector) { return this.elements(selector).then((res) => { /** * throw NoSuchElement error if no element was found */ if (!res.value || res.value.length === 0) { return new CommandError(7) } let elementIdAttributeCommands = [] for (let elem of res.value) { elementIdAttributeCommands.push(this.elementIdAttribute(elem.ELEMENT, 'value')) } return this.unify(elementIdAttributeCommands, { extractValue: true }) }) } export default getValue
bsd-3-clause
andrewconnell/aci-orchardcms
Modules/Orchard.Azure.MediaServices/Services/Assets/AssetUploader.cs
12054
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Orchard.Azure.MediaServices.Helpers; using Orchard.Azure.MediaServices.Models; using Orchard.Azure.MediaServices.Models.Assets; using Orchard.Azure.MediaServices.Models.Records; using Orchard.Azure.MediaServices.Services.TempFiles; using Orchard.Azure.MediaServices.Services.Wams; using Orchard.ContentManagement; using Orchard.Data; using Orchard.Logging; using Orchard.Services; using Orchard.Tasks; using NHibernate; namespace Orchard.Azure.MediaServices.Services.Assets { public class AssetUploader : Component, IBackgroundTask { private static readonly object _sweepLock = new object(); private readonly IOrchardServices _orchardServices; private readonly IClock _clock; private readonly ITransactionManager _transactionManager; private readonly IContentManager _contentManager; private readonly IAssetManager _assetManager; private readonly ITempFileManager _fileManager; private readonly IWamsClient _wamsClient; public AssetUploader( IOrchardServices orchardServices, IClock clock, ITransactionManager transactionManager, IContentManager contentManager, IAssetManager assetManager, ITempFileManager fileManager, IWamsClient wamsClient) { _orchardServices = orchardServices; _clock = clock; _transactionManager = transactionManager; _contentManager = contentManager; _assetManager = assetManager; _fileManager = fileManager; _wamsClient = wamsClient; } void IBackgroundTask.Sweep() { if (Monitor.TryEnter(_sweepLock)) { try { Logger.Debug("Beginning sweep."); if (!_orchardServices.WorkContext.CurrentSite.As<CloudMediaSettingsPart>().IsValid()) { Logger.Debug("Settings are invalid; going back to sleep."); return; } var pendingAssetsQuery = from asset in _assetManager.LoadPendingAssets() where _fileManager.FileExists(asset.LocalTempFileName) select asset; var pendingAssets = pendingAssetsQuery.ToArray(); if (!pendingAssets.Any()) { Logger.Debug("No pending assets with temp files on local machine were found; going back to sleep."); return; } Logger.Information("Beginning processing of {0} pending assets.", pendingAssets.Length); var uploadTasks = new List<Task>(); var progressInfoQueue = new BlockingCollection<WamsUploadProgressInfo>(); var assetProgressMonikers = new Dictionary<Guid, Asset>(); var assetCancellationTokenSources = new Dictionary<Guid, CancellationTokenSource>(); foreach (var pendingAsset in pendingAssets) { Logger.Information("Uploading asset of type {0} with name '{1}'...", pendingAsset.Record.Type, pendingAsset.Name); var cloudVideoPart = _contentManager.Get<CloudVideoPart>(pendingAsset.Record.VideoContentItemId, VersionOptions.Latest); pendingAsset.UploadState.Status = AssetUploadStatus.Uploading; pendingAsset.UploadState.StartedUtc = _clock.UtcNow; pendingAsset.UploadState.BytesComplete = 0; pendingAsset.UploadState.CompletedUtc = null; _transactionManager.RequireNew(); var assetProgressMoniker = Guid.NewGuid(); var assetCancellationTokenSource = new CancellationTokenSource(); assetProgressMonikers.Add(assetProgressMoniker, pendingAsset); assetCancellationTokenSources.Add(assetProgressMoniker, assetCancellationTokenSource); var localPendingAsset = pendingAsset; var uploadTask = _wamsClient.UploadAssetAsync(_fileManager.GetPhysicalFilePath(pendingAsset.LocalTempFileName), progressInfoQueue.Add, assetProgressMoniker, assetCancellationTokenSource.Token) .ContinueWith((previousTask) => { if (!previousTask.IsCanceled) { try { var wamsAsset = previousTask.Result; // Throws if previous task was faulted. var wamsLocators = _wamsClient.CreateLocatorsAsync(wamsAsset, WamsLocatorCategory.Private).Result; localPendingAsset.WamsPrivateLocatorId = wamsLocators.SasLocator.Id; localPendingAsset.WamsPrivateLocatorUrl = wamsLocators.SasLocator.Url; localPendingAsset.WamsAssetId = wamsAsset.Id; localPendingAsset.UploadState.Status = AssetUploadStatus.Uploaded; localPendingAsset.UploadState.BytesComplete = localPendingAsset.LocalTempFileSize; localPendingAsset.UploadState.CompletedUtc = _clock.UtcNow; } catch (Exception ex) { Logger.Error(ex, "Error while uploading asset of type {0} with name '{1}'. Resetting asset upload status to {2}.", localPendingAsset.Record.Type, localPendingAsset.Name, AssetUploadStatus.Pending); // Reset asset to pending status so it will be retried later. localPendingAsset.UploadState.CompletedUtc = null; localPendingAsset.UploadState.BytesComplete = 0; localPendingAsset.UploadState.StartedUtc = null; localPendingAsset.UploadState.Status = AssetUploadStatus.Pending; return; } } _fileManager.DeleteFile(localPendingAsset.LocalTempFileName); localPendingAsset.LocalTempFileName = null; localPendingAsset.LocalTempFileSize = null; Logger.Information("Deleted temp file '{0}' for asset of type {1} with name '{2}'.", localPendingAsset.LocalTempFileName, localPendingAsset.Record.Type, localPendingAsset.Name); if (previousTask.IsCanceled) Logger.Information("Upload of asset of type {0} with name '{1}' was canceled.", localPendingAsset.Record.Type, localPendingAsset.Name); else { try { if (cloudVideoPart.PublishOnUpload) { var remainingPendingAssetsQuery = from asset in cloudVideoPart.Assets where asset.UploadState.Status.IsAny(AssetUploadStatus.Pending, AssetUploadStatus.Uploading) select asset; if (!remainingPendingAssetsQuery.Any()) { Logger.Information("No more remaining assets on cloud video item with ID {0}; publishing the item.", cloudVideoPart.Id); _contentManager.Publish(cloudVideoPart.ContentItem); cloudVideoPart.PublishOnUpload = false; Logger.Information("Published cloud video item with ID {0}.", cloudVideoPart.Id); } } else if (cloudVideoPart.ContentItem.IsPublished()) { // Publish the asset. _assetManager.PublishAssetsFor(cloudVideoPart); } } catch (Exception ex) { Logger.Warning(ex, "Upload of asset of type {0} with name '{1}' was completed but an error occurred while publishing the cloud video item with ID {2} after upload.", localPendingAsset.Record.Type, localPendingAsset.Name, cloudVideoPart.Id); } Logger.Information("Upload of asset of type {0} with name '{1}' was successfully completed.", localPendingAsset.Record.Type, localPendingAsset.Name); } }, assetCancellationTokenSource.Token); uploadTask.ConfigureAwait(continueOnCapturedContext: false); uploadTasks.Add(uploadTask); } Task.WhenAll(uploadTasks).ContinueWith((previousTask) => progressInfoQueue.CompleteAdding()); var lastUpdateUtc = _clock.UtcNow; foreach (var progressInfo in progressInfoQueue.GetConsumingEnumerable()) { var progressAsset = assetProgressMonikers[progressInfo.AssetMoniker]; var cancellationTokenSource = assetCancellationTokenSources[progressInfo.AssetMoniker]; // Check for cancellation (asset upload status was set to Canceled). if (!cancellationTokenSource.IsCancellationRequested) { var session = _transactionManager.GetSession(); session.Refresh(progressAsset.Record, LockMode.None); if (progressAsset.UploadState.Status == AssetUploadStatus.Canceled) { Logger.Information("Cancellation request was detected for asset of type {0} with name '{1}'; cancelling upload...", progressAsset.Record.Type, progressAsset.Name); cancellationTokenSource.Cancel(); } } // Don't flood the database with progress updates; limit it to every 5 seconds. if ((_clock.UtcNow - lastUpdateUtc).Seconds >= 5) { progressAsset.UploadState.BytesComplete = progressInfo.Data.BytesTransferred; _transactionManager.RequireNew(); lastUpdateUtc = _clock.UtcNow; } Logger.Debug("Uploading asset of type {0} with name '{1}'; {2}/{3} KB uploaded ({4}%) at {5} KB/sec.", progressAsset.Record.Type, progressAsset.Name, Convert.ToInt64(progressInfo.Data.BytesTransferred / 1024), Convert.ToInt64(progressInfo.Data.TotalBytesToTransfer / 1024), progressInfo.Data.ProgressPercentage, Convert.ToInt32(progressInfo.Data.TransferRateBytesPerSecond / 1024)); } } finally { Logger.Debug("Ending sweep."); Monitor.Exit(_sweepLock); } } } } }
bsd-3-clause
chandler14362/panda3d
makepanda/makepanda.py
301845
#!/usr/bin/env python ######################################################################## # # To build panda using this script, type 'makepanda.py' on unix # or 'makepanda.bat' on windows, and examine the help-text. # Then run the script again with the appropriate options to compile # panda3d. # ######################################################################## try: import sys, os, platform, time, stat, re, getopt, threading, signal, shutil if sys.platform == "darwin" or sys.version_info >= (2, 6): import plistlib if sys.version_info >= (3, 0): import queue else: import Queue as queue except KeyboardInterrupt: raise except: print("You are either using an incomplete or an old version of Python!") print("Please install the development package of Python and try again.") exit(1) from makepandacore import * import time import os import sys ######################################################################## ## ## PARSING THE COMMAND LINE OPTIONS ## ## You might be tempted to change the defaults by editing them ## here. Don't do it. Instead, create a script that compiles ## panda with your preferred options. Or, create ## a 'makepandaPreferences' file and put it into your python path. ## ######################################################################## COMPILER=0 INSTALLER=0 WHEEL=0 RUNTESTS=0 GENMAN=0 COMPRESSOR="zlib" THREADCOUNT=0 CFLAGS="" CXXFLAGS="" LDFLAGS="" RTDIST=0 RTDIST_VERSION=None RUNTIME=0 DISTRIBUTOR="" VERSION=None DEBVERSION=None WHLVERSION=None RPMRELEASE="1" GIT_COMMIT=None P3DSUFFIX=None MAJOR_VERSION=None COREAPI_VERSION=None PLUGIN_VERSION=None OSXTARGET=None OSX_ARCHS=[] HOST_URL=None global STRDXSDKVERSION, BOOUSEINTELCOMPILER STRDXSDKVERSION = 'default' WINDOWS_SDK = None MSVC_VERSION = None BOOUSEINTELCOMPILER = False OPENCV_VER_23 = False if "MACOSX_DEPLOYMENT_TARGET" in os.environ: OSXTARGET=os.environ["MACOSX_DEPLOYMENT_TARGET"] PkgListSet(["PYTHON", "DIRECT", # Python support "GL", "GLES", "GLES2"] + DXVERSIONS + ["TINYDISPLAY", "NVIDIACG", # 3D graphics "EGL", # OpenGL (ES) integration "EIGEN", # Linear algebra acceleration "OPENAL", "FMODEX", # Audio playback "VORBIS", "OPUS", "FFMPEG", "SWSCALE", "SWRESAMPLE", # Audio decoding "ODE", "PHYSX", "BULLET", "PANDAPHYSICS", # Physics "SPEEDTREE", # SpeedTree "ZLIB", "PNG", "JPEG", "TIFF", "OPENEXR", "SQUISH", # 2D Formats support ] + MAYAVERSIONS + MAXVERSIONS + [ "FCOLLADA", "ASSIMP", "EGG", # 3D Formats support "FREETYPE", "HARFBUZZ", # Text rendering "VRPN", "OPENSSL", # Transport "FFTW", # Algorithm helpers "ARTOOLKIT", "OPENCV", "DIRECTCAM", "VISION", # Augmented Reality "GTK2", # GTK2 is used for PStats on Unix "MFC", "WX", "FLTK", # Used for web plug-in only "ROCKET", # GUI libraries "CARBON", "COCOA", # Mac OS X toolkits "X11", # Unix platform support "PANDATOOL", "PVIEW", "DEPLOYTOOLS", # Toolchain "SKEL", # Example SKEL project "PANDAFX", # Some distortion special lenses "PANDAPARTICLESYSTEM", # Built in particle system "CONTRIB", # Experimental "SSE2", "NEON", # Compiler features ]) CheckPandaSourceTree() def keyboardInterruptHandler(x,y): exit("keyboard interrupt") signal.signal(signal.SIGINT, keyboardInterruptHandler) ######################################################################## ## ## Command-line parser. ## ## You can type "makepanda --help" to see all the options. ## ######################################################################## def usage(problem): if (problem): print("") print("Error parsing command-line input: %s" % (problem)) print("") print("Makepanda generates a 'built' subdirectory containing a") print("compiled copy of Panda3D. Command-line arguments are:") print("") print(" --help (print the help message you're reading now)") print(" --verbose (print out more information)") print(" --runtime (build a runtime build instead of an SDK build)") print(" --tests (run the test suite)") print(" --installer (build an installer)") print(" --wheel (build a pip-installable .whl)") print(" --optimize X (optimization level can be 1,2,3,4)") print(" --version X (set the panda version number)") print(" --lzma (use lzma compression when building Windows installer)") print(" --distributor X (short string identifying the distributor of the build)") print(" --outputdir X (use the specified directory instead of 'built')") print(" --host URL (set the host url (runtime build only))") print(" --threads N (use the multithreaded build system. see manual)") print(" --osxtarget N (the OS X version number to build for (OS X only))") print(" --universal (build universal binaries (OS X only))") print(" --override \"O=V\" (override dtool_config/prc option value)") print(" --static (builds libraries for static linking)") print(" --target X (experimental cross-compilation (android only))") print(" --arch X (target architecture for cross-compilation)") print("") for pkg in PkgListGet(): p = pkg.lower() print(" --use-%-9s --no-%-9s (enable/disable use of %s)"%(p, p, pkg)) if sys.platform != 'win32': print(" --<PKG>-incdir (custom location for header files of thirdparty package)") print(" --<PKG>-libdir (custom location for library files of thirdparty package)") print("") print(" --nothing (disable every third-party lib)") print(" --everything (enable every third-party lib)") print(" --directx-sdk=X (specify version of DirectX SDK to use: jun2010, aug2009, mar2009, aug2006)") print(" --windows-sdk=X (specify Windows SDK version, eg. 7.0, 7.1 or 10. Default is 7.1)") print(" --msvc-version=X (specify Visual C++ version, eg. 10, 11, 12, 14. Default is 14)") print(" --use-icl (experimental setting to use an intel compiler instead of MSVC on Windows)") print("") print("The simplest way to compile panda is to just type:") print("") print(" makepanda --everything") print("") os._exit(1) def parseopts(args): global INSTALLER,WHEEL,RUNTESTS,RTDIST,RUNTIME,GENMAN,DISTRIBUTOR,VERSION global COMPRESSOR,THREADCOUNT,OSXTARGET,OSX_ARCHS,HOST_URL global DEBVERSION,WHLVERSION,RPMRELEASE,GIT_COMMIT,P3DSUFFIX,RTDIST_VERSION global STRDXSDKVERSION, WINDOWS_SDK, MSVC_VERSION, BOOUSEINTELCOMPILER # Options for which to display a deprecation warning. removedopts = [ "use-touchinput", "no-touchinput", "no-awesomium", "no-directscripts", ] # All recognized options. longopts = [ "help","distributor=","verbose","runtime","osxtarget=","tests", "optimize=","everything","nothing","installer","wheel","rtdist","nocolor", "version=","lzma","no-python","threads=","outputdir=","override=", "static","host=","debversion=","rpmrelease=","p3dsuffix=","rtdist-version=", "directx-sdk=", "windows-sdk=", "msvc-version=", "clean", "use-icl", "universal", "target=", "arch=", "git-commit=", ] + removedopts anything = 0 optimize = "" target = None target_arch = None universal = False clean_build = False for pkg in PkgListGet(): longopts.append("use-" + pkg.lower()) longopts.append("no-" + pkg.lower()) longopts.append(pkg.lower() + "-incdir=") longopts.append(pkg.lower() + "-libdir=") try: opts, extras = getopt.getopt(args, "", longopts) for option, value in opts: if (option=="--help"): raise Exception elif (option=="--optimize"): optimize=value elif (option=="--installer"): INSTALLER=1 elif (option=="--tests"): RUNTESTS=1 elif (option=="--wheel"): WHEEL=1 elif (option=="--verbose"): SetVerbose(True) elif (option=="--distributor"): DISTRIBUTOR=value elif (option=="--rtdist"): RTDIST=1 elif (option=="--runtime"): RUNTIME=1 elif (option=="--genman"): GENMAN=1 elif (option=="--everything"): PkgEnableAll() elif (option=="--nothing"): PkgDisableAll() elif (option=="--threads"): THREADCOUNT=int(value) elif (option=="--outputdir"): SetOutputDir(value.strip()) elif (option=="--osxtarget"): OSXTARGET=value.strip() elif (option=="--universal"): universal = True elif (option=="--target"): target = value.strip() elif (option=="--arch"): target_arch = value.strip() elif (option=="--nocolor"): DisableColors() elif (option=="--version"): match = re.match(r'^\d+\.\d+\.\d+', value) if not match: usage("version requires three digits") WHLVERSION = value VERSION = match.group() elif (option=="--lzma"): COMPRESSOR="lzma" elif (option=="--override"): AddOverride(value.strip()) elif (option=="--static"): SetLinkAllStatic(True) elif (option=="--host"): HOST_URL=value elif (option=="--debversion"): DEBVERSION=value elif (option=="--rpmrelease"): RPMRELEASE=value elif (option=="--git-commit"): GIT_COMMIT=value elif (option=="--p3dsuffix"): P3DSUFFIX=value elif (option=="--rtdist-version"): RTDIST_VERSION=value # Backward compatibility, OPENGL was renamed to GL elif (option=="--use-opengl"): PkgEnable("GL") elif (option=="--no-opengl"): PkgDisable("GL") elif (option=="--directx-sdk"): STRDXSDKVERSION = value.strip().lower() if STRDXSDKVERSION == '': print("No DirectX SDK version specified. Using 'default' DirectX SDK search") STRDXSDKVERSION = 'default' elif (option=="--windows-sdk"): WINDOWS_SDK = value.strip().lower() elif (option=="--msvc-version"): MSVC_VERSION = value.strip().lower() elif (option=="--use-icl"): BOOUSEINTELCOMPILER = True elif (option=="--clean"): clean_build = True elif (option[2:] in removedopts): Warn("Ignoring removed option %s" % (option)) else: for pkg in PkgListGet(): if option == "--use-" + pkg.lower(): PkgEnable(pkg) break elif option == "--no-" + pkg.lower(): PkgDisable(pkg) break elif option == "--" + pkg.lower() + "-incdir": PkgSetCustomLocation(pkg) IncDirectory(pkg, value) break elif option == "--" + pkg.lower() + "-libdir": PkgSetCustomLocation(pkg) LibDirectory(pkg, value) break if (option == "--everything" or option.startswith("--use-") or option == "--nothing" or option.startswith("--no-")): anything = 1 except: usage(sys.exc_info()[1]) if not anything: if RUNTIME: PkgEnableAll() else: usage("You should specify a list of packages to use or --everything to enable all packages.") if (RTDIST and RUNTIME): usage("Options --runtime and --rtdist cannot be specified at the same time!") if (optimize=="" and (RTDIST or RUNTIME)): optimize = "4" elif (optimize==""): optimize = "3" if OSXTARGET: try: maj, min = OSXTARGET.strip().split('.') OSXTARGET = int(maj), int(min) assert OSXTARGET[0] == 10 except: usage("Invalid setting for OSXTARGET") else: OSXTARGET = None if target is not None or target_arch is not None: SetTarget(target, target_arch) if universal: if target_arch: exit("--universal is incompatible with --arch") OSX_ARCHS.append("i386") if OSXTARGET: osxver = OSXTARGET else: maj, min = platform.mac_ver()[0].split('.')[:2] osxver = int(maj), int(min) if osxver[1] < 6: OSX_ARCHS.append("ppc") else: OSX_ARCHS.append("x86_64") elif HasTargetArch(): OSX_ARCHS.append(GetTargetArch()) try: SetOptimize(int(optimize)) assert GetOptimize() in [1, 2, 3, 4] except: usage("Invalid setting for OPTIMIZE") if GIT_COMMIT is not None and not re.match("^[a-f0-9]{40}$", GIT_COMMIT): usage("Invalid SHA-1 hash given for --git-commit option!") if GetTarget() == 'windows': if not MSVC_VERSION: print("No MSVC version specified. Defaulting to 14 (Visual Studio 2015).") MSVC_VERSION = (14, 0) else: try: MSVC_VERSION = tuple(int(d) for d in MSVC_VERSION.split('.'))[:2] if (len(MSVC_VERSION) == 1): MSVC_VERSION += (0,) except: usage("Invalid setting for --msvc-version") if MSVC_VERSION < (14, 0): warn_prefix = "%sERROR:%s " % (GetColor("red"), GetColor()) print("=========================================================================") print(warn_prefix + "Support for MSVC versions before 2015 has been discontinued.") print(warn_prefix + "For more information, or any questions, please visit:") print(warn_prefix + " https://github.com/panda3d/panda3d/issues/288") print("=========================================================================") sys.stdout.flush() time.sleep(1.0) sys.exit(1) if not WINDOWS_SDK: print("No Windows SDK version specified. Defaulting to '7.1'.") WINDOWS_SDK = '7.1' if clean_build and os.path.isdir(GetOutputDir()): print("Deleting %s" % (GetOutputDir())) shutil.rmtree(GetOutputDir()) parseopts(sys.argv[1:]) ######################################################################## ## ## Handle environment variables. ## ######################################################################## if ("CFLAGS" in os.environ): CFLAGS = os.environ["CFLAGS"].strip() if ("CXXFLAGS" in os.environ): CXXFLAGS = os.environ["CXXFLAGS"].strip() if ("RPM_OPT_FLAGS" in os.environ): CFLAGS += " " + os.environ["RPM_OPT_FLAGS"].strip() CXXFLAGS += " " + os.environ["RPM_OPT_FLAGS"].strip() if ("LDFLAGS" in os.environ): LDFLAGS = os.environ["LDFLAGS"].strip() os.environ["MAKEPANDA"] = os.path.abspath(sys.argv[0]) if GetHost() == "darwin" and OSXTARGET is not None: os.environ["MACOSX_DEPLOYMENT_TARGET"] = "%d.%d" % OSXTARGET ######################################################################## ## ## Configure things based on the command-line parameters. ## ######################################################################## PLUGIN_VERSION = ParsePluginVersion("dtool/PandaVersion.pp") COREAPI_VERSION = PLUGIN_VERSION + "." + ParseCoreapiVersion("dtool/PandaVersion.pp") if VERSION is None: if RUNTIME: VERSION = PLUGIN_VERSION else: # Take the value from the setup.cfg file. VERSION = GetMetadataValue('version') if WHLVERSION is None: WHLVERSION = VERSION print("Version: %s" % VERSION) if RUNTIME or RTDIST: print("Core API Version: %s" % COREAPI_VERSION) if DEBVERSION is None: DEBVERSION = VERSION MAJOR_VERSION = '.'.join(VERSION.split('.')[:2]) if P3DSUFFIX is None: P3DSUFFIX = MAJOR_VERSION outputdir_suffix = "" if (RUNTIME or RTDIST): # Compiling Maya/Max is pointless in rtdist build for ver in MAYAVERSIONS + MAXVERSIONS: PkgDisable(ver) if (DISTRIBUTOR.strip() == ""): exit("You must provide a valid distributor name when making a runtime or rtdist build!") outputdir_suffix += "_" + DISTRIBUTOR.strip() if (RUNTIME): outputdir_suffix += "_rt" if DISTRIBUTOR == "": DISTRIBUTOR = "makepanda" elif not RTDIST_VERSION: RTDIST_VERSION = DISTRIBUTOR.strip() + "_" + MAJOR_VERSION if not RTDIST_VERSION: RTDIST_VERSION = "dev" if not IsCustomOutputDir(): if GetTarget() == "windows" and GetTargetArch() == 'x64': outputdir_suffix += '_x64' SetOutputDir("built" + outputdir_suffix) if (RUNTIME): for pkg in PkgListGet(): if pkg in ["GTK2", "MFC"]: # Optional package(s) for runtime. pass elif pkg in ["OPENSSL", "ZLIB"]: # Required packages for runtime. if (PkgSkip(pkg)==1): exit("Runtime must be compiled with OpenSSL and ZLib support!") else: # Unused packages for runtime. PkgDisable(pkg) if (INSTALLER and RTDIST): exit("Cannot build an installer for the rtdist build!") if (WHEEL and RUNTIME): exit("Cannot build a wheel for the runtime build!") if (WHEEL and RTDIST): exit("Cannot build a wheel for the rtdist build!") if (INSTALLER) and (PkgSkip("PYTHON")) and (not RUNTIME) and GetTarget() == 'windows': exit("Cannot build installer on Windows without python") if WHEEL and PkgSkip("PYTHON"): exit("Cannot build wheel without Python") if (RTDIST) and (PkgSkip("WX") and PkgSkip("FLTK")): exit("Cannot build rtdist without wx or fltk") if (RUNTIME): SetLinkAllStatic(True) if not os.path.isdir("contrib"): PkgDisable("CONTRIB") ######################################################################## ## ## Load the dependency cache. ## ######################################################################## LoadDependencyCache() ######################################################################## ## ## Locate various SDKs. ## ######################################################################## MakeBuildTree() SdkLocateDirectX(STRDXSDKVERSION) SdkLocateMaya() SdkLocateMax() SdkLocateMacOSX(OSXTARGET) SdkLocatePython(RTDIST) SdkLocateWindows(WINDOWS_SDK) SdkLocatePhysX() SdkLocateSpeedTree() SdkLocateAndroid() SdkAutoDisableDirectX() SdkAutoDisableMaya() SdkAutoDisableMax() SdkAutoDisablePhysX() SdkAutoDisableSpeedTree() if RTDIST and DISTRIBUTOR == "cmu": # Some validation checks for the CMU builds. if (RTDIST_VERSION == "cmu_1.7" and SDK["PYTHONVERSION"] != "python2.6"): exit("The CMU 1.7 runtime distribution must be built against Python 2.6!") elif (RTDIST_VERSION == "cmu_1.8" and SDK["PYTHONVERSION"] != "python2.7"): exit("The CMU 1.8 runtime distribution must be built against Python 2.7!") elif (RTDIST_VERSION == "cmu_1.9" and SDK["PYTHONVERSION"] != "python2.7"): exit("The CMU 1.9 runtime distribution must be built against Python 2.7!") if RTDIST and not HOST_URL: exit("You must specify a host URL when building the rtdist!") if RUNTIME and not HOST_URL: # Set this to a nice default. HOST_URL = "https://runtime.panda3d.org/" ######################################################################## ## ## Choose a Compiler. ## ## This should also set up any environment variables needed to make ## the compiler work. ## ######################################################################## if GetHost() == 'windows' and GetTarget() == 'windows': COMPILER = "MSVC" SdkLocateVisualStudio(MSVC_VERSION) else: COMPILER = "GCC" SetupBuildEnvironment(COMPILER) ######################################################################## ## ## External includes, external libraries, and external defsyms. ## ######################################################################## IncDirectory("ALWAYS", GetOutputDir()+"/tmp") IncDirectory("ALWAYS", GetOutputDir()+"/include") if (COMPILER == "MSVC"): PkgDisable("X11") PkgDisable("GLES") PkgDisable("GLES2") PkgDisable("EGL") PkgDisable("CARBON") PkgDisable("COCOA") DefSymbol("FLEX", "YY_NO_UNISTD_H") if (PkgSkip("PYTHON")==0): IncDirectory("ALWAYS", SDK["PYTHON"] + "/include") LibDirectory("ALWAYS", SDK["PYTHON"] + "/libs") SmartPkgEnable("EIGEN", "eigen3", (), ("Eigen/Dense",), target_pkg = 'ALWAYS') for pkg in PkgListGet(): if (PkgSkip(pkg)==0): if (pkg[:4]=="MAYA"): IncDirectory(pkg, SDK[pkg] + "/include") DefSymbol(pkg, "MAYAVERSION", pkg) DefSymbol(pkg, "MLIBRARY_DONTUSE_MFC_MANIFEST", "") elif (pkg[:3]=="MAX"): IncDirectory(pkg, SDK[pkg] + "/include") IncDirectory(pkg, SDK[pkg] + "/include/CS") IncDirectory(pkg, SDK[pkg+"CS"] + "/include") IncDirectory(pkg, SDK[pkg+"CS"] + "/include/CS") DefSymbol(pkg, "MAX", pkg) if (int(pkg[3:]) >= 2013): DefSymbol(pkg, "UNICODE", "") DefSymbol(pkg, "_UNICODE", "") elif (pkg[:2]=="DX"): IncDirectory(pkg, SDK[pkg] + "/include") elif GetThirdpartyDir() is not None: IncDirectory(pkg, GetThirdpartyDir() + pkg.lower() + "/include") for pkg in DXVERSIONS: if (PkgSkip(pkg)==0): vnum=pkg[2:] if GetTargetArch() == 'x64': LibDirectory(pkg, SDK[pkg] + '/lib/x64') else: LibDirectory(pkg, SDK[pkg] + '/lib/x86') LibDirectory(pkg, SDK[pkg] + '/lib') LibName(pkg, 'd3dVNUM.lib'.replace("VNUM", vnum)) LibName(pkg, 'd3dxVNUM.lib'.replace("VNUM", vnum)) if int(vnum) >= 9 and "GENERIC_DXERR_LIBRARY" in SDK: LibName(pkg, 'dxerr.lib') else: LibName(pkg, 'dxerrVNUM.lib'.replace("VNUM", vnum)) #LibName(pkg, 'ddraw.lib') LibName(pkg, 'dxguid.lib') if SDK.get("VISUALSTUDIO_VERSION") >= (14,0): # dxerr needs this for __vsnwprintf definition. LibName(pkg, 'legacy_stdio_definitions.lib') if not PkgSkip("FREETYPE") and os.path.isdir(GetThirdpartyDir() + "freetype/include/freetype2"): IncDirectory("FREETYPE", GetThirdpartyDir() + "freetype/include/freetype2") IncDirectory("ALWAYS", GetThirdpartyDir() + "extras/include") LibName("WINSOCK", "wsock32.lib") LibName("WINSOCK2", "wsock32.lib") LibName("WINSOCK2", "ws2_32.lib") LibName("WINCOMCTL", "comctl32.lib") LibName("WINCOMDLG", "comdlg32.lib") LibName("WINUSER", "user32.lib") LibName("WINMM", "winmm.lib") LibName("WINIMM", "imm32.lib") LibName("WINKERNEL", "kernel32.lib") LibName("WINOLE", "ole32.lib") LibName("WINOLEAUT", "oleaut32.lib") LibName("WINOLDNAMES", "oldnames.lib") LibName("WINSHELL", "shell32.lib") LibName("WINGDI", "gdi32.lib") LibName("ADVAPI", "advapi32.lib") LibName("IPHLPAPI", "iphlpapi.lib") LibName("SETUPAPI", "setupapi.lib") LibName("GL", "opengl32.lib") LibName("GLES", "libgles_cm.lib") LibName("GLES2", "libGLESv2.lib") LibName("EGL", "libEGL.lib") LibName("MSIMG", "msimg32.lib") if (PkgSkip("DIRECTCAM")==0): LibName("DIRECTCAM", "strmiids.lib") if (PkgSkip("DIRECTCAM")==0): LibName("DIRECTCAM", "quartz.lib") if (PkgSkip("DIRECTCAM")==0): LibName("DIRECTCAM", "odbc32.lib") if (PkgSkip("DIRECTCAM")==0): LibName("DIRECTCAM", "odbccp32.lib") if (PkgSkip("OPENSSL")==0): if os.path.isfile(GetThirdpartyDir() + "openssl/lib/libpandassl.lib"): LibName("OPENSSL", GetThirdpartyDir() + "openssl/lib/libpandassl.lib") LibName("OPENSSL", GetThirdpartyDir() + "openssl/lib/libpandaeay.lib") else: LibName("OPENSSL", GetThirdpartyDir() + "openssl/lib/libeay32.lib") LibName("OPENSSL", GetThirdpartyDir() + "openssl/lib/ssleay32.lib") if (PkgSkip("PNG")==0): if os.path.isfile(GetThirdpartyDir() + "png/lib/libpng16_static.lib"): LibName("PNG", GetThirdpartyDir() + "png/lib/libpng16_static.lib") else: LibName("PNG", GetThirdpartyDir() + "png/lib/libpng_static.lib") if (PkgSkip("TIFF")==0): if os.path.isfile(GetThirdpartyDir() + "tiff/lib/libtiff.lib"): LibName("TIFF", GetThirdpartyDir() + "tiff/lib/libtiff.lib") else: LibName("TIFF", GetThirdpartyDir() + "tiff/lib/tiff.lib") if (PkgSkip("OPENEXR")==0): suffix = "" if os.path.isfile(GetThirdpartyDir() + "openexr/lib/IlmImf-2_2.lib"): suffix = "-2_2" elif os.path.isfile(GetThirdpartyDir() + "openexr/lib/IlmImf-2_3.lib"): suffix = "-2_3" if os.path.isfile(GetThirdpartyDir() + "openexr/lib/IlmImf" + suffix + "_s.lib"): suffix += "_s" LibName("OPENEXR", GetThirdpartyDir() + "openexr/lib/IlmImf" + suffix + ".lib") LibName("OPENEXR", GetThirdpartyDir() + "openexr/lib/IlmThread" + suffix + ".lib") LibName("OPENEXR", GetThirdpartyDir() + "openexr/lib/Iex" + suffix + ".lib") if suffix == "-2_2": LibName("OPENEXR", GetThirdpartyDir() + "openexr/lib/Half.lib") else: LibName("OPENEXR", GetThirdpartyDir() + "openexr/lib/Half" + suffix + ".lib") IncDirectory("OPENEXR", GetThirdpartyDir() + "openexr/include/OpenEXR") if (PkgSkip("JPEG")==0): LibName("JPEG", GetThirdpartyDir() + "jpeg/lib/jpeg-static.lib") if (PkgSkip("ZLIB")==0): LibName("ZLIB", GetThirdpartyDir() + "zlib/lib/zlibstatic.lib") if (PkgSkip("VRPN")==0): LibName("VRPN", GetThirdpartyDir() + "vrpn/lib/vrpn.lib") if (PkgSkip("VRPN")==0): LibName("VRPN", GetThirdpartyDir() + "vrpn/lib/quat.lib") if (PkgSkip("NVIDIACG")==0): LibName("CGGL", GetThirdpartyDir() + "nvidiacg/lib/cgGL.lib") if (PkgSkip("NVIDIACG")==0): LibName("CGDX9", GetThirdpartyDir() + "nvidiacg/lib/cgD3D9.lib") if (PkgSkip("NVIDIACG")==0): LibName("NVIDIACG", GetThirdpartyDir() + "nvidiacg/lib/cg.lib") if (PkgSkip("FREETYPE")==0): LibName("FREETYPE", GetThirdpartyDir() + "freetype/lib/freetype.lib") if (PkgSkip("HARFBUZZ")==0): LibName("HARFBUZZ", GetThirdpartyDir() + "harfbuzz/lib/harfbuzz.lib") IncDirectory("HARFBUZZ", GetThirdpartyDir() + "harfbuzz/include/harfbuzz") if (PkgSkip("FFTW")==0): LibName("FFTW", GetThirdpartyDir() + "fftw/lib/fftw3.lib") if (PkgSkip("ARTOOLKIT")==0):LibName("ARTOOLKIT",GetThirdpartyDir() + "artoolkit/lib/libAR.lib") if (PkgSkip("OPENCV")==0): LibName("OPENCV", GetThirdpartyDir() + "opencv/lib/cv.lib") if (PkgSkip("OPENCV")==0): LibName("OPENCV", GetThirdpartyDir() + "opencv/lib/highgui.lib") if (PkgSkip("OPENCV")==0): LibName("OPENCV", GetThirdpartyDir() + "opencv/lib/cvaux.lib") if (PkgSkip("OPENCV")==0): LibName("OPENCV", GetThirdpartyDir() + "opencv/lib/ml.lib") if (PkgSkip("OPENCV")==0): LibName("OPENCV", GetThirdpartyDir() + "opencv/lib/cxcore.lib") if (PkgSkip("FFMPEG")==0): LibName("FFMPEG", GetThirdpartyDir() + "ffmpeg/lib/avcodec.lib") if (PkgSkip("FFMPEG")==0): LibName("FFMPEG", GetThirdpartyDir() + "ffmpeg/lib/avformat.lib") if (PkgSkip("FFMPEG")==0): LibName("FFMPEG", GetThirdpartyDir() + "ffmpeg/lib/avutil.lib") if (PkgSkip("SWSCALE")==0): LibName("SWSCALE", GetThirdpartyDir() + "ffmpeg/lib/swscale.lib") if (PkgSkip("SWRESAMPLE")==0):LibName("SWRESAMPLE",GetThirdpartyDir() + "ffmpeg/lib/swresample.lib") if (PkgSkip("FCOLLADA")==0): LibName("FCOLLADA", GetThirdpartyDir() + "fcollada/lib/FCollada.lib") IncDirectory("FCOLLADA", GetThirdpartyDir() + "fcollada/include/FCollada") if (PkgSkip("ASSIMP")==0): LibName("ASSIMP", GetThirdpartyDir() + "assimp/lib/assimp.lib") if os.path.isfile(GetThirdpartyDir() + "assimp/lib/IrrXML.lib"): LibName("ASSIMP", GetThirdpartyDir() + "assimp/lib/IrrXML.lib") IncDirectory("ASSIMP", GetThirdpartyDir() + "assimp/include") if (PkgSkip("SQUISH")==0): if GetOptimize() <= 2: LibName("SQUISH", GetThirdpartyDir() + "squish/lib/squishd.lib") else: LibName("SQUISH", GetThirdpartyDir() + "squish/lib/squish.lib") if (PkgSkip("ROCKET")==0): LibName("ROCKET", GetThirdpartyDir() + "rocket/lib/RocketCore.lib") LibName("ROCKET", GetThirdpartyDir() + "rocket/lib/RocketControls.lib") if (PkgSkip("PYTHON")==0): LibName("ROCKET", GetThirdpartyDir() + "rocket/lib/" + SDK["PYTHONVERSION"] + "/boost_python-vc100-mt-1_54.lib") if (GetOptimize() <= 3): LibName("ROCKET", GetThirdpartyDir() + "rocket/lib/RocketDebugger.lib") if (PkgSkip("OPENAL")==0): LibName("OPENAL", GetThirdpartyDir() + "openal/lib/OpenAL32.lib") if not os.path.isfile(GetThirdpartyDir() + "openal/bin/OpenAL32.dll"): # Link OpenAL Soft statically. DefSymbol("OPENAL", "AL_LIBTYPE_STATIC") if (PkgSkip("ODE")==0): LibName("ODE", GetThirdpartyDir() + "ode/lib/ode_single.lib") DefSymbol("ODE", "dSINGLE", "") if (PkgSkip("FMODEX")==0): if (GetTargetArch() == 'x64'): LibName("FMODEX", GetThirdpartyDir() + "fmodex/lib/fmodex64_vc.lib") else: LibName("FMODEX", GetThirdpartyDir() + "fmodex/lib/fmodex_vc.lib") if (PkgSkip("FLTK")==0 and RTDIST): LibName("FLTK", GetThirdpartyDir() + "fltk/lib/fltk.lib") if not PkgSkip("FLTK"): # If we have fltk, we don't need wx PkgDisable("WX") if (PkgSkip("WX")==0 and RTDIST): LibName("WX", GetThirdpartyDir() + "wx/lib/wxbase28u.lib") LibName("WX", GetThirdpartyDir() + "wx/lib/wxmsw28u_core.lib") DefSymbol("WX", "__WXMSW__", "") DefSymbol("WX", "_UNICODE", "") DefSymbol("WX", "UNICODE", "") if (PkgSkip("VORBIS")==0): for lib in ('ogg', 'vorbis', 'vorbisfile'): path = GetThirdpartyDir() + "vorbis/lib/lib{0}_static.lib".format(lib) if not os.path.isfile(path): path = GetThirdpartyDir() + "vorbis/lib/{0}.lib".format(lib) LibName("VORBIS", path) if (PkgSkip("OPUS")==0): LibName("OPUS", GetThirdpartyDir() + "opus/lib/libogg_static.lib") LibName("OPUS", GetThirdpartyDir() + "opus/lib/libopus_static.lib") LibName("OPUS", GetThirdpartyDir() + "opus/lib/libopusfile_static.lib") for pkg in MAYAVERSIONS: if (PkgSkip(pkg)==0): LibName(pkg, '"' + SDK[pkg] + '/lib/Foundation.lib"') LibName(pkg, '"' + SDK[pkg] + '/lib/OpenMaya.lib"') LibName(pkg, '"' + SDK[pkg] + '/lib/OpenMayaAnim.lib"') LibName(pkg, '"' + SDK[pkg] + '/lib/OpenMayaUI.lib"') for pkg in MAXVERSIONS: if (PkgSkip(pkg)==0): LibName(pkg, SDK[pkg] + '/lib/core.lib') LibName(pkg, SDK[pkg] + '/lib/edmodel.lib') LibName(pkg, SDK[pkg] + '/lib/gfx.lib') LibName(pkg, SDK[pkg] + '/lib/geom.lib') LibName(pkg, SDK[pkg] + '/lib/mesh.lib') LibName(pkg, SDK[pkg] + '/lib/maxutil.lib') LibName(pkg, SDK[pkg] + '/lib/paramblk2.lib') if (PkgSkip("PHYSX")==0): if GetTargetArch() == 'x64': LibName("PHYSX", SDK["PHYSXLIBS"] + "/PhysXLoader64.lib") LibName("PHYSX", SDK["PHYSXLIBS"] + "/NxCharacter64.lib") else: LibName("PHYSX", SDK["PHYSXLIBS"] + "/PhysXLoader.lib") LibName("PHYSX", SDK["PHYSXLIBS"] + "/NxCharacter.lib") IncDirectory("PHYSX", SDK["PHYSX"] + "/Physics/include") IncDirectory("PHYSX", SDK["PHYSX"] + "/PhysXLoader/include") IncDirectory("PHYSX", SDK["PHYSX"] + "/NxCharacter/include") IncDirectory("PHYSX", SDK["PHYSX"] + "/NxExtensions/include") IncDirectory("PHYSX", SDK["PHYSX"] + "/Foundation/include") IncDirectory("PHYSX", SDK["PHYSX"] + "/Cooking/include") if (PkgSkip("SPEEDTREE")==0): if GetTargetArch() == 'x64': libdir = SDK["SPEEDTREE"] + "/Lib/Windows/VC10.x64/" p64ext = '64' else: libdir = SDK["SPEEDTREE"] + "/Lib/Windows/VC10/" p64ext = '' debugext = '' if (GetOptimize() <= 2): debugext = "_d" libsuffix = "_v%s_VC100MT%s_Static%s.lib" % ( SDK["SPEEDTREEVERSION"], p64ext, debugext) LibName("SPEEDTREE", "%sSpeedTreeCore%s" % (libdir, libsuffix)) LibName("SPEEDTREE", "%sSpeedTreeForest%s" % (libdir, libsuffix)) LibName("SPEEDTREE", "%sSpeedTree%sRenderer%s" % (libdir, SDK["SPEEDTREEAPI"], libsuffix)) LibName("SPEEDTREE", "%sSpeedTreeRenderInterface%s" % (libdir, libsuffix)) if (SDK["SPEEDTREEAPI"] == "OpenGL"): LibName("SPEEDTREE", "%sglew32.lib" % (libdir)) LibName("SPEEDTREE", "glu32.lib") IncDirectory("SPEEDTREE", SDK["SPEEDTREE"] + "/Include") if (PkgSkip("BULLET")==0): suffix = '.lib' if GetTargetArch() == 'x64' and os.path.isfile(GetThirdpartyDir() + "bullet/lib/BulletCollision_x64.lib"): suffix = '_x64.lib' LibName("BULLET", GetThirdpartyDir() + "bullet/lib/LinearMath" + suffix) LibName("BULLET", GetThirdpartyDir() + "bullet/lib/BulletCollision" + suffix) LibName("BULLET", GetThirdpartyDir() + "bullet/lib/BulletDynamics" + suffix) LibName("BULLET", GetThirdpartyDir() + "bullet/lib/BulletSoftBody" + suffix) if (COMPILER=="GCC"): if GetTarget() != "darwin": PkgDisable("CARBON") PkgDisable("COCOA") elif RUNTIME: # We don't support Cocoa in the runtime yet. PkgDisable("COCOA") if 'x86_64' in OSX_ARCHS: # 64-bits OS X doesn't have Carbon. PkgDisable("CARBON") #if (PkgSkip("PYTHON")==0): # IncDirectory("PYTHON", SDK["PYTHON"]) if (GetHost() == "darwin"): if (PkgSkip("FREETYPE")==0 and not os.path.isdir(GetThirdpartyDir() + 'freetype')): IncDirectory("FREETYPE", "/usr/X11/include") IncDirectory("FREETYPE", "/usr/X11/include/freetype2") LibDirectory("FREETYPE", "/usr/X11/lib") if (GetHost() == "freebsd"): IncDirectory("ALWAYS", "/usr/local/include") LibDirectory("ALWAYS", "/usr/local/lib") if (os.path.isdir("/usr/PCBSD")): IncDirectory("ALWAYS", "/usr/PCBSD/local/include") LibDirectory("ALWAYS", "/usr/PCBSD/local/lib") if GetTarget() != "windows": PkgDisable("DIRECTCAM") fcollada_libs = ("FColladaD", "FColladaSD", "FColladaS") # WARNING! The order of the ffmpeg libraries matters! ffmpeg_libs = ("libavformat", "libavcodec", "libavutil") # Name pkg-config libs, include(dir)s if (not RUNTIME): SmartPkgEnable("EIGEN", "eigen3", (), ("Eigen/Dense",), target_pkg = 'ALWAYS') SmartPkgEnable("ARTOOLKIT", "", ("AR"), "AR/ar.h") SmartPkgEnable("FCOLLADA", "", ChooseLib(fcollada_libs, "FCOLLADA"), ("FCollada", "FCollada/FCollada.h")) SmartPkgEnable("ASSIMP", "assimp", ("assimp"), "assimp/Importer.hpp") SmartPkgEnable("FFMPEG", ffmpeg_libs, ffmpeg_libs, ("libavformat/avformat.h", "libavcodec/avcodec.h", "libavutil/avutil.h")) SmartPkgEnable("SWSCALE", "libswscale", "libswscale", ("libswscale/swscale.h"), target_pkg = "FFMPEG", thirdparty_dir = "ffmpeg") SmartPkgEnable("SWRESAMPLE","libswresample", "libswresample", ("libswresample/swresample.h"), target_pkg = "FFMPEG", thirdparty_dir = "ffmpeg") SmartPkgEnable("FFTW", "", ("fftw3"), ("fftw.h")) SmartPkgEnable("FMODEX", "", ("fmodex"), ("fmodex", "fmodex/fmod.h")) SmartPkgEnable("FREETYPE", "freetype2", ("freetype"), ("freetype2", "freetype2/freetype/freetype.h")) SmartPkgEnable("HARFBUZZ", "harfbuzz", ("harfbuzz"), ("harfbuzz", "harfbuzz/hb-ft.h")) SmartPkgEnable("GL", "gl", ("GL"), ("GL/gl.h"), framework = "OpenGL") SmartPkgEnable("GLES", "glesv1_cm", ("GLESv1_CM"), ("GLES/gl.h"), framework = "OpenGLES") SmartPkgEnable("GLES2", "glesv2", ("GLESv2"), ("GLES2/gl2.h")) #framework = "OpenGLES"? SmartPkgEnable("EGL", "egl", ("EGL"), ("EGL/egl.h")) SmartPkgEnable("NVIDIACG", "", ("Cg"), "Cg/cg.h", framework = "Cg") SmartPkgEnable("ODE", "", ("ode"), "ode/ode.h", tool = "ode-config") SmartPkgEnable("OPENAL", "openal", ("openal"), "AL/al.h", framework = "OpenAL") SmartPkgEnable("SQUISH", "", ("squish"), "squish.h") SmartPkgEnable("TIFF", "libtiff-4", ("tiff"), "tiff.h") SmartPkgEnable("OPENEXR", "OpenEXR", ("IlmImf", "Imath", "Half", "Iex", "IexMath", "IlmThread"), ("OpenEXR", "OpenEXR/ImfOutputFile.h")) SmartPkgEnable("VRPN", "", ("vrpn", "quat"), ("vrpn", "quat.h", "vrpn/vrpn_Types.h")) SmartPkgEnable("BULLET", "bullet", ("BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath"), ("bullet", "bullet/btBulletDynamicsCommon.h")) SmartPkgEnable("VORBIS", "vorbisfile",("vorbisfile", "vorbis", "ogg"), ("ogg/ogg.h", "vorbis/vorbisfile.h")) SmartPkgEnable("OPUS", "opusfile", ("opusfile", "opus", "ogg"), ("ogg/ogg.h", "opus/opusfile.h", "opus")) SmartPkgEnable("JPEG", "", ("jpeg"), "jpeglib.h") SmartPkgEnable("PNG", "libpng", ("png"), "png.h", tool = "libpng-config") if not PkgSkip("FFMPEG"): if GetTarget() == "darwin": LibName("FFMPEG", "-Wl,-read_only_relocs,suppress") LibName("FFMPEG", "-framework VideoDecodeAcceleration") elif os.path.isfile(GetThirdpartyDir() + "ffmpeg/lib/libavcodec.a"): # Needed when linking ffmpeg statically on Linux. LibName("FFMPEG", "-Wl,-Bsymbolic") if PkgSkip("FFMPEG") or GetTarget() == "darwin": cv_lib = ChooseLib(("opencv_core", "cv"), "OPENCV") if cv_lib == "opencv_core": OPENCV_VER_23 = True SmartPkgEnable("OPENCV", "opencv", ("opencv_core", "opencv_highgui"), ("opencv2/core/core.hpp")) else: SmartPkgEnable("OPENCV", "opencv", ("cv", "highgui", "cvaux", "ml", "cxcore"), ("opencv", "opencv/cv.h", "opencv/cxcore.h", "opencv/highgui.h")) else: PkgDisable("OPENCV") if not PkgSkip("ASSIMP") and \ os.path.isfile(GetThirdpartyDir() + "assimp/lib/libassimp.a"): # Also pick up IrrXML, which is needed when linking statically. irrxml = GetThirdpartyDir() + "assimp/lib/libIrrXML.a" if os.path.isfile(irrxml): LibName("ASSIMP", irrxml) rocket_libs = ("RocketCore", "RocketControls") if (GetOptimize() <= 3): rocket_libs += ("RocketDebugger",) rocket_libs += ("boost_python",) SmartPkgEnable("ROCKET", "", rocket_libs, "Rocket/Core.h") if not PkgSkip("PYTHON"): python_lib = SDK["PYTHONVERSION"] if not RTDIST and GetTarget() != 'android': # We don't link anything in the SDK with libpython. python_lib = "" SmartPkgEnable("PYTHON", "", python_lib, (SDK["PYTHONVERSION"], SDK["PYTHONVERSION"] + "/Python.h")) SmartPkgEnable("OPENSSL", "openssl", ("ssl", "crypto"), ("openssl/ssl.h", "openssl/crypto.h")) SmartPkgEnable("ZLIB", "zlib", ("z"), "zlib.h") SmartPkgEnable("GTK2", "gtk+-2.0") if (RTDIST): SmartPkgEnable("WX", tool = "wx-config") SmartPkgEnable("FLTK", "", ("fltk"), ("FL/Fl.H"), tool = "fltk-config") if GetTarget() != 'darwin': # CgGL is covered by the Cg framework, and we don't need X11 components on OSX if not PkgSkip("NVIDIACG") and not RUNTIME: SmartPkgEnable("CGGL", "", ("CgGL"), "Cg/cgGL.h", thirdparty_dir = "nvidiacg") if not RUNTIME: SmartPkgEnable("X11", "x11", "X11", ("X11", "X11/Xlib.h", "X11/XKBlib.h")) if GetHost() != "darwin": # Workaround for an issue where pkg-config does not include this path if GetTargetArch() in ("x86_64", "amd64"): if (os.path.isdir("/usr/lib64/glib-2.0/include")): IncDirectory("GTK2", "/usr/lib64/glib-2.0/include") if (os.path.isdir("/usr/lib64/gtk-2.0/include")): IncDirectory("GTK2", "/usr/lib64/gtk-2.0/include") if not PkgSkip("X11"): if (os.path.isdir("/usr/X11R6/lib64")): LibDirectory("ALWAYS", "/usr/X11R6/lib64") else: LibDirectory("ALWAYS", "/usr/X11R6/lib") elif not PkgSkip("X11"): LibDirectory("ALWAYS", "/usr/X11R6/lib") if RUNTIME: # For the runtime, these packages are required for pkg in ["OPENSSL", "ZLIB"]: skips = [] if (pkg in PkgListGet() and PkgSkip(pkg)==1): skips.append(pkg) if skips: exit("Runtime must be compiled with OpenSSL and ZLib support (missing %s)" % (', '.join(skips))) for pkg in MAYAVERSIONS: if (PkgSkip(pkg)==0 and (pkg in SDK)): if (GetHost() == "darwin"): # Sheesh, Autodesk really can't make up their mind # regarding the location of the Maya devkit on OS X. if (os.path.isdir(SDK[pkg] + "/Maya.app/Contents/lib")): LibDirectory(pkg, SDK[pkg] + "/Maya.app/Contents/lib") if (os.path.isdir(SDK[pkg] + "/Maya.app/Contents/MacOS")): LibDirectory(pkg, SDK[pkg] + "/Maya.app/Contents/MacOS") if (os.path.isdir(SDK[pkg] + "/lib")): LibDirectory(pkg, SDK[pkg] + "/lib") if (os.path.isdir(SDK[pkg] + "/Maya.app/Contents/include/maya")): IncDirectory(pkg, SDK[pkg] + "/Maya.app/Contents/include") if (os.path.isdir(SDK[pkg] + "/devkit/include/maya")): IncDirectory(pkg, SDK[pkg] + "/devkit/include") if (os.path.isdir(SDK[pkg] + "/include/maya")): IncDirectory(pkg, SDK[pkg] + "/include") else: LibDirectory(pkg, SDK[pkg] + "/lib") IncDirectory(pkg, SDK[pkg] + "/include") DefSymbol(pkg, "MAYAVERSION", pkg) if GetTarget() == 'darwin': LibName("ALWAYS", "-framework AppKit") LibName("AGL", "-framework AGL") LibName("CARBON", "-framework Carbon") LibName("COCOA", "-framework Cocoa") # Fix for a bug in OSX Leopard: LibName("GL", "-dylib_file /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib:/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib") if GetTarget() == 'android': LibName("ALWAYS", '-llog') LibName("ANDROID", '-landroid') LibName("JNIGRAPHICS", '-ljnigraphics') for pkg in MAYAVERSIONS: if (PkgSkip(pkg)==0 and (pkg in SDK)): if GetTarget() == 'darwin': LibName(pkg, "-Wl,-rpath," + SDK[pkg] + "/Maya.app/Contents/MacOS") else: LibName(pkg, "-Wl,-rpath," + SDK[pkg] + "/lib") LibName(pkg, "-lOpenMaya") LibName(pkg, "-lOpenMayaAnim") LibName(pkg, "-lAnimSlice") LibName(pkg, "-lDeformSlice") LibName(pkg, "-lModifiers") LibName(pkg, "-lDynSlice") LibName(pkg, "-lKinSlice") LibName(pkg, "-lModelSlice") LibName(pkg, "-lNurbsSlice") LibName(pkg, "-lPolySlice") LibName(pkg, "-lProjectSlice") LibName(pkg, "-lImage") LibName(pkg, "-lShared") LibName(pkg, "-lTranslators") LibName(pkg, "-lDataModel") LibName(pkg, "-lRenderModel") LibName(pkg, "-lNurbsEngine") LibName(pkg, "-lDependEngine") LibName(pkg, "-lCommandEngine") LibName(pkg, "-lFoundation") LibName(pkg, "-lIMFbase") if GetTarget() != 'darwin': LibName(pkg, "-lOpenMayalib") else: LibName(pkg, "-dylib_file /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib:/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib") if (PkgSkip("PHYSX")==0): IncDirectory("PHYSX", SDK["PHYSX"] + "/Physics/include") IncDirectory("PHYSX", SDK["PHYSX"] + "/PhysXLoader/include") IncDirectory("PHYSX", SDK["PHYSX"] + "/NxCharacter/include") IncDirectory("PHYSX", SDK["PHYSX"] + "/NxExtensions/include") IncDirectory("PHYSX", SDK["PHYSX"] + "/Foundation/include") IncDirectory("PHYSX", SDK["PHYSX"] + "/Cooking/include") LibDirectory("PHYSX", SDK["PHYSXLIBS"]) if (GetHost() == "darwin"): LibName("PHYSX", SDK["PHYSXLIBS"] + "/osxstatic/PhysXCooking.a") LibName("PHYSX", SDK["PHYSXLIBS"] + "/osxstatic/PhysXCore.a") else: LibName("PHYSX", "-lPhysXLoader") LibName("PHYSX", "-lNxCharacter") DefSymbol("WITHINPANDA", "WITHIN_PANDA", "1") if GetLinkAllStatic(): DefSymbol("ALWAYS", "LINK_ALL_STATIC") if GetTarget() == 'android': DefSymbol("ALWAYS", "ANDROID") if not PkgSkip("EIGEN"): if GetOptimize() >= 3: if COMPILER == "MSVC": # Squeeze out a bit more performance on MSVC builds... # Only do this if EIGEN_NO_DEBUG is also set, otherwise it # will turn them into runtime assertions. DefSymbol("ALWAYS", "EIGEN_NO_STATIC_ASSERT") ######################################################################## ## ## Give a Status Report on Command-Line Options ## ######################################################################## def printStatus(header,warnings): if GetVerbose(): print("") print("-------------------------------------------------------------------") print(header) tkeep = "" tomit = "" for x in PkgListGet(): if PkgSkip(x): tomit = tomit + x + " " else: tkeep = tkeep + x + " " if RTDIST: print("Makepanda: Runtime distribution build") elif RUNTIME: print("Makepanda: Runtime build") else: print("Makepanda: Regular build") print("Makepanda: Compiler: %s" % (COMPILER)) print("Makepanda: Optimize: %d" % (GetOptimize())) print("Makepanda: Keep Pkg: %s" % (tkeep)) print("Makepanda: Omit Pkg: %s" % (tomit)) if GENMAN: print("Makepanda: Generate API reference manual") else: print("Makepanda: Don't generate API reference manual") if GetHost() == "windows" and not RTDIST: if INSTALLER: print("Makepanda: Build installer, using %s" % (COMPRESSOR)) else: print("Makepanda: Don't build installer") print("Makepanda: Version ID: %s" % (VERSION)) for x in warnings: print("Makepanda: %s" % (x)) print("-------------------------------------------------------------------") print("") sys.stdout.flush() ######################################################################## ## ## BracketNameWithQuotes ## ######################################################################## def BracketNameWithQuotes(name): # Workaround for OSX bug - compiler doesn't like those flags quoted. if (name.startswith("-framework")): return name if (name.startswith("-dylib_file")): return name # Don't add quotes when it's not necessary. if " " not in name: return name # Account for quoted name (leave as is) but quote everything else (e.g., to protect spaces within paths from improper parsing) if (name.startswith('"') and name.endswith('"')): return name else: return '"' + name + '"' ######################################################################## ## ## CompileCxx ## ######################################################################## def CompileCxx(obj,src,opts): ipath = GetListOption(opts, "DIR:") optlevel = GetOptimizeOption(opts) if (COMPILER=="MSVC"): if not BOOUSEINTELCOMPILER: cmd = "cl " if GetTargetArch() == 'x64': cmd += "/favor:blend " cmd += "/wd4996 /wd4275 /wd4273 " # We still target Windows XP. cmd += "/DWINVER=0x501 " # Work around a WinXP/2003 bug when using VS 2015+. if SDK.get("VISUALSTUDIO_VERSION") >= (14,0): cmd += "/Zc:threadSafeInit- " cmd += "/Fo" + obj + " /nologo /c" if GetTargetArch() != 'x64' and (not PkgSkip("SSE2") or 'SSE2' in opts): cmd += " /arch:SSE2" for x in ipath: cmd += " /I" + x for (opt,dir) in INCDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += " /I" + BracketNameWithQuotes(dir) for (opt,var,val) in DEFSYMBOLS: if (opt=="ALWAYS") or (opt in opts): cmd += " /D" + var + "=" + val if (opts.count('MSFORSCOPE')): cmd += ' /Zc:forScope-' if (optlevel==1): cmd += " /MDd /Zi /RTCs /GS" if (optlevel==2): cmd += " /MDd /Zi" if (optlevel==3): cmd += " /MD /Zi /GS- /O2 /Ob2 /Oi /Ot /fp:fast" if (optlevel==4): cmd += " /MD /Zi /GS- /Ox /Ob2 /Oi /Ot /fp:fast /DFORCE_INLINING /DNDEBUG /GL" cmd += " /Oy /Zp16" # jean-claude add /Zp16 insures correct static alignment for SSEx cmd += " /Fd" + os.path.splitext(obj)[0] + ".pdb" building = GetValueOption(opts, "BUILDING:") if (building): cmd += " /DBUILDING_" + building if ("BIGOBJ" in opts) or GetTargetArch() == 'x64': cmd += " /bigobj" cmd += " /Zm300 /DWIN32_VC /DWIN32" if 'EXCEPTIONS' in opts: cmd += " /EHsc" else: cmd += " /D_HAS_EXCEPTIONS=0" if 'RTTI' not in opts: cmd += " /GR-" if GetTargetArch() == 'x64': cmd += " /DWIN64_VC /DWIN64" if WINDOWS_SDK.startswith('7.') and MSVC_VERSION > (10,): # To preserve Windows XP compatibility. cmd += " /D_USING_V110_SDK71_" cmd += " /W3 " + BracketNameWithQuotes(src) oscmd(cmd) else: cmd = "icl " if GetTargetArch() == 'x64': cmd += "/favor:blend " cmd += "/wd4996 /wd4275 /wd4267 /wd4101 /wd4273 " cmd += "/DWINVER=0x501 " cmd += "/Fo" + obj + " /c" for x in ipath: cmd += " /I" + x for (opt,dir) in INCDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += " /I" + BracketNameWithQuotes(dir) for (opt,var,val) in DEFSYMBOLS: if (opt=="ALWAYS") or (opt in opts): cmd += " /D" + var + "=" + val if (opts.count('MSFORSCOPE')): cmd += ' /Zc:forScope-' if (optlevel==1): cmd += " /MDd /Zi /RTCs /GS" if (optlevel==2): cmd += " /MDd /Zi /arch:SSE3" # core changes from jean-claude (dec 2011) # ---------------------------------------- # performance will be seeked at level 3 & 4 # ----------------------------------------- if (optlevel==3): cmd += " /MD /Zi /O2 /Oi /Ot /arch:SSE3" cmd += " /Ob0" cmd += " /Qipo-" # beware of IPO !!! ## Lesson learned: Don't use /GL flag -> end result is MESSY ## ---------------------------------------------------------------- if (optlevel==4): cmd += " /MD /Zi /O3 /Oi /Ot /Ob0 /Yc /DNDEBUG" # /Ob0 a ete rajoute en cours de route a 47% cmd += " /Qipo" # optimization multi file # for 3 & 4 optimization levels # ----------------------------- if (optlevel>=3): cmd += " /fp:fast=2" cmd += " /Qftz" cmd += " /Qfp-speculation:fast" cmd += " /Qopt-matmul" # needs /O2 or /O3 cmd += " /Qprec-div-" cmd += " /Qsimd" cmd += " /QxHost" # compile for target host; Compiling for distribs should probably strictly enforce /arch:.. cmd += " /Quse-intel-optimized-headers" # use intel optimized headers cmd += " /Qparallel" # enable parallelization cmd += " /Qvc10" # for Microsoft Visual C++ 2010 ## PCH files coexistence: the /Qpchi option causes the Intel C++ Compiler to name its ## PCH files with a .pchi filename suffix and reduce build time. ## The /Qpchi option is on by default but interferes with Microsoft libs; so use /Qpchi- to turn it off. ## I need to have a deeper look at this since the compile time is quite influenced by this setting !!! cmd += " /Qpchi-" # keep it this way! ## Inlining seems to be an issue here ! (the linker doesn't find necessary info later on) ## ------------------------------------ ## so don't use cmd += " /DFORCE_INLINING" (need to check why with Panda developpers!) ## Inline expansion /Ob1 : Allow functions marked inline to be inlined. ## Inline any /Ob2 : Inline functions deemed appropriate by compiler. ## Ctor displacement /vd0 : Disable constructor displacement. ## Choose this option only if no class constructors or destructors call virtual functions. ## Use /vd1 (default) to enable. Alternate: #pragma vtordisp ## Best case ptrs /vmb : Use best case "pointer to class member" representation. ## Use this option if you always define a class before you declare a pointer to a member of the class. ## The compiler will issue an error if it encounters a pointer declaration before the class is defined. ## Alternate: #pragma pointers_to_members cmd += " /Fd" + os.path.splitext(obj)[0] + ".pdb" building = GetValueOption(opts, "BUILDING:") if (building): cmd += " /DBUILDING_" + building if ("BIGOBJ" in opts) or GetTargetArch() == 'x64': cmd += " /bigobj" # level of warnings and optimization reports if GetVerbose(): cmd += " /W3 " # or /W4 or /Wall cmd += " /Qopt-report:2 /Qopt-report-phase:hlo /Qopt-report-phase:hpo" # some optimization reports else: cmd += " /W1 " cmd += " /EHa /Zm300 /DWIN32_VC /DWIN32" if GetTargetArch() == 'x64': cmd += " /DWIN64_VC /DWIN64" cmd += " " + BracketNameWithQuotes(src) oscmd(cmd) if (COMPILER=="GCC"): if (src.endswith(".c")): cmd = GetCC() +' -fPIC -c -o ' + obj else: cmd = GetCXX()+' -std=gnu++11 -ftemplate-depth-70 -fPIC -c -o ' + obj for (opt, dir) in INCDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += ' -I' + BracketNameWithQuotes(dir) for (opt, dir) in FRAMEWORKDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += ' -F' + BracketNameWithQuotes(dir) for (opt,var,val) in DEFSYMBOLS: if (opt=="ALWAYS") or (opt in opts): cmd += ' -D' + var + '=' + val for x in ipath: cmd += ' -I' + x if not GetLinkAllStatic() and 'NOHIDDEN' not in opts: cmd += ' -fvisibility=hidden' # Mac-specific flags. if GetTarget() == "darwin": cmd += " -Wno-deprecated-declarations" if OSXTARGET is not None: cmd += " -isysroot " + SDK["MACOSX"] cmd += " -mmacosx-version-min=%d.%d" % (OSXTARGET) for arch in OSX_ARCHS: if 'NOARCH:' + arch.upper() not in opts: cmd += " -arch %s" % arch if "SYSROOT" in SDK: if GetTarget() != "android": cmd += ' --sysroot=%s' % (SDK["SYSROOT"]) else: ndk_dir = SDK["ANDROID_NDK"].replace('\\', '/') cmd += ' -isystem %s/sysroot/usr/include' % (ndk_dir) cmd += ' -isystem %s/sysroot/usr/include/%s' % (ndk_dir, SDK["ANDROID_TRIPLE"]) cmd += ' -no-canonical-prefixes' # Android-specific flags. arch = GetTargetArch() if GetTarget() == "android": # Most of the specific optimization flags here were # just copied from the default Android Makefiles. if "ANDROID_API" in SDK: cmd += ' -D__ANDROID_API__=' + str(SDK["ANDROID_API"]) if "ANDROID_GCC_TOOLCHAIN" in SDK: cmd += ' -gcc-toolchain ' + SDK["ANDROID_GCC_TOOLCHAIN"].replace('\\', '/') cmd += ' -ffunction-sections -funwind-tables' if arch == 'armv7a': cmd += ' -target armv7-none-linux-androideabi' cmd += ' -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16' cmd += ' -fno-integrated-as' elif arch == 'arm': cmd += ' -target armv5te-none-linux-androideabi' cmd += ' -march=armv5te -mtune=xscale -msoft-float' cmd += ' -fno-integrated-as' elif arch == 'aarch64': cmd += ' -target aarch64-none-linux-android' elif arch == 'mips': cmd += ' -target mipsel-none-linux-android' cmd += ' -mips32' elif arch == 'mips64': cmd += ' -target mips64el-none-linux-android' cmd += ' -fintegrated-as' elif arch == 'x86': cmd += ' -target i686-none-linux-android' cmd += ' -march=i686 -mtune=intel -mssse3 -mfpmath=sse -m32' cmd += ' -mstackrealign' elif arch == 'x86_64': cmd += ' -target x86_64-none-linux-android' cmd += ' -march=x86-64 -msse4.2 -mpopcnt -m64 -mtune=intel' cmd += " -Wa,--noexecstack" # Do we want thumb or arm instructions? if arch.startswith('arm'): if optlevel >= 3: cmd += ' -mthumb' else: cmd += ' -marm' # Enable SIMD instructions if requested if arch.startswith('arm') and PkgSkip("NEON") == 0: cmd += ' -mfpu=neon' else: cmd += " -pthread" if not src.endswith(".c"): # We don't use exceptions for most modules. if 'EXCEPTIONS' in opts: cmd += " -fexceptions" else: cmd += " -fno-exceptions" if src.endswith(".mm"): # Work around Apple compiler bug. cmd += " -U__EXCEPTIONS" target = GetTarget() if 'RTTI' not in opts and target != "darwin": # We always disable RTTI on Android for memory usage reasons. if optlevel >= 4 or target == "android": cmd += " -fno-rtti" if ('SSE2' in opts or not PkgSkip("SSE2")) and not arch.startswith("arm") and arch != 'aarch64': cmd += " -msse2" # Needed by both Python, Panda, Eigen, all of which break aliasing rules. cmd += " -fno-strict-aliasing" if optlevel >= 3: cmd += " -ffast-math -fno-stack-protector" if optlevel == 3: # Fast math is nice, but we'd like to see NaN in dev builds. cmd += " -fno-finite-math-only" # Make sure this is off to avoid GCC/Eigen bug (see GitHub #228) cmd += " -fno-unsafe-math-optimizations" if (optlevel==1): cmd += " -ggdb -D_DEBUG" if (optlevel==2): cmd += " -O1 -D_DEBUG" if (optlevel==3): cmd += " -O2" if (optlevel==4): cmd += " -O3 -DNDEBUG" # Enable more warnings. cmd += " -Wall -Wno-unused-function" if not src.endswith(".c"): cmd += " -Wno-reorder" # Ignore unused variables in NDEBUG builds, often used in asserts. if optlevel == 4: cmd += " -Wno-unused-variable" if src.endswith(".c"): cmd += ' ' + CFLAGS else: cmd += ' ' + CXXFLAGS cmd = cmd.rstrip() building = GetValueOption(opts, "BUILDING:") if (building): cmd += " -DBUILDING_" + building cmd += ' ' + BracketNameWithQuotes(src) oscmd(cmd) ######################################################################## ## ## CompileBison ## ######################################################################## def CompileBison(wobj, wsrc, opts): ifile = os.path.basename(wsrc) wdsth = GetOutputDir()+"/include/" + ifile[:-4] + ".h" wdstc = GetOutputDir()+"/tmp/" + ifile + ".cxx" pre = GetValueOption(opts, "BISONPREFIX_") bison = GetBison() if bison is None: # We don't have bison. See if there is a prebuilt file. base, ext = os.path.splitext(wsrc) if os.path.isfile(base + '.h.prebuilt') and \ os.path.isfile(base + '.cxx.prebuilt'): CopyFile(wdstc, base + '.cxx.prebuilt') CopyFile(wdsth, base + '.h.prebuilt') else: exit('Could not find bison!') else: oscmd(bison + ' -y -d -o'+GetOutputDir()+'/tmp/'+ifile+'.c -p '+pre+' '+wsrc) CopyFile(wdstc, GetOutputDir()+"/tmp/"+ifile+".c") CopyFile(wdsth, GetOutputDir()+"/tmp/"+ifile+".h") # Finally, compile the generated source file. CompileCxx(wobj, wdstc, opts + ["FLEX"]) ######################################################################## ## ## CompileFlex ## ######################################################################## def CompileFlex(wobj,wsrc,opts): ifile = os.path.basename(wsrc) wdst = GetOutputDir()+"/tmp/"+ifile+".cxx" pre = GetValueOption(opts, "BISONPREFIX_") dashi = opts.count("FLEXDASHI") flex = GetFlex() if flex is None: # We don't have flex. See if there is a prebuilt file. base, ext = os.path.splitext(wsrc) if os.path.isfile(base + '.cxx.prebuilt'): CopyFile(wdst, base + '.cxx.prebuilt') else: exit('Could not find flex!') else: if (dashi): oscmd(flex + " -i -P" + pre + " -o"+wdst+" "+wsrc) else: oscmd(flex + " -P" + pre + " -o"+wdst+" "+wsrc) # Finally, compile the generated source file. CompileCxx(wobj,wdst,opts) ######################################################################## ## ## CompileIgate ## ######################################################################## def CompileIgate(woutd,wsrc,opts): outbase = os.path.basename(woutd)[:-3] woutc = GetOutputDir()+"/tmp/"+outbase+"_igate.cxx" srcdir = GetValueOption(opts, "SRCDIR:") module = GetValueOption(opts, "IMOD:") library = GetValueOption(opts, "ILIB:") ipath = GetListOption(opts, "DIR:") if (PkgSkip("PYTHON")): WriteFile(woutc, "") WriteFile(woutd, "") ConditionalWriteFile(woutd, "") return if not CrossCompiling(): # If we're compiling for this platform, we can use the one we've built. cmd = os.path.join(GetOutputDir(), 'bin', 'interrogate') else: # Assume that interrogate is on the PATH somewhere. cmd = 'interrogate' if GetVerbose(): cmd += ' -v' cmd += ' -srcdir %s -I%s' % (srcdir, srcdir) cmd += ' -DCPPPARSER -D__STDC__=1 -D__cplusplus=201103L' if (COMPILER=="MSVC"): cmd += ' -DWIN32_VC -DWIN32 -D_WIN32' if GetTargetArch() == 'x64': cmd += ' -DWIN64_VC -DWIN64 -D_WIN64 -D_M_X64 -D_M_AMD64' else: cmd += ' -D_M_IX86' # NOTE: this 1600 value is the version number for VC2010. cmd += ' -D_MSC_VER=1600 -D"__declspec(param)=" -D__cdecl -D_near -D_far -D__near -D__far -D__stdcall' if (COMPILER=="GCC"): cmd += ' -D__attribute__\(x\)=' target_arch = GetTargetArch() if target_arch in ("x86_64", "amd64"): cmd += ' -D_LP64' elif target_arch == 'aarch64': cmd += ' -D_LP64 -D__LP64__ -D__aarch64__' else: cmd += ' -D__i386__' target = GetTarget() if target == 'darwin': cmd += ' -D__APPLE__' elif target == 'android': cmd += ' -D__ANDROID__' optlevel = GetOptimizeOption(opts) if (optlevel==1): cmd += ' -D_DEBUG' if (optlevel==2): cmd += ' -D_DEBUG' if (optlevel==3): pass if (optlevel==4): cmd += ' -DNDEBUG' cmd += ' -oc ' + woutc + ' -od ' + woutd cmd += ' -fnames -string -refcount -assert -python-native' cmd += ' -S' + GetOutputDir() + '/include/parser-inc' # Add -I, -S and -D flags for x in ipath: cmd += ' -I' + BracketNameWithQuotes(x) for (opt,dir) in INCDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += ' -S' + BracketNameWithQuotes(dir) for (opt,var,val) in DEFSYMBOLS: if (opt=="ALWAYS") or (opt in opts): cmd += ' -D' + var + '=' + val #building = GetValueOption(opts, "BUILDING:") #if (building): cmd += " -DBUILDING_"+building cmd += ' -module ' + module + ' -library ' + library for x in wsrc: if (x.startswith("/")): cmd += ' ' + BracketNameWithQuotes(x) else: cmd += ' ' + BracketNameWithQuotes(os.path.basename(x)) oscmd(cmd) ######################################################################## ## ## CompileImod ## ######################################################################## def CompileImod(wobj, wsrc, opts): module = GetValueOption(opts, "IMOD:") library = GetValueOption(opts, "ILIB:") if (COMPILER=="MSVC"): woutc = wobj[:-4]+".cxx" if (COMPILER=="GCC"): woutc = wobj[:-2]+".cxx" if (PkgSkip("PYTHON")): WriteFile(woutc, "") CompileCxx(wobj, woutc, opts) return if not CrossCompiling(): # If we're compiling for this platform, we can use the one we've built. cmd = os.path.join(GetOutputDir(), 'bin', 'interrogate_module') else: # Assume that interrogate_module is on the PATH somewhere. cmd = 'interrogate_module' cmd += ' -oc ' + woutc + ' -module ' + module + ' -library ' + library + ' -python-native' importmod = GetValueOption(opts, "IMPORT:") if importmod: cmd += ' -import ' + importmod for x in wsrc: cmd += ' ' + BracketNameWithQuotes(x) oscmd(cmd) CompileCxx(wobj,woutc,opts) return ######################################################################## ## ## CompileLib ## ######################################################################## def CompileLib(lib, obj, opts): if (COMPILER=="MSVC"): if not BOOUSEINTELCOMPILER: #Use MSVC Linker cmd = 'link /lib /nologo' if GetOptimizeOption(opts) == 4: cmd += " /LTCG" if HasTargetArch(): cmd += " /MACHINE:" + GetTargetArch().upper() cmd += ' /OUT:' + BracketNameWithQuotes(lib) for x in obj: if not x.endswith('.lib'): cmd += ' ' + BracketNameWithQuotes(x) oscmd(cmd) else: # Choose Intel linker; from Jean-Claude cmd = 'xilink /verbose:lib /lib ' if HasTargetArch(): cmd += " /MACHINE:" + GetTargetArch().upper() cmd += ' /OUT:' + BracketNameWithQuotes(lib) for x in obj: cmd += ' ' + BracketNameWithQuotes(x) cmd += ' /LIBPATH:"C:\Program Files (x86)\Intel\Composer XE 2011 SP1\ipp\lib\ia32"' cmd += ' /LIBPATH:"C:\Program Files (x86)\Intel\Composer XE 2011 SP1\TBB\Lib\ia32\vc10"' cmd += ' /LIBPATH:"C:\Program Files (x86)\Intel\Composer XE 2011 SP1\compiler\lib\ia32"' oscmd(cmd) if (COMPILER=="GCC"): if GetTarget() == 'darwin': cmd = 'libtool -static -o ' + BracketNameWithQuotes(lib) else: cmd = GetAR() + ' cru ' + BracketNameWithQuotes(lib) for x in obj: if GetLinkAllStatic() and x.endswith('.a'): continue cmd += ' ' + BracketNameWithQuotes(x) oscmd(cmd) oscmd(GetRanlib() + ' ' + BracketNameWithQuotes(lib)) ######################################################################## ## ## CompileLink ## ######################################################################## def CompileLink(dll, obj, opts): if (COMPILER=="MSVC"): if not BOOUSEINTELCOMPILER: cmd = "link /nologo " if HasTargetArch(): cmd += " /MACHINE:" + GetTargetArch().upper() if ("MFC" not in opts): cmd += " /NOD:MFC90.LIB /NOD:MFC80.LIB /NOD:LIBCMT" cmd += " /NOD:LIBCI.LIB /DEBUG" cmd += " /nod:libc /nod:libcmtd /nod:atlthunk /nod:atls /nod:atlsd" if (GetOrigExt(dll) != ".exe"): cmd += " /DLL" optlevel = GetOptimizeOption(opts) if (optlevel==1): cmd += " /MAP /MAPINFO:EXPORTS /NOD:MSVCRT.LIB /NOD:MSVCPRT.LIB /NOD:MSVCIRT.LIB" if (optlevel==2): cmd += " /MAP:NUL /NOD:MSVCRT.LIB /NOD:MSVCPRT.LIB /NOD:MSVCIRT.LIB" if (optlevel==3): cmd += " /MAP:NUL /NOD:MSVCRTD.LIB /NOD:MSVCPRTD.LIB /NOD:MSVCIRTD.LIB" if (optlevel==4): cmd += " /MAP:NUL /LTCG /NOD:MSVCRTD.LIB /NOD:MSVCPRTD.LIB /NOD:MSVCIRTD.LIB" if ("MFC" in opts): if (optlevel<=2): cmd += " /NOD:MSVCRTD.LIB mfcs100d.lib MSVCRTD.lib" else: cmd += " /NOD:MSVCRT.LIB mfcs100.lib MSVCRT.lib" cmd += " /FIXED:NO /OPT:REF /STACK:4194304 /INCREMENTAL:NO " cmd += ' /OUT:' + BracketNameWithQuotes(dll) if not PkgSkip("PYTHON"): # If we're building without Python, don't pick it up implicitly. if "PYTHON" not in opts: pythonv = SDK["PYTHONVERSION"].replace('.', '') if optlevel <= 2: cmd += ' /NOD:{}d.lib'.format(pythonv) else: cmd += ' /NOD:{}.lib'.format(pythonv) # Yes, we know we are importing "locally defined symbols". for x in obj: if x.endswith('libp3pystub.lib'): cmd += ' /ignore:4049,4217' break # Set the subsystem. Specify that we want to target Windows XP. subsystem = GetValueOption(opts, "SUBSYSTEM:") or "CONSOLE" cmd += " /SUBSYSTEM:" + subsystem if GetTargetArch() == 'x64': cmd += ",5.02" else: cmd += ",5.01" if dll.endswith(".dll") or dll.endswith(".pyd"): cmd += ' /IMPLIB:' + GetOutputDir() + '/lib/' + os.path.splitext(os.path.basename(dll))[0] + ".lib" for (opt, dir) in LIBDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += ' /LIBPATH:' + BracketNameWithQuotes(dir) for x in obj: if x.endswith(".dll") or x.endswith(".pyd"): cmd += ' ' + GetOutputDir() + '/lib/' + os.path.splitext(os.path.basename(x))[0] + ".lib" elif x.endswith(".lib"): dname = os.path.splitext(os.path.basename(x))[0] + ".dll" if (GetOrigExt(x) != ".ilb" and os.path.exists(GetOutputDir()+"/bin/" + dname)): exit("Error: in makepanda, specify "+dname+", not "+x) cmd += ' ' + BracketNameWithQuotes(x) elif x.endswith(".def"): cmd += ' /DEF:' + BracketNameWithQuotes(x) elif x.endswith(".dat"): pass else: cmd += ' ' + BracketNameWithQuotes(x) if (GetOrigExt(dll)==".exe" and "NOICON" not in opts): cmd += " " + GetOutputDir() + "/tmp/pandaIcon.res" for (opt, name) in LIBNAMES: if (opt=="ALWAYS") or (opt in opts): cmd += " " + BracketNameWithQuotes(name) oscmd(cmd) else: cmd = "xilink" if GetVerbose(): cmd += " /verbose:lib" if HasTargetArch(): cmd += " /MACHINE:" + GetTargetArch().upper() if ("MFC" not in opts): cmd += " /NOD:MFC90.LIB /NOD:MFC80.LIB /NOD:LIBCMT" cmd += " /NOD:LIBCI.LIB /DEBUG" cmd += " /nod:libc /nod:libcmtd /nod:atlthunk /nod:atls" cmd += ' /LIBPATH:"C:\Program Files (x86)\Intel\Composer XE 2011 SP1\ipp\lib\ia32"' cmd += ' /LIBPATH:"C:\Program Files (x86)\Intel\Composer XE 2011 SP1\TBB\Lib\ia32\vc10"' cmd += ' /LIBPATH:"C:\Program Files (x86)\Intel\Composer XE 2011 SP1\compiler\lib\ia32"' if (GetOrigExt(dll) != ".exe"): cmd += " /DLL" optlevel = GetOptimizeOption(opts) if (optlevel==1): cmd += " /MAP /MAPINFO:EXPORTS /NOD:MSVCRT.LIB /NOD:MSVCPRT.LIB /NOD:MSVCIRT.LIB" if (optlevel==2): cmd += " /MAP:NUL /NOD:MSVCRT.LIB /NOD:MSVCPRT.LIB /NOD:MSVCIRT.LIB" if (optlevel==3): cmd += " /MAP:NUL /NOD:MSVCRTD.LIB /NOD:MSVCPRTD.LIB /NOD:MSVCIRTD.LIB" if (optlevel==4): cmd += " /MAP:NUL /LTCG /NOD:MSVCRTD.LIB /NOD:MSVCPRTD.LIB /NOD:MSVCIRTD.LIB" if ("MFC" in opts): if (optlevel<=2): cmd += " /NOD:MSVCRTD.LIB mfcs100d.lib MSVCRTD.lib" else: cmd += " /NOD:MSVCRT.LIB mfcs100.lib MSVCRT.lib" cmd += " /FIXED:NO /OPT:REF /STACK:4194304 /INCREMENTAL:NO " cmd += ' /OUT:' + BracketNameWithQuotes(dll) subsystem = GetValueOption(opts, "SUBSYSTEM:") if subsystem: cmd += " /SUBSYSTEM:" + subsystem if dll.endswith(".dll"): cmd += ' /IMPLIB:' + GetOutputDir() + '/lib/' + os.path.splitext(os.path.basename(dll))[0] + ".lib" for (opt, dir) in LIBDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += ' /LIBPATH:' + BracketNameWithQuotes(dir) for x in obj: if x.endswith(".dll") or x.endswith(".pyd"): cmd += ' ' + GetOutputDir() + '/lib/' + os.path.splitext(os.path.basename(x))[0] + ".lib" elif x.endswith(".lib"): dname = os.path.splitext(dll)[0]+".dll" if (GetOrigExt(x) != ".ilb" and os.path.exists(GetOutputDir()+"/bin/" + os.path.splitext(os.path.basename(x))[0] + ".dll")): exit("Error: in makepanda, specify "+dname+", not "+x) cmd += ' ' + BracketNameWithQuotes(x) elif x.endswith(".def"): cmd += ' /DEF:' + BracketNameWithQuotes(x) elif x.endswith(".dat"): pass else: cmd += ' ' + BracketNameWithQuotes(x) if (GetOrigExt(dll)==".exe" and "NOICON" not in opts): cmd += " " + GetOutputDir() + "/tmp/pandaIcon.res" for (opt, name) in LIBNAMES: if (opt=="ALWAYS") or (opt in opts): cmd += " " + BracketNameWithQuotes(name) oscmd(cmd) if COMPILER == "GCC": cxx = GetCXX() if GetOrigExt(dll) == ".exe": cmd = cxx + ' -o ' + dll + ' -L' + GetOutputDir() + '/lib -L' + GetOutputDir() + '/tmp' if GetTarget() == "android": # Necessary to work around an issue with libandroid depending on vendor libraries cmd += ' -Wl,--allow-shlib-undefined' else: if (GetTarget() == "darwin"): cmd = cxx + ' -undefined dynamic_lookup' if ("BUNDLE" in opts or GetOrigExt(dll) == ".pyd"): cmd += ' -bundle ' else: install_name = '@loader_path/../lib/' + os.path.basename(dll) cmd += ' -dynamiclib -install_name ' + install_name cmd += ' -compatibility_version ' + MAJOR_VERSION + ' -current_version ' + VERSION cmd += ' -o ' + dll + ' -L' + GetOutputDir() + '/lib -L' + GetOutputDir() + '/tmp' else: cmd = cxx + ' -shared' # Always set soname on Android to avoid a linker warning when loading the library. if "MODULE" not in opts or GetTarget() == 'android': cmd += " -Wl,-soname=" + os.path.basename(dll) cmd += ' -o ' + dll + ' -L' + GetOutputDir() + '/lib -L' + GetOutputDir() + '/tmp' for x in obj: if GetOrigExt(x) != ".dat": cmd += ' ' + x if (GetOrigExt(dll) == ".exe" and GetTarget() == 'windows' and "NOICON" not in opts): cmd += " " + GetOutputDir() + "/tmp/pandaIcon.res" # Mac OS X specific flags. if GetTarget() == 'darwin': cmd += " -headerpad_max_install_names" if OSXTARGET is not None: cmd += " -isysroot " + SDK["MACOSX"] + " -Wl,-syslibroot," + SDK["MACOSX"] cmd += " -mmacosx-version-min=%d.%d" % (OSXTARGET) for arch in OSX_ARCHS: if 'NOARCH:' + arch.upper() not in opts: cmd += " -arch %s" % arch elif GetTarget() == 'android': arch = GetTargetArch() if "ANDROID_GCC_TOOLCHAIN" in SDK: cmd += ' -gcc-toolchain ' + SDK["ANDROID_GCC_TOOLCHAIN"].replace('\\', '/') cmd += " -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now" if arch == 'armv7a': cmd += ' -target armv7-none-linux-androideabi' cmd += " -march=armv7-a -Wl,--fix-cortex-a8" elif arch == 'arm': cmd += ' -target armv5te-none-linux-androideabi' elif arch == 'aarch64': cmd += ' -target aarch64-none-linux-android' elif arch == 'mips': cmd += ' -target mipsel-none-linux-android' cmd += ' -mips32' elif arch == 'mips64': cmd += ' -target mips64el-none-linux-android' elif arch == 'x86': cmd += ' -target i686-none-linux-android' elif arch == 'x86_64': cmd += ' -target x86_64-none-linux-android' cmd += ' -lc -lm' else: cmd += " -pthread" if "SYSROOT" in SDK: cmd += " --sysroot=%s -no-canonical-prefixes" % (SDK["SYSROOT"]) if LDFLAGS != "": cmd += " " + LDFLAGS # Don't link libraries with Python, except on Android. if "PYTHON" in opts and GetOrigExt(dll) != ".exe" and not RTDIST and GetTarget() != 'android': opts = opts[:] opts.remove("PYTHON") for (opt, dir) in LIBDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += ' -L' + BracketNameWithQuotes(dir) for (opt, dir) in FRAMEWORKDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += ' -F' + BracketNameWithQuotes(dir) for (opt, name) in LIBNAMES: if (opt=="ALWAYS") or (opt in opts): cmd += ' ' + BracketNameWithQuotes(name) if GetTarget() != 'freebsd': cmd += " -ldl" oscmd(cmd) if GetOptimizeOption(opts) == 4 and GetTarget() in ('linux', 'android'): oscmd(GetStrip() + " --strip-unneeded " + BracketNameWithQuotes(dll)) os.system("chmod +x " + BracketNameWithQuotes(dll)) if dll.endswith("." + MAJOR_VERSION + ".dylib"): newdll = dll[:-6-len(MAJOR_VERSION)] + "dylib" if os.path.isfile(newdll): os.remove(newdll) oscmd("ln -s " + BracketNameWithQuotes(os.path.basename(dll)) + " " + BracketNameWithQuotes(newdll)) elif dll.endswith("." + MAJOR_VERSION): newdll = dll[:-len(MAJOR_VERSION)-1] if os.path.isfile(newdll): os.remove(newdll) oscmd("ln -s " + BracketNameWithQuotes(os.path.basename(dll)) + " " + BracketNameWithQuotes(newdll)) ########################################################################################## # # CompileEgg # ########################################################################################## def CompileEgg(eggfile, src, opts): pz = False if eggfile.endswith(".pz"): pz = True eggfile = eggfile[:-3] # Determine the location of the pzip and flt2egg tools. if CrossCompiling(): # We may not be able to use our generated versions of these tools, # so we'll expect them to already be present in the PATH. pzip = 'pzip' flt2egg = 'flt2egg' else: # If we're compiling for this machine, we can use the binaries we've built. pzip = os.path.join(GetOutputDir(), 'bin', 'pzip') flt2egg = os.path.join(GetOutputDir(), 'bin', 'flt2egg') if not os.path.isfile(pzip): pzip = 'pzip' if not os.path.isfile(flt2egg): flt2egg = 'flt2egg' if src.endswith(".egg"): CopyFile(eggfile, src) elif src.endswith(".flt"): oscmd(flt2egg + ' -ps keep -o ' + BracketNameWithQuotes(eggfile) + ' ' + BracketNameWithQuotes(src)) if pz: oscmd(pzip + ' ' + BracketNameWithQuotes(eggfile)) ########################################################################################## # # CompileRes, CompileRsrc # ########################################################################################## def CompileRes(target, src, opts): """Compiles a Windows .rc file into a .res file.""" ipath = GetListOption(opts, "DIR:") if (COMPILER == "MSVC"): cmd = "rc" cmd += " /Fo" + BracketNameWithQuotes(target) for x in ipath: cmd += " /I" + x for (opt,dir) in INCDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += " /I" + BracketNameWithQuotes(dir) for (opt,var,val) in DEFSYMBOLS: if (opt=="ALWAYS") or (opt in opts): cmd += " /D" + var + "=" + val cmd += " " + BracketNameWithQuotes(src) else: cmd = "windres" for x in ipath: cmd += " -I" + x for (opt,dir) in INCDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += " -I" + BracketNameWithQuotes(dir) for (opt,var,val) in DEFSYMBOLS: if (opt=="ALWAYS") or (opt in opts): cmd += " -D" + var + "=" + val cmd += " -i " + BracketNameWithQuotes(src) cmd += " -o " + BracketNameWithQuotes(target) oscmd(cmd) def CompileRsrc(target, src, opts): """Compiles a Mac OS .r file into an .rsrc file.""" ipath = GetListOption(opts, "DIR:") if os.path.isfile("/usr/bin/Rez"): cmd = "Rez -useDF" else: cmd = "/Developer/Tools/Rez -useDF" cmd += " -o " + BracketNameWithQuotes(target) for x in ipath: cmd += " -i " + x for (opt,dir) in INCDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += " -i " + BracketNameWithQuotes(dir) for (opt,var,val) in DEFSYMBOLS: if (opt=="ALWAYS") or (opt in opts): if (val == ""): cmd += " -d " + var else: cmd += " -d " + var + " = " + val cmd += " " + BracketNameWithQuotes(src) oscmd(cmd) ########################################################################################## # # CompileJava (Android only) # ########################################################################################## def CompileJava(target, src, opts): """Compiles a .java file into a .class file.""" cmd = "ecj " optlevel = GetOptimizeOption(opts) if optlevel >= 4: cmd += "-debug:none " cmd += "-cp " + GetOutputDir() + "/classes " cmd += "-d " + GetOutputDir() + "/classes " cmd += BracketNameWithQuotes(src) oscmd(cmd) ########################################################################################## # # FreezePy # ########################################################################################## def FreezePy(target, inputs, opts): assert len(inputs) > 0 cmdstr = BracketNameWithQuotes(SDK["PYTHONEXEC"].replace('\\', '/')) + " " if sys.version_info >= (2, 6): cmdstr += "-B " cmdstr += os.path.join(GetOutputDir(), "direct", "showutil", "pfreeze.py") if 'FREEZE_STARTUP' in opts: cmdstr += " -s" if GetOrigExt(target) == '.exe': src = inputs.pop(0) else: src = "" for i in inputs: i = os.path.splitext(i)[0] i = i.replace('/', '.') if i.startswith('direct.src'): i = i.replace('.src.', '.') cmdstr += " -i " + i cmdstr += " -o " + target + " " + src if ("LINK_PYTHON_STATIC" in opts): os.environ["LINK_PYTHON_STATIC"] = "1" oscmd(cmdstr) if ("LINK_PYTHON_STATIC" in os.environ): del os.environ["LINK_PYTHON_STATIC"] if (not os.path.exists(target)): exit("FREEZER_ERROR") ########################################################################################## # # Package # ########################################################################################## def Package(target, inputs, opts): assert len(inputs) == 1 # Invoke the ppackage script. command = BracketNameWithQuotes(SDK["PYTHONEXEC"]) + " " if GetOptimizeOption(opts) >= 4: command += "-OO " if sys.version_info >= (2, 6): command += "-B " command += "direct/src/p3d/ppackage.py" if not RTDIST: # Don't compile Python sources, because we might not running in the same # Python version as the selected host. command += " -N" if GetTarget() == "darwin": if SDK.get("MACOSX"): command += " -R \"%s\"" % SDK["MACOSX"] for arch in OSX_ARCHS: if arch == "x86_64": arch = "amd64" command += " -P osx_%s" % arch command += " -i \"" + GetOutputDir() + "/stage\"" if (P3DSUFFIX): command += ' -a "' + P3DSUFFIX + '"' command += " " + inputs[0] if GetOrigExt(target) == '.p3d': # Build a specific .p3d file. basename = os.path.basename(os.path.splitext(target)[0]) command += " " + basename oscmd(command) if GetTarget() == 'windows': # Make an .exe that calls this .p3d. objfile = FindLocation('p3dWrapper_' + basename + '.obj', []) CompileCxx(objfile, 'direct/src/p3d/p3dWrapper.c', []) exefile = FindLocation(basename + '.exe', []) CompileLink(exefile, [objfile], ['ADVAPI']) # Move it to the bin directory. os.rename(GetOutputDir() + '/stage/' + basename + P3DSUFFIX + '.p3d', target) if sys.platform != 'win32': oscmd('chmod +x ' + BracketNameWithQuotes(target)) else: # This is presumably a package or set of packages. oscmd(command) ########################################################################################## # # CompileBundle # ########################################################################################## def CompileBundle(target, inputs, opts): assert GetTarget() == "darwin", 'bundles can only be made for Mac OS X' plist = None resources = [] objects = [] for i in inputs: if (i.endswith(".plist")): if (plist != None): exit("Only one plist file can be used when creating a bundle!") plist = i elif (i.endswith(".rsrc") or i.endswith(".icns")): resources.append(i) elif (GetOrigExt(i) == ".obj" or GetOrigExt(i) in SUFFIX_LIB or GetOrigExt(i) in SUFFIX_DLL): objects.append(i) else: exit("Don't know how to bundle file %s" % i) # Now link the object files to form the bundle. if (plist == None): exit("One plist file must be used when creating a bundle!") bundleName = plistlib.readPlist(plist)["CFBundleExecutable"] oscmd("rm -rf %s" % target) oscmd("mkdir -p %s/Contents/MacOS/" % target) oscmd("mkdir -p %s/Contents/Resources/" % target) if target.endswith(".app"): SetOrigExt("%s/Contents/MacOS/%s" % (target, bundleName), ".exe") else: SetOrigExt("%s/Contents/MacOS/%s" % (target, bundleName), ".dll") CompileLink("%s/Contents/MacOS/%s" % (target, bundleName), objects, opts + ["BUNDLE"]) oscmd("cp %s %s/Contents/Info.plist" % (plist, target)) for r in resources: oscmd("cp %s %s/Contents/Resources/" % (r, target)) ########################################################################################## # # CompileMIDL # ########################################################################################## def CompileMIDL(target, src, opts): ipath = GetListOption(opts, "DIR:") if (COMPILER=="MSVC"): cmd = "midl" cmd += " /out" + BracketNameWithQuotes(os.path.dirname(target)) for x in ipath: cmd += " /I" + x for (opt,dir) in INCDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += " /I" + BracketNameWithQuotes(dir) for (opt,var,val) in DEFSYMBOLS: if (opt=="ALWAYS") or (opt in opts): cmd += " /D" + var + "=" + val cmd += " " + BracketNameWithQuotes(src) oscmd(cmd) ########################################################################################## # # CompileAnything # ########################################################################################## def CompileAnything(target, inputs, opts, progress = None): if (opts.count("DEPENDENCYONLY")): return if (len(inputs)==0): exit("No input files for target "+target) infile = inputs[0] origsuffix = GetOrigExt(target) if (len(inputs) == 1 and origsuffix == GetOrigExt(infile)): # It must be a simple copy operation. ProgressOutput(progress, "Copying file", target) CopyFile(target, infile) if (origsuffix==".exe" and GetHost() != "windows"): os.system("chmod +x \"%s\"" % target) return elif (infile.endswith(".py")): if origsuffix == ".obj": source = os.path.splitext(target)[0] + ".c" SetOrigExt(source, ".c") ProgressOutput(progress, "Building frozen source", source) FreezePy(source, inputs, opts) ProgressOutput(progress, "Building C++ object", target) return CompileCxx(target, source, opts) if origsuffix == ".exe": ProgressOutput(progress, "Building frozen executable", target) else: ProgressOutput(progress, "Building frozen library", target) return FreezePy(target, inputs, opts) elif (infile.endswith(".idl")): ProgressOutput(progress, "Compiling MIDL file", infile) return CompileMIDL(target, infile, opts) elif (infile.endswith(".pdef")): if origsuffix == '.p3d': ProgressOutput(progress, "Building package", target) else: ProgressOutput(progress, "Building package from pdef file", infile) return Package(target, inputs, opts) elif origsuffix in SUFFIX_LIB: ProgressOutput(progress, "Linking static library", target) return CompileLib(target, inputs, opts) elif origsuffix in SUFFIX_DLL or (origsuffix==".plugin" and GetTarget() != "darwin"): if (origsuffix==".exe"): ProgressOutput(progress, "Linking executable", target) else: ProgressOutput(progress, "Linking dynamic library", target) # Add version number to the dynamic library, on unix if origsuffix == ".dll" and "MODULE" not in opts and not RTDIST: tplatform = GetTarget() if tplatform == "darwin": # On Mac, libraries are named like libpanda.1.2.dylib if target.lower().endswith(".dylib"): target = target[:-5] + MAJOR_VERSION + ".dylib" SetOrigExt(target, origsuffix) elif tplatform != "windows" and tplatform != "android": # On Linux, libraries are named like libpanda.so.1.2 target += "." + MAJOR_VERSION SetOrigExt(target, origsuffix) return CompileLink(target, inputs, opts) elif (origsuffix==".in"): ProgressOutput(progress, "Building Interrogate database", target) return CompileIgate(target, inputs, opts) elif (origsuffix==".plugin" and GetTarget() == "darwin"): ProgressOutput(progress, "Building plugin bundle", target) return CompileBundle(target, inputs, opts) elif (origsuffix==".app"): ProgressOutput(progress, "Building application bundle", target) return CompileBundle(target, inputs, opts) elif (origsuffix==".pz"): ProgressOutput(progress, "Compressing", target) return CompileEgg(target, infile, opts) elif (origsuffix==".egg"): ProgressOutput(progress, "Converting", target) return CompileEgg(target, infile, opts) elif (origsuffix==".res"): ProgressOutput(progress, "Building resource object", target) return CompileRes(target, infile, opts) elif (origsuffix==".rsrc"): ProgressOutput(progress, "Building resource object", target) return CompileRsrc(target, infile, opts) elif (origsuffix==".class"): ProgressOutput(progress, "Building Java class", target) return CompileJava(target, infile, opts) elif (origsuffix==".obj"): if (infile.endswith(".cxx")): ProgressOutput(progress, "Building C++ object", target) return CompileCxx(target, infile, opts) elif (infile.endswith(".c")): ProgressOutput(progress, "Building C object", target) return CompileCxx(target, infile, opts) elif (infile.endswith(".mm")): ProgressOutput(progress, "Building Objective-C++ object", target) return CompileCxx(target, infile, opts) elif (infile.endswith(".yxx")): ProgressOutput(progress, "Building Bison object", target) return CompileBison(target, infile, opts) elif (infile.endswith(".lxx")): ProgressOutput(progress, "Building Flex object", target) return CompileFlex(target, infile, opts) elif (infile.endswith(".in")): ProgressOutput(progress, "Building Interrogate object", target) return CompileImod(target, inputs, opts) elif (infile.endswith(".rc")): ProgressOutput(progress, "Building resource object", target) return CompileRes(target, infile, opts) elif (infile.endswith(".r")): ProgressOutput(progress, "Building resource object", target) return CompileRsrc(target, infile, opts) exit("Don't know how to compile: %s from %s" % (target, inputs)) ########################################################################################## # # Generate dtool_config.h, prc_parameters.h, and dtool_have_xxx.dat # ########################################################################################## DTOOL_CONFIG=[ #_Variable_________________________Windows___________________Unix__________ ("HAVE_PYTHON", '1', '1'), ("USE_DEBUG_PYTHON", 'UNDEF', 'UNDEF'), ("PYTHON_FRAMEWORK", 'UNDEF', 'UNDEF'), ("COMPILE_IN_DEFAULT_FONT", '1', '1'), ("STDFLOAT_DOUBLE", 'UNDEF', 'UNDEF'), ("HAVE_MAYA", '1', '1'), ("HAVE_SOFTIMAGE", 'UNDEF', 'UNDEF'), ("REPORT_OPENSSL_ERRORS", '1', '1'), ("USE_PANDAFILESTREAM", '1', '1'), ("USE_DELETED_CHAIN", '1', '1'), ("HAVE_GLX", 'UNDEF', '1'), ("HAVE_WGL", '1', 'UNDEF'), ("HAVE_DX9", 'UNDEF', 'UNDEF'), ("HAVE_THREADS", '1', '1'), ("SIMPLE_THREADS", 'UNDEF', 'UNDEF'), ("OS_SIMPLE_THREADS", '1', '1'), ("DEBUG_THREADS", 'UNDEF', 'UNDEF'), ("HAVE_POSIX_THREADS", 'UNDEF', '1'), ("MUTEX_SPINLOCK", 'UNDEF', 'UNDEF'), ("HAVE_AUDIO", '1', '1'), ("NOTIFY_DEBUG", 'UNDEF', 'UNDEF'), ("DO_PSTATS", 'UNDEF', 'UNDEF'), ("DO_DCAST", 'UNDEF', 'UNDEF'), ("DO_COLLISION_RECORDING", 'UNDEF', 'UNDEF'), ("SUPPORT_IMMEDIATE_MODE", 'UNDEF', 'UNDEF'), ("SUPPORT_FIXED_FUNCTION", '1', '1'), ("DO_MEMORY_USAGE", 'UNDEF', 'UNDEF'), ("DO_PIPELINING", '1', '1'), ("DEFAULT_PATHSEP", '";"', '":"'), ("WORDS_BIGENDIAN", 'UNDEF', 'UNDEF'), ("PHAVE_LOCKF", '1', '1'), ("SIMPLE_STRUCT_POINTERS", '1', 'UNDEF'), ("HAVE_DINKUM", 'UNDEF', 'UNDEF'), ("HAVE_STL_HASH", 'UNDEF', 'UNDEF'), ("GETTIMEOFDAY_ONE_PARAM", 'UNDEF', 'UNDEF'), ("HAVE_GETOPT", 'UNDEF', '1'), ("HAVE_GETOPT_LONG_ONLY", 'UNDEF', '1'), ("PHAVE_GETOPT_H", 'UNDEF', '1'), ("PHAVE_LINUX_INPUT_H", 'UNDEF', '1'), ("IOCTL_TERMINAL_WIDTH", 'UNDEF', '1'), ("HAVE_IOS_TYPEDEFS", '1', '1'), ("HAVE_IOS_BINARY", '1', '1'), ("STATIC_INIT_GETENV", '1', 'UNDEF'), ("HAVE_PROC_SELF_EXE", 'UNDEF', '1'), ("HAVE_PROC_SELF_MAPS", 'UNDEF', '1'), ("HAVE_PROC_SELF_ENVIRON", 'UNDEF', '1'), ("HAVE_PROC_SELF_CMDLINE", 'UNDEF', '1'), ("HAVE_PROC_CURPROC_FILE", 'UNDEF', 'UNDEF'), ("HAVE_PROC_CURPROC_MAP", 'UNDEF', 'UNDEF'), ("HAVE_PROC_SELF_CMDLINE", 'UNDEF', 'UNDEF'), ("HAVE_GLOBAL_ARGV", '1', 'UNDEF'), ("PROTOTYPE_GLOBAL_ARGV", 'UNDEF', 'UNDEF'), ("GLOBAL_ARGV", '__argv', 'UNDEF'), ("GLOBAL_ARGC", '__argc', 'UNDEF'), ("PHAVE_IO_H", '1', 'UNDEF'), ("PHAVE_IOSTREAM", '1', '1'), ("PHAVE_STRING_H", 'UNDEF', '1'), ("PHAVE_LIMITS_H", 'UNDEF', '1'), ("PHAVE_STDLIB_H", 'UNDEF', '1'), ("PHAVE_MALLOC_H", '1', '1'), ("PHAVE_SYS_MALLOC_H", 'UNDEF', 'UNDEF'), ("PHAVE_ALLOCA_H", 'UNDEF', '1'), ("PHAVE_LOCALE_H", 'UNDEF', '1'), ("PHAVE_SSTREAM", '1', '1'), ("PHAVE_NEW", '1', '1'), ("PHAVE_SYS_TYPES_H", '1', '1'), ("PHAVE_SYS_TIME_H", 'UNDEF', '1'), ("PHAVE_UNISTD_H", 'UNDEF', '1'), ("PHAVE_UTIME_H", 'UNDEF', '1'), ("PHAVE_GLOB_H", 'UNDEF', '1'), ("PHAVE_DIRENT_H", 'UNDEF', '1'), ("PHAVE_UCONTEXT_H", 'UNDEF', '1'), ("PHAVE_STDINT_H", '1', '1'), ("HAVE_RTTI", '1', '1'), ("HAVE_X11", 'UNDEF', '1'), ("IS_LINUX", 'UNDEF', '1'), ("IS_OSX", 'UNDEF', 'UNDEF'), ("IS_FREEBSD", 'UNDEF', 'UNDEF'), ("HAVE_EIGEN", 'UNDEF', 'UNDEF'), ("LINMATH_ALIGN", '1', '1'), ("HAVE_ZLIB", 'UNDEF', 'UNDEF'), ("HAVE_PNG", 'UNDEF', 'UNDEF'), ("HAVE_JPEG", 'UNDEF', 'UNDEF'), ("HAVE_VIDEO4LINUX", 'UNDEF', '1'), ("HAVE_TIFF", 'UNDEF', 'UNDEF'), ("HAVE_OPENEXR", 'UNDEF', 'UNDEF'), ("HAVE_SGI_RGB", '1', '1'), ("HAVE_TGA", '1', '1'), ("HAVE_IMG", '1', '1'), ("HAVE_SOFTIMAGE_PIC", '1', '1'), ("HAVE_BMP", '1', '1'), ("HAVE_PNM", '1', '1'), ("HAVE_STB_IMAGE", '1', '1'), ("HAVE_VORBIS", 'UNDEF', 'UNDEF'), ("HAVE_OPUS", 'UNDEF', 'UNDEF'), ("HAVE_FREETYPE", 'UNDEF', 'UNDEF'), ("HAVE_FFTW", 'UNDEF', 'UNDEF'), ("HAVE_OPENSSL", 'UNDEF', 'UNDEF'), ("HAVE_NET", 'UNDEF', 'UNDEF'), ("WANT_NATIVE_NET", '1', '1'), ("SIMULATE_NETWORK_DELAY", 'UNDEF', 'UNDEF'), ("HAVE_CG", 'UNDEF', 'UNDEF'), ("HAVE_CGGL", 'UNDEF', 'UNDEF'), ("HAVE_CGDX9", 'UNDEF', 'UNDEF'), ("HAVE_ARTOOLKIT", 'UNDEF', 'UNDEF'), ("HAVE_DIRECTCAM", 'UNDEF', 'UNDEF'), ("HAVE_SQUISH", 'UNDEF', 'UNDEF'), ("HAVE_CARBON", 'UNDEF', 'UNDEF'), ("HAVE_COCOA", 'UNDEF', 'UNDEF'), ("HAVE_OPENAL_FRAMEWORK", 'UNDEF', 'UNDEF'), ("HAVE_ROCKET_PYTHON", '1', '1'), ("HAVE_ROCKET_DEBUGGER", 'UNDEF', 'UNDEF'), ("USE_TAU", 'UNDEF', 'UNDEF'), ("PRC_SAVE_DESCRIPTIONS", '1', '1'), # ("_SECURE_SCL", '0', 'UNDEF'), # ("_SECURE_SCL_THROWS", '0', 'UNDEF'), ("HAVE_P3D_PLUGIN", 'UNDEF', 'UNDEF'), ] PRC_PARAMETERS=[ ("DEFAULT_PRC_DIR", '"<auto>etc"', '"<auto>etc"'), ("PRC_DIR_ENVVARS", '"PANDA_PRC_DIR"', '"PANDA_PRC_DIR"'), ("PRC_PATH_ENVVARS", '"PANDA_PRC_PATH"', '"PANDA_PRC_PATH"'), ("PRC_PATH2_ENVVARS", '""', '""'), ("PRC_PATTERNS", '"*.prc"', '"*.prc"'), ("PRC_ENCRYPTED_PATTERNS", '"*.prc.pe"', '"*.prc.pe"'), ("PRC_ENCRYPTION_KEY", '""', '""'), ("PRC_EXECUTABLE_PATTERNS", '""', '""'), ("PRC_EXECUTABLE_ARGS_ENVVAR", '"PANDA_PRC_XARGS"', '"PANDA_PRC_XARGS"'), ("PRC_PUBLIC_KEYS_FILENAME", '""', '""'), ("PRC_RESPECT_TRUST_LEVEL", 'UNDEF', 'UNDEF'), ("PRC_DCONFIG_TRUST_LEVEL", '0', '0'), ("PRC_INC_TRUST_LEVEL", '0', '0'), ] def WriteConfigSettings(): dtool_config={} prc_parameters={} speedtree_parameters={} plugin_config={} if (GetTarget() == 'windows'): for key,win,unix in DTOOL_CONFIG: dtool_config[key] = win for key,win,unix in PRC_PARAMETERS: prc_parameters[key] = win else: for key,win,unix in DTOOL_CONFIG: dtool_config[key] = unix for key,win,unix in PRC_PARAMETERS: prc_parameters[key] = unix for x in PkgListGet(): if ("HAVE_"+x in dtool_config): if (PkgSkip(x)==0): dtool_config["HAVE_"+x] = '1' else: dtool_config["HAVE_"+x] = 'UNDEF' dtool_config["HAVE_NET"] = '1' if (PkgSkip("NVIDIACG")==0): dtool_config["HAVE_CG"] = '1' dtool_config["HAVE_CGGL"] = '1' dtool_config["HAVE_CGDX9"] = '1' if GetTarget() not in ("linux", "android"): dtool_config["HAVE_PROC_SELF_EXE"] = 'UNDEF' dtool_config["HAVE_PROC_SELF_MAPS"] = 'UNDEF' dtool_config["HAVE_PROC_SELF_CMDLINE"] = 'UNDEF' dtool_config["HAVE_PROC_SELF_ENVIRON"] = 'UNDEF' if (GetTarget() == "darwin"): dtool_config["PYTHON_FRAMEWORK"] = 'Python' dtool_config["PHAVE_MALLOC_H"] = 'UNDEF' dtool_config["PHAVE_SYS_MALLOC_H"] = '1' dtool_config["HAVE_OPENAL_FRAMEWORK"] = '1' dtool_config["HAVE_X11"] = 'UNDEF' # We might have X11, but we don't need it. dtool_config["HAVE_GLX"] = 'UNDEF' dtool_config["IS_LINUX"] = 'UNDEF' dtool_config["HAVE_VIDEO4LINUX"] = 'UNDEF' dtool_config["PHAVE_LINUX_INPUT_H"] = 'UNDEF' dtool_config["IS_OSX"] = '1' # 10.4 had a broken ucontext implementation if int(platform.mac_ver()[0][3]) <= 4: dtool_config["PHAVE_UCONTEXT_H"] = 'UNDEF' if (GetTarget() == "freebsd"): dtool_config["IS_LINUX"] = 'UNDEF' dtool_config["HAVE_VIDEO4LINUX"] = 'UNDEF' dtool_config["IS_FREEBSD"] = '1' dtool_config["PHAVE_ALLOCA_H"] = 'UNDEF' dtool_config["PHAVE_MALLOC_H"] = 'UNDEF' dtool_config["PHAVE_LINUX_INPUT_H"] = 'UNDEF' dtool_config["HAVE_PROC_CURPROC_FILE"] = '1' dtool_config["HAVE_PROC_CURPROC_MAP"] = '1' dtool_config["HAVE_PROC_CURPROC_CMDLINE"] = '1' if (GetTarget() == "android"): # Android does have RTTI, but we disable it anyway. dtool_config["HAVE_RTTI"] = 'UNDEF' dtool_config["PHAVE_GLOB_H"] = 'UNDEF' dtool_config["PHAVE_LOCKF"] = 'UNDEF' dtool_config["HAVE_VIDEO4LINUX"] = 'UNDEF' if (GetOptimize() <= 2 and GetTarget() == "windows"): dtool_config["USE_DEBUG_PYTHON"] = '1' # This should probably be more sophisticated, such as based # on whether the libRocket Python modules are available. if (PkgSkip("PYTHON") != 0): dtool_config["HAVE_ROCKET_PYTHON"] = 'UNDEF' if (GetOptimize() <= 3): dtool_config["HAVE_ROCKET_DEBUGGER"] = '1' if (GetOptimize() <= 3): if (dtool_config["HAVE_NET"] != 'UNDEF'): dtool_config["DO_PSTATS"] = '1' if (GetOptimize() <= 3): dtool_config["DO_DCAST"] = '1' if (GetOptimize() <= 3): dtool_config["DO_COLLISION_RECORDING"] = '1' if (GetOptimize() <= 3): dtool_config["DO_MEMORY_USAGE"] = '1' if (GetOptimize() <= 3): dtool_config["NOTIFY_DEBUG"] = '1' if (GetOptimize() >= 4): dtool_config["PRC_SAVE_DESCRIPTIONS"] = 'UNDEF' if (GetOptimize() >= 4): # Disable RTTI on release builds. dtool_config["HAVE_RTTI"] = 'UNDEF' # Now that we have OS_SIMPLE_THREADS, we can support # SIMPLE_THREADS on exotic architectures like win64, so we no # longer need to disable it for this platform. ## if GetTarget() == 'windows' and GetTargetArch() == 'x64': ## dtool_config["SIMPLE_THREADS"] = 'UNDEF' if (RTDIST or RUNTIME): prc_parameters["DEFAULT_PRC_DIR"] = '""' if HOST_URL: plugin_config["PANDA_PACKAGE_HOST_URL"] = HOST_URL #plugin_config["P3D_PLUGIN_LOG_DIRECTORY"] = "" plugin_config["P3D_PLUGIN_LOG_BASENAME1"] = "" plugin_config["P3D_PLUGIN_LOG_BASENAME2"] = "" plugin_config["P3D_PLUGIN_LOG_BASENAME3"] = "" plugin_config["P3D_PLUGIN_P3D_PLUGIN"] = "" plugin_config["P3D_PLUGIN_P3DPYTHON"] = "" plugin_config["P3D_COREAPI_VERSION_STR"] = COREAPI_VERSION plugin_config["P3D_PLUGIN_VERSION_STR"] = PLUGIN_VERSION if PkgSkip("GTK2") == 0: plugin_config["HAVE_GTK"] = '1' if (RUNTIME): dtool_config["HAVE_P3D_PLUGIN"] = '1' # Whether it's present on the system doesn't matter here, # as the runtime itself doesn't include or link with X11. if (RUNTIME and GetTarget() == 'linux'): dtool_config["HAVE_X11"] = '1' if ("GENERIC_DXERR_LIBRARY" in SDK): dtool_config["USE_GENERIC_DXERR_LIBRARY"] = "1" else: dtool_config["USE_GENERIC_DXERR_LIBRARY"] = "UNDEF" if (PkgSkip("SPEEDTREE")==0): speedtree_parameters["SPEEDTREE_OPENGL"] = "UNDEF" speedtree_parameters["SPEEDTREE_DIRECTX9"] = "UNDEF" if SDK["SPEEDTREEAPI"] == "OpenGL": speedtree_parameters["SPEEDTREE_OPENGL"] = "1" elif SDK["SPEEDTREEAPI"] == "DirectX9": speedtree_parameters["SPEEDTREE_DIRECTX9"] = "1" speedtree_parameters["SPEEDTREE_BIN_DIR"] = (SDK["SPEEDTREE"] + "/Bin") conf = "/* prc_parameters.h. Generated automatically by makepanda.py */\n" for key in sorted(prc_parameters.keys()): if ((key == "DEFAULT_PRC_DIR") or (key[:4]=="PRC_")): val = OverrideValue(key, prc_parameters[key]) if (val == 'UNDEF'): conf = conf + "#undef " + key + "\n" else: conf = conf + "#define " + key + " " + val + "\n" ConditionalWriteFile(GetOutputDir() + '/include/prc_parameters.h', conf) conf = "/* dtool_config.h. Generated automatically by makepanda.py */\n" for key in sorted(dtool_config.keys()): val = OverrideValue(key, dtool_config[key]) if (val == 'UNDEF'): conf = conf + "#undef " + key + "\n" else: conf = conf + "#define " + key + " " + val + "\n" ConditionalWriteFile(GetOutputDir() + '/include/dtool_config.h', conf) if (RTDIST or RUNTIME): conf = "/* p3d_plugin_config.h. Generated automatically by makepanda.py */\n" for key in sorted(plugin_config.keys()): val = plugin_config[key] if (val == 'UNDEF'): conf = conf + "#undef " + key + "\n" else: conf = conf + "#define " + key + " \"" + val.replace("\\", "\\\\") + "\"\n" ConditionalWriteFile(GetOutputDir() + '/include/p3d_plugin_config.h', conf) if (PkgSkip("SPEEDTREE")==0): conf = "/* speedtree_parameters.h. Generated automatically by makepanda.py */\n" for key in sorted(speedtree_parameters.keys()): val = OverrideValue(key, speedtree_parameters[key]) if (val == 'UNDEF'): conf = conf + "#undef " + key + "\n" else: conf = conf + "#define " + key + " \"" + val.replace("\\", "\\\\") + "\"\n" ConditionalWriteFile(GetOutputDir() + '/include/speedtree_parameters.h', conf) for x in PkgListGet(): if (PkgSkip(x)): ConditionalWriteFile(GetOutputDir() + '/tmp/dtool_have_'+x.lower()+'.dat', "0\n") else: ConditionalWriteFile(GetOutputDir() + '/tmp/dtool_have_'+x.lower()+'.dat', "1\n") # This is useful for tools like makepackage that need to know things about # the build parameters. ConditionalWriteFile(GetOutputDir() + '/tmp/optimize.dat', str(GetOptimize())) WriteConfigSettings() WarnConflictingFiles() if SystemLibraryExists("dtoolbase"): Warn("Found conflicting Panda3D libraries from other ppremake build!") if SystemLibraryExists("p3dtoolconfig"): Warn("Found conflicting Panda3D libraries from other makepanda build!") ########################################################################################## # # Generate pandaVersion.h, pythonversion, null.cxx, etc. # ########################################################################################## PANDAVERSION_H=""" #define PANDA_MAJOR_VERSION $VERSION1 #define PANDA_MINOR_VERSION $VERSION2 #define PANDA_SEQUENCE_VERSION $VERSION3 #define PANDA_VERSION $NVERSION #define PANDA_NUMERIC_VERSION $NVERSION #define PANDA_VERSION_STR "$VERSION1.$VERSION2.$VERSION3" #define PANDA_ABI_VERSION_STR "$VERSION1.$VERSION2" #define PANDA_DISTRIBUTOR "$DISTRIBUTOR" #define PANDA_PACKAGE_VERSION_STR "$RTDIST_VERSION" #define PANDA_PACKAGE_HOST_URL "$HOST_URL" """ PANDAVERSION_H_RUNTIME=""" #define PANDA_MAJOR_VERSION 0 #define PANDA_MINOR_VERSION 0 #define PANDA_SEQUENCE_VERSION 0 #define PANDA_VERSION_STR "0.0.0" #define PANDA_ABI_VERSION_STR "0.0" #define P3D_PLUGIN_MAJOR_VERSION $VERSION1 #define P3D_PLUGIN_MINOR_VERSION $VERSION2 #define P3D_PLUGIN_SEQUENCE_VERSION $VERSION3 #define P3D_PLUGIN_VERSION_STR "$VERSION1.$VERSION2.$VERSION3" #define P3D_COREAPI_VERSION_STR "$COREAPI_VERSION" #define PANDA_DISTRIBUTOR "$DISTRIBUTOR" #define PANDA_PACKAGE_VERSION_STR "" #define PANDA_PACKAGE_HOST_URL "$HOST_URL" """ CHECKPANDAVERSION_CXX=""" # include "dtoolbase.h" EXPCL_DTOOL_DTOOLBASE int panda_version_$VERSION1_$VERSION2 = 0; """ CHECKPANDAVERSION_H=""" # ifndef CHECKPANDAVERSION_H # define CHECKPANDAVERSION_H # include "dtoolbase.h" extern EXPCL_DTOOL_DTOOLBASE int panda_version_$VERSION1_$VERSION2; // Hack to forcibly depend on the check template<typename T> class CheckPandaVersion { public: int check_version() { return panda_version_$VERSION1_$VERSION2; } }; template class CheckPandaVersion<void>; # endif """ P3DACTIVEX_RC="""#include "resource.h" #define APSTUDIO_READONLY_SYMBOLS #include "afxres.h" #undef APSTUDIO_READONLY_SYMBOLS #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #endif #ifdef APSTUDIO_INVOKED 1 TEXTINCLUDE BEGIN "resource.h\\0" END 2 TEXTINCLUDE BEGIN "#include ""afxres.h""\\r\\n" "\\0" END 3 TEXTINCLUDE BEGIN "1 TYPELIB ""P3DActiveX.tlb""\\r\\n" "\\0" END #endif %s IDB_P3DACTIVEX BITMAP "P3DActiveXCtrl.bmp" IDD_PROPPAGE_P3DACTIVEX DIALOG 0, 0, 250, 62 STYLE DS_SETFONT | WS_CHILD FONT 8, "MS Sans Serif" BEGIN LTEXT "TODO: Place controls to manipulate properties of P3DActiveX Control on this dialog.", IDC_STATIC,7,25,229,16 END #ifdef APSTUDIO_INVOKED GUIDELINES DESIGNINFO BEGIN IDD_PROPPAGE_P3DACTIVEX, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 243 TOPMARGIN, 7 BOTTOMMARGIN, 55 END END #endif STRINGTABLE BEGIN IDS_P3DACTIVEX "P3DActiveX Control" IDS_P3DACTIVEX_PPG "P3DActiveX Property Page" END STRINGTABLE BEGIN IDS_P3DACTIVEX_PPG_CAPTION "General" END #endif #ifndef APSTUDIO_INVOKED 1 TYPELIB "P3DActiveX.tlb" #endif""" def CreatePandaVersionFiles(): version1=int(VERSION.split(".")[0]) version2=int(VERSION.split(".")[1]) version3=int(VERSION.split(".")[2]) nversion=version1*1000000+version2*1000+version3 if (DISTRIBUTOR != "cmu"): # Subtract 1 if we are not an official version. nversion -= 1 if (RUNTIME): pandaversion_h = PANDAVERSION_H_RUNTIME else: pandaversion_h = PANDAVERSION_H pandaversion_h = pandaversion_h.replace("$VERSION1",str(version1)) pandaversion_h = pandaversion_h.replace("$VERSION2",str(version2)) pandaversion_h = pandaversion_h.replace("$VERSION3",str(version3)) pandaversion_h = pandaversion_h.replace("$NVERSION",str(nversion)) pandaversion_h = pandaversion_h.replace("$DISTRIBUTOR",DISTRIBUTOR) pandaversion_h = pandaversion_h.replace("$RTDIST_VERSION",RTDIST_VERSION) pandaversion_h = pandaversion_h.replace("$COREAPI_VERSION",COREAPI_VERSION) pandaversion_h = pandaversion_h.replace("$HOST_URL",(HOST_URL or "")) if (DISTRIBUTOR == "cmu"): pandaversion_h += "\n#define PANDA_OFFICIAL_VERSION\n" else: pandaversion_h += "\n#undef PANDA_OFFICIAL_VERSION\n" if GIT_COMMIT: pandaversion_h += "\n#define PANDA_GIT_COMMIT_STR \"%s\"\n" % (GIT_COMMIT) if not RUNTIME: checkpandaversion_cxx = CHECKPANDAVERSION_CXX.replace("$VERSION1",str(version1)) checkpandaversion_cxx = checkpandaversion_cxx.replace("$VERSION2",str(version2)) checkpandaversion_cxx = checkpandaversion_cxx.replace("$VERSION3",str(version3)) checkpandaversion_cxx = checkpandaversion_cxx.replace("$NVERSION",str(nversion)) checkpandaversion_h = CHECKPANDAVERSION_H.replace("$VERSION1",str(version1)) checkpandaversion_h = checkpandaversion_h.replace("$VERSION2",str(version2)) checkpandaversion_h = checkpandaversion_h.replace("$VERSION3",str(version3)) checkpandaversion_h = checkpandaversion_h.replace("$NVERSION",str(nversion)) ConditionalWriteFile(GetOutputDir()+'/include/pandaVersion.h', pandaversion_h) if RUNTIME: ConditionalWriteFile(GetOutputDir()+'/include/checkPandaVersion.cxx', '') ConditionalWriteFile(GetOutputDir()+'/include/checkPandaVersion.h', '') else: ConditionalWriteFile(GetOutputDir()+'/include/checkPandaVersion.cxx', checkpandaversion_cxx) ConditionalWriteFile(GetOutputDir()+'/include/checkPandaVersion.h', checkpandaversion_h) ConditionalWriteFile(GetOutputDir()+"/tmp/null.cxx","") if RUNTIME: p3dactivex_rc = {"name" : "Panda3D Game Engine Plug-in", "version" : VERSION, "description" : "Runs 3-D games and interactive applets", "filename" : "p3dactivex.ocx", "mimetype" : "application/x-panda3d", "extension" : "p3d", "filedesc" : "Panda3D applet"} ConditionalWriteFile(GetOutputDir()+"/include/P3DActiveX.rc", P3DACTIVEX_RC % GenerateResourceFile(**p3dactivex_rc)) CreatePandaVersionFiles() ########################################################################################## # # Copy the "direct" tree # ########################################################################################## if (PkgSkip("DIRECT")==0): CopyPythonTree(GetOutputDir() + '/direct', 'direct/src', threads=THREADCOUNT) ConditionalWriteFile(GetOutputDir() + '/direct/__init__.py', "") # This file used to be copied, but would nowadays cause conflicts. # Let's get it out of the way in case someone hasn't cleaned their build since. if os.path.isfile(GetOutputDir() + '/bin/panda3d.py'): os.remove(GetOutputDir() + '/bin/panda3d.py') if os.path.isfile(GetOutputDir() + '/lib/panda3d.py'): os.remove(GetOutputDir() + '/lib/panda3d.py') # This directory doesn't exist at all any more. if os.path.isdir(os.path.join(GetOutputDir(), 'direct', 'ffi')): shutil.rmtree(os.path.join(GetOutputDir(), 'direct', 'ffi')) # These files used to exist; remove them to avoid conflicts. del_files = ['core.py', 'core.pyc', 'core.pyo', '_core.pyd', '_core.so', 'direct.py', 'direct.pyc', 'direct.pyo', '_direct.pyd', '_direct.so', 'dtoolconfig.pyd', 'dtoolconfig.so'] for basename in del_files: path = os.path.join(GetOutputDir(), 'panda3d', basename) if os.path.isfile(path): print("Removing %s" % (path)) os.remove(path) # Write an appropriate panda3d/__init__.py p3d_init = """"Python bindings for the Panda3D libraries" __version__ = '%s' """ % (WHLVERSION) if GetTarget() == 'windows': p3d_init += """ import os bindir = os.path.join(os.path.dirname(__file__), '..', 'bin') if os.path.isdir(bindir): if not os.environ.get('PATH'): os.environ['PATH'] = bindir else: os.environ['PATH'] = bindir + os.pathsep + os.environ['PATH'] del os, bindir """ if not PkgSkip("PYTHON"): ConditionalWriteFile(GetOutputDir() + '/panda3d/__init__.py', p3d_init) # Also add this file, for backward compatibility. ConditionalWriteFile(GetOutputDir() + '/panda3d/dtoolconfig.py', """ if __debug__: print("Warning: panda3d.dtoolconfig is deprecated, use panda3d.interrogatedb instead.") from .interrogatedb import * """) # PandaModules is now deprecated; generate a shim for backward compatibility. for fn in glob.glob(GetOutputDir() + '/pandac/*.py') + glob.glob(GetOutputDir() + '/pandac/*.py[co]'): if os.path.basename(fn) not in ('PandaModules.py', '__init__.py'): os.remove(fn) panda_modules = ['core'] if not PkgSkip("PANDAPHYSICS"): panda_modules.append('physics') if not PkgSkip('PANDAFX'): panda_modules.append('fx') if not PkgSkip("DIRECT"): panda_modules.append('direct') if not PkgSkip("VISION"): panda_modules.append('vision') if not PkgSkip("SKEL"): panda_modules.append('skel') if not PkgSkip("EGG"): panda_modules.append('egg') if not PkgSkip("ODE"): panda_modules.append('ode') if not PkgSkip("VRPN"): panda_modules.append('vrpn') panda_modules_code = """ "This module is deprecated. Import from panda3d.core and other panda3d.* modules instead." if __debug__: print("Warning: pandac.PandaModules is deprecated, import from panda3d.core instead") """ for module in panda_modules: panda_modules_code += """ try: from panda3d.%s import * except ImportError as err: if "No module named %s" not in str(err): raise""" % (module, module) panda_modules_code += """ from direct.showbase import DConfig def get_config_showbase(): return DConfig def get_config_express(): return DConfig getConfigShowbase = get_config_showbase getConfigExpress = get_config_express """ exthelpers_code = """ "This module is deprecated. Import from direct.extensions_native.extension_native_helpers instead." from direct.extensions_native.extension_native_helpers import * """ if not PkgSkip("PYTHON"): ConditionalWriteFile(GetOutputDir() + '/pandac/PandaModules.py', panda_modules_code) ConditionalWriteFile(GetOutputDir() + '/pandac/extension_native_helpers.py', exthelpers_code) ConditionalWriteFile(GetOutputDir() + '/pandac/__init__.py', '') ########################################################################################## # # Generate the PRC files into the ETC directory. # ########################################################################################## confautoprc = ReadFile("makepanda/confauto.in") if (PkgSkip("SPEEDTREE")==0): # If SpeedTree is available, enable it in the config file confautoprc = confautoprc.replace('#st#', '') else: # otherwise, disable it. confautoprc = confautoprc.replace('#st#', '#') if PkgSkip("ASSIMP"): confautoprc = confautoprc.replace("load-file-type p3assimp", "#load-file-type p3assimp") if (os.path.isfile("makepanda/myconfig.in")): configprc = ReadFile("makepanda/myconfig.in") else: configprc = ReadFile("makepanda/config.in") if (GetTarget() == 'windows'): configprc = configprc.replace("$XDG_CACHE_HOME/panda3d", "$USER_APPDATA/Panda3D-%s" % MAJOR_VERSION) else: configprc = configprc.replace("aux-display pandadx9", "") if (GetTarget() == 'darwin'): configprc = configprc.replace("$XDG_CACHE_HOME/panda3d", "Library/Caches/Panda3D-%s" % MAJOR_VERSION) # OpenAL is not yet working well on OSX for us, so let's do this for now. configprc = configprc.replace("p3openal_audio", "p3fmod_audio") if GetTarget() == 'windows': # Convert to Windows newlines. ConditionalWriteFile(GetOutputDir()+"/etc/Config.prc", configprc, newline='\r\n') ConditionalWriteFile(GetOutputDir()+"/etc/Confauto.prc", confautoprc, newline='\r\n') else: ConditionalWriteFile(GetOutputDir()+"/etc/Config.prc", configprc) ConditionalWriteFile(GetOutputDir()+"/etc/Confauto.prc", confautoprc) ########################################################################################## # # Copy the precompiled binaries and DLLs into the build. # ########################################################################################## tp_dir = GetThirdpartyDir() if tp_dir is not None: dylibs = {} if GetTarget() == 'darwin': # Make a list of all the dylibs we ship, to figure out whether we should use # install_name_tool to correct the library reference to point to our copy. for lib in glob.glob(tp_dir + "/*/lib/*.dylib"): dylibs[os.path.basename(lib)] = os.path.basename(os.path.realpath(lib)) if not PkgSkip("PYTHON"): for lib in glob.glob(tp_dir + "/*/lib/" + SDK["PYTHONVERSION"] + "/*.dylib"): dylibs[os.path.basename(lib)] = os.path.basename(os.path.realpath(lib)) for pkg in PkgListGet(): if PkgSkip(pkg): continue tp_pkg = tp_dir + pkg.lower() if GetTarget() == 'windows': if os.path.exists(tp_pkg + "/bin"): CopyAllFiles(GetOutputDir() + "/bin/", tp_pkg + "/bin/") if (PkgSkip("PYTHON")==0 and os.path.exists(tp_pkg + "/bin/" + SDK["PYTHONVERSION"])): CopyAllFiles(GetOutputDir() + "/bin/", tp_pkg + "/bin/" + SDK["PYTHONVERSION"] + "/") elif GetTarget() == 'darwin': tp_libs = glob.glob(tp_pkg + "/lib/*.dylib") if not PkgSkip("PYTHON"): tp_libs += glob.glob(os.path.join(tp_pkg, "lib", SDK["PYTHONVERSION"], "*.dylib")) tp_libs += glob.glob(os.path.join(tp_pkg, "lib", SDK["PYTHONVERSION"], "*.so")) if pkg != 'PYTHON': tp_libs += glob.glob(os.path.join(tp_pkg, "lib", SDK["PYTHONVERSION"], "*.py")) for tp_lib in tp_libs: basename = os.path.basename(tp_lib) if basename.endswith('.dylib'): # It's a dynamic link library. Put it in the lib directory. target = GetOutputDir() + "/lib/" + basename dep_prefix = "@loader_path/../lib/" lib_id = dep_prefix + basename else: # It's a Python module, like _rocketcore.so. Copy it to the root, because # nowadays the 'lib' directory may no longer be on the PYTHONPATH. target = GetOutputDir() + "/" + basename dep_prefix = "@loader_path/lib/" lib_id = basename if not NeedsBuild([target], [tp_lib]): continue CopyFile(target, tp_lib) if os.path.islink(target) or target.endswith('.py'): continue # Correct the inter-library dependencies so that the build is relocatable. oscmd('install_name_tool -id %s %s' % (lib_id, target)) oscmd("otool -L %s | grep .dylib > %s/tmp/otool-libs.txt" % (target, GetOutputDir()), True) for line in open(GetOutputDir() + "/tmp/otool-libs.txt", "r"): line = line.strip() if not line or line.startswith(dep_prefix) or line.endswith(":"): continue libdep = line.split(" ", 1)[0] dep_basename = os.path.basename(libdep) if dep_basename in dylibs: dep_target = dylibs[dep_basename] oscmd("install_name_tool -change %s %s%s %s" % (libdep, dep_prefix, dep_target, target), True) JustBuilt([target], [tp_lib]) for fwx in glob.glob(tp_pkg + "/*.framework"): CopyTree(GetOutputDir() + "/Frameworks/" + os.path.basename(fwx), fwx) else: # Linux / FreeBSD case. for tp_lib in glob.glob(tp_pkg + "/lib/*.so*"): CopyFile(GetOutputDir() + "/lib/" + os.path.basename(tp_lib), tp_lib) if not PkgSkip("PYTHON"): for tp_lib in glob.glob(os.path.join(tp_pkg, "lib", SDK["PYTHONVERSION"], "*.so*")): base = os.path.basename(tp_lib) if base.startswith('lib'): CopyFile(GetOutputDir() + "/lib/" + base, tp_lib) else: # It's a Python module, like _rocketcore.so. CopyFile(GetOutputDir() + "/" + base, tp_lib) if GetTarget() == 'windows': if os.path.isdir(os.path.join(tp_dir, "extras", "bin")): CopyAllFiles(GetOutputDir() + "/bin/", tp_dir + "extras/bin/") if not PkgSkip("PYTHON") and not RTDIST: # We need to copy the Python DLL to the bin directory for now. pydll = "/" + SDK["PYTHONVERSION"].replace(".", "") if GetOptimize() <= 2: pydll += "_d.dll" else: pydll += ".dll" CopyFile(GetOutputDir() + "/bin" + pydll, SDK["PYTHON"] + pydll) for fn in glob.glob(SDK["PYTHON"] + "/vcruntime*.dll"): CopyFile(GetOutputDir() + "/bin/", fn) # Copy the whole Python directory. CopyTree(GetOutputDir() + "/python", SDK["PYTHON"]) # NB: Python does not always ship with the correct manifest/dll. # Figure out the correct one to ship, and grab it from WinSxS dir. manifest = GetOutputDir() + '/tmp/python.manifest' if os.path.isfile(manifest): os.unlink(manifest) oscmd('mt -inputresource:"%s\\python.exe";#1 -out:"%s" -nologo' % (SDK["PYTHON"], manifest), True) if os.path.isfile(manifest): import xml.etree.ElementTree as ET tree = ET.parse(manifest) idents = tree.findall('./{urn:schemas-microsoft-com:asm.v1}dependency/{urn:schemas-microsoft-com:asm.v1}dependentAssembly/{urn:schemas-microsoft-com:asm.v1}assemblyIdentity') else: idents = () for ident in idents: sxs_name = '_'.join([ ident.get('processorArchitecture'), ident.get('name').lower(), ident.get('publicKeyToken'), ident.get('version'), ]) # Find the manifest matching these parameters. pattern = os.path.join('C:' + os.sep, 'Windows', 'WinSxS', 'Manifests', sxs_name + '_*.manifest') manifests = glob.glob(pattern) if not manifests: Warn("Could not locate manifest %s. You may need to reinstall the Visual C++ Redistributable." % (pattern)) continue CopyFile(GetOutputDir() + "/python/" + ident.get('name') + ".manifest", manifests[0]) # Also copy the corresponding msvcr dll. pattern = os.path.join('C:' + os.sep, 'Windows', 'WinSxS', sxs_name + '_*', 'msvcr*.dll') for file in glob.glob(pattern): CopyFile(GetOutputDir() + "/python/", file) # Copy python.exe to ppython.exe. if not os.path.isfile(SDK["PYTHON"] + "/ppython.exe") and os.path.isfile(SDK["PYTHON"] + "/python.exe"): CopyFile(GetOutputDir() + "/python/ppython.exe", SDK["PYTHON"] + "/python.exe") if not os.path.isfile(SDK["PYTHON"] + "/ppythonw.exe") and os.path.isfile(SDK["PYTHON"] + "/pythonw.exe"): CopyFile(GetOutputDir() + "/python/ppythonw.exe", SDK["PYTHON"] + "/pythonw.exe") ConditionalWriteFile(GetOutputDir() + "/python/panda.pth", "..\n../bin\n") # Copy over the MSVC runtime. if GetTarget() == 'windows' and "VISUALSTUDIO" in SDK: vsver = "%s%s" % SDK["VISUALSTUDIO_VERSION"] vcver = "%s%s" % (SDK["MSVC_VERSION"][0], 0) # ignore minor version. crtname = "Microsoft.VC%s.CRT" % (vsver) if ("VCTOOLSVERSION" in SDK): dir = os.path.join(SDK["VISUALSTUDIO"], "VC", "Redist", "MSVC", SDK["VCTOOLSVERSION"], "onecore", GetTargetArch(), crtname) else: dir = os.path.join(SDK["VISUALSTUDIO"], "VC", "redist", GetTargetArch(), crtname) if os.path.isfile(os.path.join(dir, "msvcr" + vcver + ".dll")): CopyFile(GetOutputDir() + "/bin/", os.path.join(dir, "msvcr" + vcver + ".dll")) if os.path.isfile(os.path.join(dir, "msvcp" + vcver + ".dll")): CopyFile(GetOutputDir() + "/bin/", os.path.join(dir, "msvcp" + vcver + ".dll")) if os.path.isfile(os.path.join(dir, "vcruntime" + vcver + ".dll")): CopyFile(GetOutputDir() + "/bin/", os.path.join(dir, "vcruntime" + vcver + ".dll")) ######################################################################## ## ## Copy various stuff into the build. ## ######################################################################## if GetTarget() == 'windows': # Convert to Windows newlines so they can be opened by notepad. WriteFile(GetOutputDir() + "/LICENSE", ReadFile("doc/LICENSE"), newline='\r\n') WriteFile(GetOutputDir() + "/ReleaseNotes", ReadFile("doc/ReleaseNotes"), newline='\r\n') CopyFile(GetOutputDir() + "/pandaIcon.ico", "panda/src/configfiles/pandaIcon.ico") else: CopyFile(GetOutputDir()+"/", "doc/LICENSE") CopyFile(GetOutputDir()+"/", "doc/ReleaseNotes") if (PkgSkip("PANDATOOL")==0): CopyAllFiles(GetOutputDir()+"/plugins/", "pandatool/src/scripts/", ".mel") CopyAllFiles(GetOutputDir()+"/plugins/", "pandatool/src/scripts/", ".ms") if (PkgSkip("PYTHON")==0 and os.path.isdir(GetThirdpartyBase()+"/Pmw")): CopyTree(GetOutputDir()+'/Pmw', GetThirdpartyBase()+'/Pmw') ConditionalWriteFile(GetOutputDir()+'/include/ctl3d.h', '/* dummy file to make MAX happy */') # Since Eigen is included by all sorts of core headers, as a convenience # to C++ users on Win and Mac, we include it in the Panda include directory. if not PkgSkip("EIGEN") and GetTarget() in ("windows", "darwin") and GetThirdpartyDir(): CopyTree(GetOutputDir()+'/include/Eigen', GetThirdpartyDir()+'eigen/include/Eigen') ######################################################################## # # Copy header files to the built/include/parser-inc directory. # ######################################################################## CopyTree(GetOutputDir()+'/include/parser-inc','dtool/src/parser-inc') DeleteVCS(GetOutputDir()+'/include/parser-inc') ######################################################################## # # Transfer all header files to the built/include directory. # ######################################################################## CopyAllHeaders('dtool/src/dtoolbase') CopyAllHeaders('dtool/src/dtoolutil', skip=["pandaVersion.h", "checkPandaVersion.h"]) CopyFile(GetOutputDir()+'/include/','dtool/src/dtoolutil/vector_src.cxx') CopyAllHeaders('dtool/metalibs/dtool') CopyAllHeaders('dtool/src/cppparser') CopyAllHeaders('dtool/src/prc', skip=["prc_parameters.h"]) CopyAllHeaders('dtool/src/dconfig') CopyAllHeaders('dtool/src/interrogatedb') CopyAllHeaders('dtool/metalibs/dtoolconfig') CopyAllHeaders('dtool/src/pystub') CopyAllHeaders('dtool/src/interrogate') CopyAllHeaders('dtool/src/test_interrogate') CopyAllHeaders('panda/src/putil') CopyAllHeaders('panda/src/pandabase') CopyAllHeaders('panda/src/express') CopyAllHeaders('panda/src/downloader') CopyAllHeaders('panda/metalibs/pandaexpress') CopyAllHeaders('panda/src/pipeline') CopyAllHeaders('panda/src/linmath') CopyAllHeaders('panda/src/putil') CopyAllHeaders('dtool/src/prckeys') CopyAllHeaders('panda/src/audio') CopyAllHeaders('panda/src/event') CopyAllHeaders('panda/src/mathutil') CopyAllHeaders('panda/src/gsgbase') CopyAllHeaders('panda/src/pnmimage') CopyAllHeaders('panda/src/nativenet') CopyAllHeaders('panda/src/net') CopyAllHeaders('panda/src/pstatclient') CopyAllHeaders('panda/src/gobj') CopyAllHeaders('panda/src/movies') CopyAllHeaders('panda/src/pgraphnodes') CopyAllHeaders('panda/src/pgraph') CopyAllHeaders('panda/src/cull') CopyAllHeaders('panda/src/display') CopyAllHeaders('panda/src/chan') CopyAllHeaders('panda/src/char') CopyAllHeaders('panda/src/dgraph') CopyAllHeaders('panda/src/device') CopyAllHeaders('panda/src/pnmtext') CopyAllHeaders('panda/src/text') CopyAllHeaders('panda/src/grutil') if (PkgSkip("VISION")==0): CopyAllHeaders('panda/src/vision') if (PkgSkip("FFMPEG")==0): CopyAllHeaders('panda/src/ffmpeg') CopyAllHeaders('panda/src/tform') CopyAllHeaders('panda/src/collide') CopyAllHeaders('panda/src/parametrics') CopyAllHeaders('panda/src/pgui') CopyAllHeaders('panda/src/pnmimagetypes') CopyAllHeaders('panda/src/recorder') if (PkgSkip("ROCKET")==0): CopyAllHeaders('panda/src/rocket') if (PkgSkip("VRPN")==0): CopyAllHeaders('panda/src/vrpn') CopyAllHeaders('panda/src/wgldisplay') CopyAllHeaders('panda/src/ode') CopyAllHeaders('panda/metalibs/pandaode') if (PkgSkip("PANDAPHYSICS")==0): CopyAllHeaders('panda/src/physics') if (PkgSkip("PANDAPARTICLESYSTEM")==0): CopyAllHeaders('panda/src/particlesystem') CopyAllHeaders('panda/src/dxml') CopyAllHeaders('panda/metalibs/panda') CopyAllHeaders('panda/src/audiotraits') CopyAllHeaders('panda/src/audiotraits') CopyAllHeaders('panda/src/distort') CopyAllHeaders('panda/src/downloadertools') CopyAllHeaders('panda/src/windisplay') CopyAllHeaders('panda/src/dxgsg9') CopyAllHeaders('panda/metalibs/pandadx9') if not PkgSkip("EGG"): CopyAllHeaders('panda/src/egg') CopyAllHeaders('panda/src/egg2pg') CopyAllHeaders('panda/src/framework') CopyAllHeaders('panda/metalibs/pandafx') CopyAllHeaders('panda/src/glstuff') CopyAllHeaders('panda/src/glgsg') CopyAllHeaders('panda/src/glesgsg') CopyAllHeaders('panda/src/gles2gsg') if not PkgSkip("EGG"): CopyAllHeaders('panda/metalibs/pandaegg') if GetTarget() == 'windows': CopyAllHeaders('panda/src/wgldisplay') elif GetTarget() == 'darwin': CopyAllHeaders('panda/src/osxdisplay') CopyAllHeaders('panda/src/cocoadisplay') elif GetTarget() == 'android': CopyAllHeaders('panda/src/android') CopyAllHeaders('panda/src/androiddisplay') else: CopyAllHeaders('panda/src/x11display') CopyAllHeaders('panda/src/glxdisplay') CopyAllHeaders('panda/src/egldisplay') CopyAllHeaders('panda/metalibs/pandagl') CopyAllHeaders('panda/metalibs/pandagles') CopyAllHeaders('panda/metalibs/pandagles2') CopyAllHeaders('panda/metalibs/pandaphysics') CopyAllHeaders('panda/src/testbed') if (PkgSkip("PHYSX")==0): CopyAllHeaders('panda/src/physx') CopyAllHeaders('panda/metalibs/pandaphysx') if (PkgSkip("BULLET")==0): CopyAllHeaders('panda/src/bullet') CopyAllHeaders('panda/metalibs/pandabullet') if (PkgSkip("SPEEDTREE")==0): CopyAllHeaders('panda/src/speedtree') if (PkgSkip("DIRECT")==0): CopyAllHeaders('direct/src/directbase') CopyAllHeaders('direct/src/dcparser') CopyAllHeaders('direct/src/deadrec') CopyAllHeaders('direct/src/distributed') CopyAllHeaders('direct/src/interval') CopyAllHeaders('direct/src/showbase') CopyAllHeaders('direct/src/dcparse') if (RUNTIME or RTDIST): CopyAllHeaders('direct/src/plugin', skip=["p3d_plugin_config.h"]) if (RUNTIME): CopyAllHeaders('direct/src/plugin_npapi') CopyAllHeaders('direct/src/plugin_standalone') if (PkgSkip("PANDATOOL")==0): CopyAllHeaders('pandatool/src/pandatoolbase') CopyAllHeaders('pandatool/src/converter') CopyAllHeaders('pandatool/src/progbase') CopyAllHeaders('pandatool/src/eggbase') CopyAllHeaders('pandatool/src/bam') CopyAllHeaders('pandatool/src/cvscopy') CopyAllHeaders('pandatool/src/daeegg') CopyAllHeaders('pandatool/src/daeprogs') CopyAllHeaders('pandatool/src/dxf') CopyAllHeaders('pandatool/src/dxfegg') CopyAllHeaders('pandatool/src/dxfprogs') CopyAllHeaders('pandatool/src/palettizer') CopyAllHeaders('pandatool/src/egg-mkfont') CopyAllHeaders('pandatool/src/eggcharbase') CopyAllHeaders('pandatool/src/egg-optchar') CopyAllHeaders('pandatool/src/egg-palettize') CopyAllHeaders('pandatool/src/egg-qtess') CopyAllHeaders('pandatool/src/eggprogs') CopyAllHeaders('pandatool/src/flt') CopyAllHeaders('pandatool/src/fltegg') CopyAllHeaders('pandatool/src/fltprogs') CopyAllHeaders('pandatool/src/imagebase') CopyAllHeaders('pandatool/src/imageprogs') CopyAllHeaders('pandatool/src/pfmprogs') CopyAllHeaders('pandatool/src/lwo') CopyAllHeaders('pandatool/src/lwoegg') CopyAllHeaders('pandatool/src/lwoprogs') CopyAllHeaders('pandatool/src/maya') CopyAllHeaders('pandatool/src/mayaegg') CopyAllHeaders('pandatool/src/maxegg') CopyAllHeaders('pandatool/src/maxprogs') CopyAllHeaders('pandatool/src/objegg') CopyAllHeaders('pandatool/src/objprogs') CopyAllHeaders('pandatool/src/vrml') CopyAllHeaders('pandatool/src/vrmlegg') CopyAllHeaders('pandatool/src/xfile') CopyAllHeaders('pandatool/src/xfileegg') CopyAllHeaders('pandatool/src/ptloader') CopyAllHeaders('pandatool/src/miscprogs') CopyAllHeaders('pandatool/src/pstatserver') CopyAllHeaders('pandatool/src/text-stats') CopyAllHeaders('pandatool/src/vrmlprogs') CopyAllHeaders('pandatool/src/win-stats') CopyAllHeaders('pandatool/src/xfileprogs') if (PkgSkip("CONTRIB")==0): CopyAllHeaders('contrib/src/contribbase') CopyAllHeaders('contrib/src/ai') ######################################################################## # # These definitions are syntactic shorthand. They make it easy # to link with the usual libraries without listing them all. # ######################################################################## COMMON_DTOOL_LIBS=[ 'libp3dtool.dll', 'libp3dtoolconfig.dll', ] COMMON_PANDA_LIBS=[ 'libpanda.dll', 'libpandaexpress.dll' ] + COMMON_DTOOL_LIBS COMMON_EGG2X_LIBS=[ 'libp3eggbase.lib', 'libp3progbase.lib', 'libp3converter.lib', 'libp3pandatoolbase.lib', 'libpandaegg.dll', ] + COMMON_PANDA_LIBS ######################################################################## # # This section contains a list of all the files that need to be compiled. # ######################################################################## print("Generating dependencies...") sys.stdout.flush() # # Compile Panda icon resource file. # We do it first because we need it at # the time we compile an executable. # if GetTarget() == 'windows': OPTS=['DIR:panda/src/configfiles'] TargetAdd('pandaIcon.res', opts=OPTS, input='pandaIcon.rc') # # DIRECTORY: dtool/src/dtoolbase/ # OPTS=['DIR:dtool/src/dtoolbase', 'BUILDING:DTOOL'] TargetAdd('p3dtoolbase_composite1.obj', opts=OPTS, input='p3dtoolbase_composite1.cxx') TargetAdd('p3dtoolbase_composite2.obj', opts=OPTS, input='p3dtoolbase_composite2.cxx') TargetAdd('p3dtoolbase_lookup3.obj', opts=OPTS, input='lookup3.c') TargetAdd('p3dtoolbase_indent.obj', opts=OPTS, input='indent.cxx') # # DIRECTORY: dtool/src/dtoolutil/ # OPTS=['DIR:dtool/src/dtoolutil', 'BUILDING:DTOOL'] TargetAdd('p3dtoolutil_composite1.obj', opts=OPTS, input='p3dtoolutil_composite1.cxx') TargetAdd('p3dtoolutil_composite2.obj', opts=OPTS, input='p3dtoolutil_composite2.cxx') if GetTarget() == 'darwin': TargetAdd('p3dtoolutil_filename_assist.obj', opts=OPTS, input='filename_assist.mm') # # DIRECTORY: dtool/metalibs/dtool/ # OPTS=['DIR:dtool/metalibs/dtool', 'BUILDING:DTOOL'] TargetAdd('p3dtool_dtool.obj', opts=OPTS, input='dtool.cxx') TargetAdd('libp3dtool.dll', input='p3dtool_dtool.obj') TargetAdd('libp3dtool.dll', input='p3dtoolutil_composite1.obj') TargetAdd('libp3dtool.dll', input='p3dtoolutil_composite2.obj') if GetTarget() == 'darwin': TargetAdd('libp3dtool.dll', input='p3dtoolutil_filename_assist.obj') TargetAdd('libp3dtool.dll', input='p3dtoolbase_composite1.obj') TargetAdd('libp3dtool.dll', input='p3dtoolbase_composite2.obj') TargetAdd('libp3dtool.dll', input='p3dtoolbase_indent.obj') TargetAdd('libp3dtool.dll', input='p3dtoolbase_lookup3.obj') TargetAdd('libp3dtool.dll', opts=['ADVAPI','WINSHELL','WINKERNEL']) # # DIRECTORY: dtool/src/cppparser/ # if (not RUNTIME): OPTS=['DIR:dtool/src/cppparser', 'BISONPREFIX_cppyy'] CreateFile(GetOutputDir()+"/include/cppBison.h") TargetAdd('p3cppParser_cppBison.obj', opts=OPTS, input='cppBison.yxx') TargetAdd('cppBison.h', input='p3cppParser_cppBison.obj', opts=['DEPENDENCYONLY']) TargetAdd('p3cppParser_composite1.obj', opts=OPTS, input='p3cppParser_composite1.cxx') TargetAdd('p3cppParser_composite2.obj', opts=OPTS, input='p3cppParser_composite2.cxx') TargetAdd('libp3cppParser.ilb', input='p3cppParser_composite1.obj') TargetAdd('libp3cppParser.ilb', input='p3cppParser_composite2.obj') TargetAdd('libp3cppParser.ilb', input='p3cppParser_cppBison.obj') # # DIRECTORY: dtool/src/prc/ # OPTS=['DIR:dtool/src/prc', 'BUILDING:DTOOLCONFIG', 'OPENSSL'] TargetAdd('p3prc_composite1.obj', opts=OPTS, input='p3prc_composite1.cxx') TargetAdd('p3prc_composite2.obj', opts=OPTS, input='p3prc_composite2.cxx') # # DIRECTORY: dtool/metalibs/dtoolconfig/ # OPTS=['DIR:dtool/metalibs/dtoolconfig', 'BUILDING:DTOOLCONFIG'] TargetAdd('p3dtoolconfig_dtoolconfig.obj', opts=OPTS, input='dtoolconfig.cxx') TargetAdd('libp3dtoolconfig.dll', input='p3dtoolconfig_dtoolconfig.obj') TargetAdd('libp3dtoolconfig.dll', input='p3prc_composite1.obj') TargetAdd('libp3dtoolconfig.dll', input='p3prc_composite2.obj') TargetAdd('libp3dtoolconfig.dll', input='libp3dtool.dll') TargetAdd('libp3dtoolconfig.dll', opts=['ADVAPI', 'OPENSSL', 'WINGDI', 'WINUSER']) # # DIRECTORY: dtool/src/interrogatedb/ # OPTS=['DIR:dtool/src/interrogatedb', 'BUILDING:INTERROGATEDB'] TargetAdd('p3interrogatedb_composite1.obj', opts=OPTS, input='p3interrogatedb_composite1.cxx') TargetAdd('p3interrogatedb_composite2.obj', opts=OPTS, input='p3interrogatedb_composite2.cxx') TargetAdd('libp3interrogatedb.dll', input='p3interrogatedb_composite1.obj') TargetAdd('libp3interrogatedb.dll', input='p3interrogatedb_composite2.obj') TargetAdd('libp3interrogatedb.dll', input='libp3dtool.dll') TargetAdd('libp3interrogatedb.dll', input='libp3dtoolconfig.dll') # This used to be called dtoolconfig.pyd, but it just contains the interrogatedb # stuff, so it has been renamed appropriately. OPTS=['DIR:dtool/metalibs/dtoolconfig'] PyTargetAdd('interrogatedb_pydtool.obj', opts=OPTS, input="pydtool.cxx") PyTargetAdd('interrogatedb.pyd', input='interrogatedb_pydtool.obj') PyTargetAdd('interrogatedb.pyd', input='libp3dtool.dll') PyTargetAdd('interrogatedb.pyd', input='libp3dtoolconfig.dll') PyTargetAdd('interrogatedb.pyd', input='libp3interrogatedb.dll') # # DIRECTORY: dtool/src/pystub/ # if not RUNTIME and not RTDIST: OPTS=['DIR:dtool/src/pystub'] TargetAdd('p3pystub_pystub.obj', opts=OPTS, input='pystub.cxx') TargetAdd('libp3pystub.lib', input='p3pystub_pystub.obj') #TargetAdd('libp3pystub.lib', input='libp3dtool.dll') TargetAdd('libp3pystub.lib', opts=['ADVAPI']) # # DIRECTORY: dtool/src/interrogate/ # if (not RUNTIME): OPTS=['DIR:dtool/src/interrogate', 'DIR:dtool/src/cppparser', 'DIR:dtool/src/interrogatedb'] TargetAdd('interrogate_composite1.obj', opts=OPTS, input='interrogate_composite1.cxx') TargetAdd('interrogate_composite2.obj', opts=OPTS, input='interrogate_composite2.cxx') TargetAdd('interrogate.exe', input='interrogate_composite1.obj') TargetAdd('interrogate.exe', input='interrogate_composite2.obj') TargetAdd('interrogate.exe', input='libp3cppParser.ilb') TargetAdd('interrogate.exe', input=COMMON_DTOOL_LIBS) TargetAdd('interrogate.exe', input='libp3interrogatedb.dll') TargetAdd('interrogate.exe', opts=['ADVAPI', 'OPENSSL', 'WINSHELL', 'WINGDI', 'WINUSER']) preamble = WriteEmbeddedStringFile('interrogate_preamble_python_native', inputs=[ 'dtool/src/interrogatedb/py_panda.cxx', 'dtool/src/interrogatedb/py_compat.cxx', 'dtool/src/interrogatedb/py_wrappers.cxx', 'dtool/src/interrogatedb/dtool_super_base.cxx', ]) TargetAdd('interrogate_module_preamble_python_native.obj', opts=OPTS, input=preamble) TargetAdd('interrogate_module_interrogate_module.obj', opts=OPTS, input='interrogate_module.cxx') TargetAdd('interrogate_module.exe', input='interrogate_module_interrogate_module.obj') TargetAdd('interrogate_module.exe', input='interrogate_module_preamble_python_native.obj') TargetAdd('interrogate_module.exe', input='libp3cppParser.ilb') TargetAdd('interrogate_module.exe', input=COMMON_DTOOL_LIBS) TargetAdd('interrogate_module.exe', input='libp3interrogatedb.dll') TargetAdd('interrogate_module.exe', opts=['ADVAPI', 'OPENSSL', 'WINSHELL', 'WINGDI', 'WINUSER']) if (not RTDIST): TargetAdd('parse_file_parse_file.obj', opts=OPTS, input='parse_file.cxx') TargetAdd('parse_file.exe', input='parse_file_parse_file.obj') TargetAdd('parse_file.exe', input='libp3cppParser.ilb') TargetAdd('parse_file.exe', input=COMMON_DTOOL_LIBS) TargetAdd('parse_file.exe', input='libp3interrogatedb.dll') TargetAdd('parse_file.exe', opts=['ADVAPI', 'OPENSSL', 'WINSHELL', 'WINGDI', 'WINUSER']) # # DIRECTORY: dtool/src/prckeys/ # if (PkgSkip("OPENSSL")==0 and not RUNTIME and not RTDIST): OPTS=['DIR:dtool/src/prckeys', 'OPENSSL'] TargetAdd('make-prc-key_makePrcKey.obj', opts=OPTS, input='makePrcKey.cxx') TargetAdd('make-prc-key.exe', input='make-prc-key_makePrcKey.obj') TargetAdd('make-prc-key.exe', input=COMMON_DTOOL_LIBS) TargetAdd('make-prc-key.exe', opts=['ADVAPI', 'OPENSSL', 'WINSHELL', 'WINGDI', 'WINUSER']) # # DIRECTORY: dtool/src/test_interrogate/ # if (not RTDIST and not RUNTIME): OPTS=['DIR:dtool/src/test_interrogate'] TargetAdd('test_interrogate_test_interrogate.obj', opts=OPTS, input='test_interrogate.cxx') TargetAdd('test_interrogate.exe', input='test_interrogate_test_interrogate.obj') TargetAdd('test_interrogate.exe', input='libp3interrogatedb.dll') TargetAdd('test_interrogate.exe', input=COMMON_DTOOL_LIBS) TargetAdd('test_interrogate.exe', opts=['ADVAPI', 'OPENSSL', 'WINSHELL', 'WINGDI', 'WINUSER']) # # DIRECTORY: dtool/src/dtoolbase/ # OPTS=['DIR:dtool/src/dtoolbase'] IGATEFILES=GetDirectoryContents('dtool/src/dtoolbase', ["*_composite*.cxx"]) IGATEFILES += [ "typeHandle.h", "typeHandle_ext.h", "typeRegistry.h", "typedObject.h", "neverFreeMemory.h", ] TargetAdd('libp3dtoolbase.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3dtoolbase.in', opts=['IMOD:panda3d.core', 'ILIB:libp3dtoolbase', 'SRCDIR:dtool/src/dtoolbase']) PyTargetAdd('p3dtoolbase_typeHandle_ext.obj', opts=OPTS, input='typeHandle_ext.cxx') # # DIRECTORY: dtool/src/dtoolutil/ # OPTS=['DIR:dtool/src/dtoolutil'] IGATEFILES=GetDirectoryContents('dtool/src/dtoolutil', ["*_composite*.cxx"]) IGATEFILES += [ "config_dtoolutil.h", "pandaSystem.h", "dSearchPath.h", "executionEnvironment.h", "textEncoder.h", "textEncoder_ext.h", "filename.h", "filename_ext.h", "globPattern.h", "globPattern_ext.h", "pandaFileStream.h", "lineStream.h", ] TargetAdd('libp3dtoolutil.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3dtoolutil.in', opts=['IMOD:panda3d.core', 'ILIB:libp3dtoolutil', 'SRCDIR:dtool/src/dtoolutil']) PyTargetAdd('p3dtoolutil_ext_composite.obj', opts=OPTS, input='p3dtoolutil_ext_composite.cxx') # # DIRECTORY: dtool/src/prc/ # OPTS=['DIR:dtool/src/prc'] IGATEFILES=GetDirectoryContents('dtool/src/prc', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3prc.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3prc.in', opts=['IMOD:panda3d.core', 'ILIB:libp3prc', 'SRCDIR:dtool/src/prc']) PyTargetAdd('p3prc_ext_composite.obj', opts=OPTS, input='p3prc_ext_composite.cxx') # # DIRECTORY: panda/src/pandabase/ # OPTS=['DIR:panda/src/pandabase', 'BUILDING:PANDAEXPRESS'] TargetAdd('p3pandabase_pandabase.obj', opts=OPTS, input='pandabase.cxx') # # DIRECTORY: panda/src/express/ # OPTS=['DIR:panda/src/express', 'BUILDING:PANDAEXPRESS', 'OPENSSL', 'ZLIB'] TargetAdd('p3express_composite1.obj', opts=OPTS, input='p3express_composite1.cxx') TargetAdd('p3express_composite2.obj', opts=OPTS, input='p3express_composite2.cxx') OPTS=['DIR:panda/src/express', 'OPENSSL', 'ZLIB'] IGATEFILES=GetDirectoryContents('panda/src/express', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3express.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3express.in', opts=['IMOD:panda3d.core', 'ILIB:libp3express', 'SRCDIR:panda/src/express']) PyTargetAdd('p3express_ext_composite.obj', opts=OPTS, input='p3express_ext_composite.cxx') # # DIRECTORY: panda/src/downloader/ # OPTS=['DIR:panda/src/downloader', 'BUILDING:PANDAEXPRESS', 'OPENSSL', 'ZLIB'] TargetAdd('p3downloader_composite1.obj', opts=OPTS, input='p3downloader_composite1.cxx') TargetAdd('p3downloader_composite2.obj', opts=OPTS, input='p3downloader_composite2.cxx') OPTS=['DIR:panda/src/downloader', 'OPENSSL', 'ZLIB'] IGATEFILES=GetDirectoryContents('panda/src/downloader', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3downloader.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3downloader.in', opts=['IMOD:panda3d.core', 'ILIB:libp3downloader', 'SRCDIR:panda/src/downloader']) PyTargetAdd('p3downloader_stringStream_ext.obj', opts=OPTS, input='stringStream_ext.cxx') # # DIRECTORY: panda/metalibs/pandaexpress/ # OPTS=['DIR:panda/metalibs/pandaexpress', 'BUILDING:PANDAEXPRESS', 'ZLIB'] TargetAdd('pandaexpress_pandaexpress.obj', opts=OPTS, input='pandaexpress.cxx') TargetAdd('libpandaexpress.dll', input='pandaexpress_pandaexpress.obj') TargetAdd('libpandaexpress.dll', input='p3downloader_composite1.obj') TargetAdd('libpandaexpress.dll', input='p3downloader_composite2.obj') TargetAdd('libpandaexpress.dll', input='p3express_composite1.obj') TargetAdd('libpandaexpress.dll', input='p3express_composite2.obj') TargetAdd('libpandaexpress.dll', input='p3pandabase_pandabase.obj') TargetAdd('libpandaexpress.dll', input=COMMON_DTOOL_LIBS) TargetAdd('libpandaexpress.dll', opts=['ADVAPI', 'WINSOCK2', 'OPENSSL', 'ZLIB', 'WINGDI', 'WINUSER', 'ANDROID']) # # DIRECTORY: panda/src/pipeline/ # if (not RUNTIME): OPTS=['DIR:panda/src/pipeline', 'BUILDING:PANDA'] TargetAdd('p3pipeline_composite1.obj', opts=OPTS, input='p3pipeline_composite1.cxx') TargetAdd('p3pipeline_composite2.obj', opts=OPTS, input='p3pipeline_composite2.cxx') TargetAdd('p3pipeline_contextSwitch.obj', opts=OPTS, input='contextSwitch.c') OPTS=['DIR:panda/src/pipeline'] IGATEFILES=GetDirectoryContents('panda/src/pipeline', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3pipeline.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3pipeline.in', opts=['IMOD:panda3d.core', 'ILIB:libp3pipeline', 'SRCDIR:panda/src/pipeline']) PyTargetAdd('p3pipeline_pythonThread.obj', opts=OPTS, input='pythonThread.cxx') # # DIRECTORY: panda/src/linmath/ # if (not RUNTIME): OPTS=['DIR:panda/src/linmath', 'BUILDING:PANDA'] TargetAdd('p3linmath_composite1.obj', opts=OPTS, input='p3linmath_composite1.cxx') TargetAdd('p3linmath_composite2.obj', opts=OPTS, input='p3linmath_composite2.cxx') OPTS=['DIR:panda/src/linmath'] IGATEFILES=GetDirectoryContents('panda/src/linmath', ["*.h", "*_composite*.cxx"]) for ifile in IGATEFILES[:]: if "_src." in ifile: IGATEFILES.remove(ifile) IGATEFILES.remove('cast_to_double.h') IGATEFILES.remove('lmat_ops.h') IGATEFILES.remove('cast_to_float.h') TargetAdd('libp3linmath.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3linmath.in', opts=['IMOD:panda3d.core', 'ILIB:libp3linmath', 'SRCDIR:panda/src/linmath']) # # DIRECTORY: panda/src/putil/ # if (not RUNTIME): OPTS=['DIR:panda/src/putil', 'BUILDING:PANDA', 'ZLIB'] TargetAdd('p3putil_composite1.obj', opts=OPTS, input='p3putil_composite1.cxx') TargetAdd('p3putil_composite2.obj', opts=OPTS, input='p3putil_composite2.cxx') OPTS=['DIR:panda/src/putil', 'ZLIB'] IGATEFILES=GetDirectoryContents('panda/src/putil', ["*.h", "*_composite*.cxx"]) IGATEFILES.remove("test_bam.h") IGATEFILES.remove("config_util.h") TargetAdd('libp3putil.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3putil.in', opts=['IMOD:panda3d.core', 'ILIB:libp3putil', 'SRCDIR:panda/src/putil']) PyTargetAdd('p3putil_ext_composite.obj', opts=OPTS, input='p3putil_ext_composite.cxx') # # DIRECTORY: panda/src/audio/ # if (not RUNTIME): OPTS=['DIR:panda/src/audio', 'BUILDING:PANDA'] TargetAdd('p3audio_composite1.obj', opts=OPTS, input='p3audio_composite1.cxx') OPTS=['DIR:panda/src/audio'] IGATEFILES=["audio.h"] TargetAdd('libp3audio.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3audio.in', opts=['IMOD:panda3d.core', 'ILIB:libp3audio', 'SRCDIR:panda/src/audio']) # # DIRECTORY: panda/src/event/ # if (not RUNTIME): OPTS=['DIR:panda/src/event', 'BUILDING:PANDA'] TargetAdd('p3event_composite1.obj', opts=OPTS, input='p3event_composite1.cxx') TargetAdd('p3event_composite2.obj', opts=OPTS, input='p3event_composite2.cxx') OPTS=['DIR:panda/src/event'] PyTargetAdd('p3event_asyncFuture_ext.obj', opts=OPTS, input='asyncFuture_ext.cxx') PyTargetAdd('p3event_pythonTask.obj', opts=OPTS, input='pythonTask.cxx') IGATEFILES=GetDirectoryContents('panda/src/event', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3event.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3event.in', opts=['IMOD:panda3d.core', 'ILIB:libp3event', 'SRCDIR:panda/src/event']) # # DIRECTORY: panda/src/mathutil/ # if (not RUNTIME): OPTS=['DIR:panda/src/mathutil', 'BUILDING:PANDA', 'FFTW'] TargetAdd('p3mathutil_composite1.obj', opts=OPTS, input='p3mathutil_composite1.cxx') TargetAdd('p3mathutil_composite2.obj', opts=OPTS, input='p3mathutil_composite2.cxx') OPTS=['DIR:panda/src/mathutil', 'FFTW'] IGATEFILES=GetDirectoryContents('panda/src/mathutil', ["*.h", "*_composite*.cxx"]) for ifile in IGATEFILES[:]: if "_src." in ifile: IGATEFILES.remove(ifile) TargetAdd('libp3mathutil.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3mathutil.in', opts=['IMOD:panda3d.core', 'ILIB:libp3mathutil', 'SRCDIR:panda/src/mathutil']) # # DIRECTORY: panda/src/gsgbase/ # if (not RUNTIME): OPTS=['DIR:panda/src/gsgbase', 'BUILDING:PANDA'] TargetAdd('p3gsgbase_composite1.obj', opts=OPTS, input='p3gsgbase_composite1.cxx') OPTS=['DIR:panda/src/gsgbase'] IGATEFILES=GetDirectoryContents('panda/src/gsgbase', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3gsgbase.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3gsgbase.in', opts=['IMOD:panda3d.core', 'ILIB:libp3gsgbase', 'SRCDIR:panda/src/gsgbase']) # # DIRECTORY: panda/src/pnmimage/ # if (not RUNTIME): OPTS=['DIR:panda/src/pnmimage', 'BUILDING:PANDA', 'ZLIB'] TargetAdd('p3pnmimage_composite1.obj', opts=OPTS, input='p3pnmimage_composite1.cxx') TargetAdd('p3pnmimage_composite2.obj', opts=OPTS, input='p3pnmimage_composite2.cxx') TargetAdd('p3pnmimage_convert_srgb_sse2.obj', opts=OPTS+['SSE2'], input='convert_srgb_sse2.cxx') OPTS=['DIR:panda/src/pnmimage', 'ZLIB'] IGATEFILES=GetDirectoryContents('panda/src/pnmimage', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3pnmimage.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3pnmimage.in', opts=['IMOD:panda3d.core', 'ILIB:libp3pnmimage', 'SRCDIR:panda/src/pnmimage']) PyTargetAdd('p3pnmimage_pfmFile_ext.obj', opts=OPTS, input='pfmFile_ext.cxx') # # DIRECTORY: panda/src/nativenet/ # if (not RUNTIME): OPTS=['DIR:panda/src/nativenet', 'OPENSSL', 'BUILDING:PANDA'] TargetAdd('p3nativenet_composite1.obj', opts=OPTS, input='p3nativenet_composite1.cxx') OPTS=['DIR:panda/src/nativenet', 'OPENSSL'] IGATEFILES=GetDirectoryContents('panda/src/nativenet', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3nativenet.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3nativenet.in', opts=['IMOD:panda3d.core', 'ILIB:libp3nativenet', 'SRCDIR:panda/src/nativenet']) # # DIRECTORY: panda/src/net/ # if (not RUNTIME): OPTS=['DIR:panda/src/net', 'BUILDING:PANDA'] TargetAdd('p3net_composite1.obj', opts=OPTS, input='p3net_composite1.cxx') TargetAdd('p3net_composite2.obj', opts=OPTS, input='p3net_composite2.cxx') OPTS=['DIR:panda/src/net'] IGATEFILES=GetDirectoryContents('panda/src/net', ["*.h", "*_composite*.cxx"]) IGATEFILES.remove("datagram_ui.h") TargetAdd('libp3net.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3net.in', opts=['IMOD:panda3d.core', 'ILIB:libp3net', 'SRCDIR:panda/src/net']) # # DIRECTORY: panda/src/pstatclient/ # if (not RUNTIME): OPTS=['DIR:panda/src/pstatclient', 'BUILDING:PANDA'] TargetAdd('p3pstatclient_composite1.obj', opts=OPTS, input='p3pstatclient_composite1.cxx') TargetAdd('p3pstatclient_composite2.obj', opts=OPTS, input='p3pstatclient_composite2.cxx') OPTS=['DIR:panda/src/pstatclient'] IGATEFILES=GetDirectoryContents('panda/src/pstatclient', ["*.h", "*_composite*.cxx"]) IGATEFILES.remove("config_pstats.h") TargetAdd('libp3pstatclient.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3pstatclient.in', opts=['IMOD:panda3d.core', 'ILIB:libp3pstatclient', 'SRCDIR:panda/src/pstatclient']) # # DIRECTORY: panda/src/gobj/ # if (not RUNTIME): OPTS=['DIR:panda/src/gobj', 'BUILDING:PANDA', 'NVIDIACG', 'ZLIB', 'SQUISH'] TargetAdd('p3gobj_composite1.obj', opts=OPTS, input='p3gobj_composite1.cxx') TargetAdd('p3gobj_composite2.obj', opts=OPTS+['BIGOBJ'], input='p3gobj_composite2.cxx') OPTS=['DIR:panda/src/gobj', 'NVIDIACG', 'ZLIB', 'SQUISH'] IGATEFILES=GetDirectoryContents('panda/src/gobj', ["*.h", "*_composite*.cxx"]) if ("cgfx_states.h" in IGATEFILES): IGATEFILES.remove("cgfx_states.h") TargetAdd('libp3gobj.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3gobj.in', opts=['IMOD:panda3d.core', 'ILIB:libp3gobj', 'SRCDIR:panda/src/gobj']) PyTargetAdd('p3gobj_ext_composite.obj', opts=OPTS, input='p3gobj_ext_composite.cxx') # # DIRECTORY: panda/src/pgraphnodes/ # if (not RUNTIME): OPTS=['DIR:panda/src/pgraphnodes', 'BUILDING:PANDA'] TargetAdd('p3pgraphnodes_composite1.obj', opts=OPTS, input='p3pgraphnodes_composite1.cxx') TargetAdd('p3pgraphnodes_composite2.obj', opts=OPTS, input='p3pgraphnodes_composite2.cxx') OPTS=['DIR:panda/src/pgraphnodes'] IGATEFILES=GetDirectoryContents('panda/src/pgraphnodes', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3pgraphnodes.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3pgraphnodes.in', opts=['IMOD:panda3d.core', 'ILIB:libp3pgraphnodes', 'SRCDIR:panda/src/pgraphnodes']) # # DIRECTORY: panda/src/pgraph/ # if (not RUNTIME): OPTS=['DIR:panda/src/pgraph', 'BUILDING:PANDA'] TargetAdd('p3pgraph_nodePath.obj', opts=OPTS, input='nodePath.cxx') TargetAdd('p3pgraph_composite1.obj', opts=OPTS, input='p3pgraph_composite1.cxx') TargetAdd('p3pgraph_composite2.obj', opts=OPTS, input='p3pgraph_composite2.cxx') TargetAdd('p3pgraph_composite3.obj', opts=OPTS, input='p3pgraph_composite3.cxx') TargetAdd('p3pgraph_composite4.obj', opts=OPTS, input='p3pgraph_composite4.cxx') OPTS=['DIR:panda/src/pgraph'] IGATEFILES=GetDirectoryContents('panda/src/pgraph', ["*.h", "nodePath.cxx", "*_composite*.cxx"]) TargetAdd('libp3pgraph.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3pgraph.in', opts=['IMOD:panda3d.core', 'ILIB:libp3pgraph', 'SRCDIR:panda/src/pgraph']) PyTargetAdd('p3pgraph_ext_composite.obj', opts=OPTS, input='p3pgraph_ext_composite.cxx') # # DIRECTORY: panda/src/cull/ # if (not RUNTIME): OPTS=['DIR:panda/src/cull', 'BUILDING:PANDA'] TargetAdd('p3cull_composite1.obj', opts=OPTS, input='p3cull_composite1.cxx') TargetAdd('p3cull_composite2.obj', opts=OPTS, input='p3cull_composite2.cxx') OPTS=['DIR:panda/src/cull'] IGATEFILES=GetDirectoryContents('panda/src/cull', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3cull.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3cull.in', opts=['IMOD:panda3d.core', 'ILIB:libp3cull', 'SRCDIR:panda/src/cull']) # # DIRECTORY: panda/src/dgraph/ # if (not RUNTIME): OPTS=['DIR:panda/src/dgraph', 'BUILDING:PANDA'] TargetAdd('p3dgraph_composite1.obj', opts=OPTS, input='p3dgraph_composite1.cxx') TargetAdd('p3dgraph_composite2.obj', opts=OPTS, input='p3dgraph_composite2.cxx') OPTS=['DIR:panda/src/dgraph'] IGATEFILES=GetDirectoryContents('panda/src/dgraph', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3dgraph.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3dgraph.in', opts=['IMOD:panda3d.core', 'ILIB:libp3dgraph', 'SRCDIR:panda/src/dgraph']) # # DIRECTORY: panda/src/device/ # if (not RUNTIME): OPTS=['DIR:panda/src/device', 'BUILDING:PANDA'] TargetAdd('p3device_composite1.obj', opts=OPTS, input='p3device_composite1.cxx') TargetAdd('p3device_composite2.obj', opts=OPTS, input='p3device_composite2.cxx') OPTS=['DIR:panda/src/device'] IGATEFILES=GetDirectoryContents('panda/src/device', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3device.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3device.in', opts=['IMOD:panda3d.core', 'ILIB:libp3device', 'SRCDIR:panda/src/device']) # # DIRECTORY: panda/src/display/ # if (not RUNTIME): OPTS=['DIR:panda/src/display', 'BUILDING:PANDA'] TargetAdd('p3display_graphicsStateGuardian.obj', opts=OPTS, input='graphicsStateGuardian.cxx') TargetAdd('p3display_composite1.obj', opts=OPTS, input='p3display_composite1.cxx') TargetAdd('p3display_composite2.obj', opts=OPTS, input='p3display_composite2.cxx') OPTS=['DIR:panda/src/display'] IGATEFILES=GetDirectoryContents('panda/src/display', ["*.h", "*_composite*.cxx"]) IGATEFILES.remove("renderBuffer.h") TargetAdd('libp3display.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3display.in', opts=['IMOD:panda3d.core', 'ILIB:libp3display', 'SRCDIR:panda/src/display']) PyTargetAdd('p3display_ext_composite.obj', opts=OPTS, input='p3display_ext_composite.cxx') if RTDIST and GetTarget() == 'darwin': OPTS=['DIR:panda/src/display'] TargetAdd('subprocessWindowBuffer.obj', opts=OPTS, input='subprocessWindowBuffer.cxx') TargetAdd('libp3subprocbuffer.ilb', input='subprocessWindowBuffer.obj') # # DIRECTORY: panda/src/chan/ # if (not RUNTIME): OPTS=['DIR:panda/src/chan', 'BUILDING:PANDA'] TargetAdd('p3chan_composite1.obj', opts=OPTS, input='p3chan_composite1.cxx') TargetAdd('p3chan_composite2.obj', opts=OPTS, input='p3chan_composite2.cxx') OPTS=['DIR:panda/src/chan'] IGATEFILES=GetDirectoryContents('panda/src/chan', ["*.h", "*_composite*.cxx"]) IGATEFILES.remove('movingPart.h') IGATEFILES.remove('animChannelFixed.h') TargetAdd('libp3chan.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3chan.in', opts=['IMOD:panda3d.core', 'ILIB:libp3chan', 'SRCDIR:panda/src/chan']) # DIRECTORY: panda/src/char/ # if (not RUNTIME): OPTS=['DIR:panda/src/char', 'BUILDING:PANDA'] TargetAdd('p3char_composite1.obj', opts=OPTS, input='p3char_composite1.cxx') TargetAdd('p3char_composite2.obj', opts=OPTS, input='p3char_composite2.cxx') OPTS=['DIR:panda/src/char'] IGATEFILES=GetDirectoryContents('panda/src/char', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3char.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3char.in', opts=['IMOD:panda3d.core', 'ILIB:libp3char', 'SRCDIR:panda/src/char']) # # DIRECTORY: panda/src/pnmtext/ # if (PkgSkip("FREETYPE")==0 and not RUNTIME): OPTS=['DIR:panda/src/pnmtext', 'BUILDING:PANDA', 'FREETYPE'] TargetAdd('p3pnmtext_composite1.obj', opts=OPTS, input='p3pnmtext_composite1.cxx') OPTS=['DIR:panda/src/pnmtext', 'FREETYPE'] IGATEFILES=GetDirectoryContents('panda/src/pnmtext', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3pnmtext.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3pnmtext.in', opts=['IMOD:panda3d.core', 'ILIB:libp3pnmtext', 'SRCDIR:panda/src/pnmtext']) # # DIRECTORY: panda/src/text/ # if (not RUNTIME): if not PkgSkip("HARFBUZZ"): DefSymbol("HARFBUZZ", "HAVE_HARFBUZZ") OPTS=['DIR:panda/src/text', 'BUILDING:PANDA', 'ZLIB', 'FREETYPE', 'HARFBUZZ'] TargetAdd('p3text_composite1.obj', opts=OPTS, input='p3text_composite1.cxx') TargetAdd('p3text_composite2.obj', opts=OPTS, input='p3text_composite2.cxx') OPTS=['DIR:panda/src/text', 'ZLIB', 'FREETYPE'] IGATEFILES=GetDirectoryContents('panda/src/text', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3text.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3text.in', opts=['IMOD:panda3d.core', 'ILIB:libp3text', 'SRCDIR:panda/src/text']) # # DIRECTORY: panda/src/movies/ # if (not RUNTIME): OPTS=['DIR:panda/src/movies', 'BUILDING:PANDA', 'VORBIS', 'OPUS'] TargetAdd('p3movies_composite1.obj', opts=OPTS, input='p3movies_composite1.cxx') OPTS=['DIR:panda/src/movies', 'VORBIS', 'OPUS'] IGATEFILES=GetDirectoryContents('panda/src/movies', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3movies.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3movies.in', opts=['IMOD:panda3d.core', 'ILIB:libp3movies', 'SRCDIR:panda/src/movies']) # # DIRECTORY: panda/src/grutil/ # if (not RUNTIME): OPTS=['DIR:panda/src/grutil', 'BUILDING:PANDA'] TargetAdd('p3grutil_multitexReducer.obj', opts=OPTS, input='multitexReducer.cxx') TargetAdd('p3grutil_composite1.obj', opts=OPTS, input='p3grutil_composite1.cxx') TargetAdd('p3grutil_composite2.obj', opts=OPTS, input='p3grutil_composite2.cxx') OPTS=['DIR:panda/src/grutil'] IGATEFILES=GetDirectoryContents('panda/src/grutil', ["*.h", "*_composite*.cxx"]) if 'convexHull.h' in IGATEFILES: IGATEFILES.remove('convexHull.h') TargetAdd('libp3grutil.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3grutil.in', opts=['IMOD:panda3d.core', 'ILIB:libp3grutil', 'SRCDIR:panda/src/grutil']) # # DIRECTORY: panda/src/tform/ # if (not RUNTIME): OPTS=['DIR:panda/src/tform', 'BUILDING:PANDA'] TargetAdd('p3tform_composite1.obj', opts=OPTS, input='p3tform_composite1.cxx') TargetAdd('p3tform_composite2.obj', opts=OPTS, input='p3tform_composite2.cxx') OPTS=['DIR:panda/src/tform'] IGATEFILES=GetDirectoryContents('panda/src/tform', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3tform.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3tform.in', opts=['IMOD:panda3d.core', 'ILIB:libp3tform', 'SRCDIR:panda/src/tform']) # # DIRECTORY: panda/src/collide/ # if (not RUNTIME): OPTS=['DIR:panda/src/collide', 'BUILDING:PANDA'] TargetAdd('p3collide_composite1.obj', opts=OPTS, input='p3collide_composite1.cxx') TargetAdd('p3collide_composite2.obj', opts=OPTS, input='p3collide_composite2.cxx') OPTS=['DIR:panda/src/collide'] IGATEFILES=GetDirectoryContents('panda/src/collide', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3collide.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3collide.in', opts=['IMOD:panda3d.core', 'ILIB:libp3collide', 'SRCDIR:panda/src/collide']) # # DIRECTORY: panda/src/parametrics/ # if (not RUNTIME): OPTS=['DIR:panda/src/parametrics', 'BUILDING:PANDA'] TargetAdd('p3parametrics_composite1.obj', opts=OPTS, input='p3parametrics_composite1.cxx') TargetAdd('p3parametrics_composite2.obj', opts=OPTS, input='p3parametrics_composite2.cxx') OPTS=['DIR:panda/src/parametrics'] IGATEFILES=GetDirectoryContents('panda/src/parametrics', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3parametrics.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3parametrics.in', opts=['IMOD:panda3d.core', 'ILIB:libp3parametrics', 'SRCDIR:panda/src/parametrics']) # # DIRECTORY: panda/src/pgui/ # if (not RUNTIME): OPTS=['DIR:panda/src/pgui', 'BUILDING:PANDA'] TargetAdd('p3pgui_composite1.obj', opts=OPTS, input='p3pgui_composite1.cxx') TargetAdd('p3pgui_composite2.obj', opts=OPTS, input='p3pgui_composite2.cxx') OPTS=['DIR:panda/src/pgui'] IGATEFILES=GetDirectoryContents('panda/src/pgui', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3pgui.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3pgui.in', opts=['IMOD:panda3d.core', 'ILIB:libp3pgui', 'SRCDIR:panda/src/pgui']) # # DIRECTORY: panda/src/pnmimagetypes/ # if (not RUNTIME): OPTS=['DIR:panda/src/pnmimagetypes', 'DIR:panda/src/pnmimage', 'BUILDING:PANDA', 'PNG', 'ZLIB', 'JPEG', 'TIFF', 'OPENEXR', 'EXCEPTIONS'] TargetAdd('p3pnmimagetypes_composite1.obj', opts=OPTS, input='p3pnmimagetypes_composite1.cxx') TargetAdd('p3pnmimagetypes_composite2.obj', opts=OPTS, input='p3pnmimagetypes_composite2.cxx') # # DIRECTORY: panda/src/recorder/ # if (not RUNTIME): OPTS=['DIR:panda/src/recorder', 'BUILDING:PANDA'] TargetAdd('p3recorder_composite1.obj', opts=OPTS, input='p3recorder_composite1.cxx') TargetAdd('p3recorder_composite2.obj', opts=OPTS, input='p3recorder_composite2.cxx') OPTS=['DIR:panda/src/recorder'] IGATEFILES=GetDirectoryContents('panda/src/recorder', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3recorder.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3recorder.in', opts=['IMOD:panda3d.core', 'ILIB:libp3recorder', 'SRCDIR:panda/src/recorder']) # # DIRECTORY: panda/src/dxml/ # DefSymbol("TINYXML", "TIXML_USE_STL", "") OPTS=['DIR:panda/src/dxml', 'TINYXML'] TargetAdd('tinyxml_composite1.obj', opts=OPTS, input='tinyxml_composite1.cxx') TargetAdd('libp3tinyxml.ilb', input='tinyxml_composite1.obj') if (not RUNTIME): OPTS=['DIR:panda/src/dxml', 'BUILDING:PANDA', 'TINYXML'] TargetAdd('p3dxml_composite1.obj', opts=OPTS, input='p3dxml_composite1.cxx') OPTS=['DIR:panda/src/dxml', 'TINYXML'] IGATEFILES=GetDirectoryContents('panda/src/dxml', ["*.h", "p3dxml_composite1.cxx"]) TargetAdd('libp3dxml.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3dxml.in', opts=['IMOD:panda3d.core', 'ILIB:libp3dxml', 'SRCDIR:panda/src/dxml']) # # DIRECTORY: panda/metalibs/panda/ # if (not RUNTIME): OPTS=['DIR:panda/metalibs/panda', 'BUILDING:PANDA', 'JPEG', 'PNG', 'HARFBUZZ', 'TIFF', 'OPENEXR', 'ZLIB', 'OPENSSL', 'FREETYPE', 'FFTW', 'ADVAPI', 'WINSOCK2', 'SQUISH', 'NVIDIACG', 'VORBIS', 'OPUS', 'WINUSER', 'WINMM', 'WINGDI', 'IPHLPAPI', 'SETUPAPI'] TargetAdd('panda_panda.obj', opts=OPTS, input='panda.cxx') TargetAdd('libpanda.dll', input='panda_panda.obj') TargetAdd('libpanda.dll', input='p3recorder_composite1.obj') TargetAdd('libpanda.dll', input='p3recorder_composite2.obj') TargetAdd('libpanda.dll', input='p3pgraphnodes_composite1.obj') TargetAdd('libpanda.dll', input='p3pgraphnodes_composite2.obj') TargetAdd('libpanda.dll', input='p3pgraph_nodePath.obj') TargetAdd('libpanda.dll', input='p3pgraph_composite1.obj') TargetAdd('libpanda.dll', input='p3pgraph_composite2.obj') TargetAdd('libpanda.dll', input='p3pgraph_composite3.obj') TargetAdd('libpanda.dll', input='p3pgraph_composite4.obj') TargetAdd('libpanda.dll', input='p3cull_composite1.obj') TargetAdd('libpanda.dll', input='p3cull_composite2.obj') TargetAdd('libpanda.dll', input='p3movies_composite1.obj') TargetAdd('libpanda.dll', input='p3grutil_multitexReducer.obj') TargetAdd('libpanda.dll', input='p3grutil_composite1.obj') TargetAdd('libpanda.dll', input='p3grutil_composite2.obj') TargetAdd('libpanda.dll', input='p3chan_composite1.obj') TargetAdd('libpanda.dll', input='p3chan_composite2.obj') TargetAdd('libpanda.dll', input='p3pstatclient_composite1.obj') TargetAdd('libpanda.dll', input='p3pstatclient_composite2.obj') TargetAdd('libpanda.dll', input='p3char_composite1.obj') TargetAdd('libpanda.dll', input='p3char_composite2.obj') TargetAdd('libpanda.dll', input='p3collide_composite1.obj') TargetAdd('libpanda.dll', input='p3collide_composite2.obj') TargetAdd('libpanda.dll', input='p3device_composite1.obj') TargetAdd('libpanda.dll', input='p3device_composite2.obj') TargetAdd('libpanda.dll', input='p3dgraph_composite1.obj') TargetAdd('libpanda.dll', input='p3dgraph_composite2.obj') TargetAdd('libpanda.dll', input='p3display_graphicsStateGuardian.obj') TargetAdd('libpanda.dll', input='p3display_composite1.obj') TargetAdd('libpanda.dll', input='p3display_composite2.obj') TargetAdd('libpanda.dll', input='p3pipeline_composite1.obj') TargetAdd('libpanda.dll', input='p3pipeline_composite2.obj') TargetAdd('libpanda.dll', input='p3pipeline_contextSwitch.obj') TargetAdd('libpanda.dll', input='p3event_composite1.obj') TargetAdd('libpanda.dll', input='p3event_composite2.obj') TargetAdd('libpanda.dll', input='p3gobj_composite1.obj') TargetAdd('libpanda.dll', input='p3gobj_composite2.obj') TargetAdd('libpanda.dll', input='p3gsgbase_composite1.obj') TargetAdd('libpanda.dll', input='p3linmath_composite1.obj') TargetAdd('libpanda.dll', input='p3linmath_composite2.obj') TargetAdd('libpanda.dll', input='p3mathutil_composite1.obj') TargetAdd('libpanda.dll', input='p3mathutil_composite2.obj') TargetAdd('libpanda.dll', input='p3parametrics_composite1.obj') TargetAdd('libpanda.dll', input='p3parametrics_composite2.obj') TargetAdd('libpanda.dll', input='p3pnmimagetypes_composite1.obj') TargetAdd('libpanda.dll', input='p3pnmimagetypes_composite2.obj') TargetAdd('libpanda.dll', input='p3pnmimage_composite1.obj') TargetAdd('libpanda.dll', input='p3pnmimage_composite2.obj') TargetAdd('libpanda.dll', input='p3pnmimage_convert_srgb_sse2.obj') TargetAdd('libpanda.dll', input='p3text_composite1.obj') TargetAdd('libpanda.dll', input='p3text_composite2.obj') TargetAdd('libpanda.dll', input='p3tform_composite1.obj') TargetAdd('libpanda.dll', input='p3tform_composite2.obj') TargetAdd('libpanda.dll', input='p3putil_composite1.obj') TargetAdd('libpanda.dll', input='p3putil_composite2.obj') TargetAdd('libpanda.dll', input='p3audio_composite1.obj') TargetAdd('libpanda.dll', input='p3pgui_composite1.obj') TargetAdd('libpanda.dll', input='p3pgui_composite2.obj') TargetAdd('libpanda.dll', input='p3net_composite1.obj') TargetAdd('libpanda.dll', input='p3net_composite2.obj') TargetAdd('libpanda.dll', input='p3nativenet_composite1.obj') TargetAdd('libpanda.dll', input='p3pandabase_pandabase.obj') TargetAdd('libpanda.dll', input='libpandaexpress.dll') TargetAdd('libpanda.dll', input='p3dxml_composite1.obj') TargetAdd('libpanda.dll', input='libp3dtoolconfig.dll') TargetAdd('libpanda.dll', input='libp3dtool.dll') if PkgSkip("FREETYPE")==0: TargetAdd('libpanda.dll', input="p3pnmtext_composite1.obj") TargetAdd('libpanda.dll', dep='dtool_have_freetype.dat') TargetAdd('libpanda.dll', opts=OPTS) PyTargetAdd('core_module.obj', input='libp3dtoolbase.in') PyTargetAdd('core_module.obj', input='libp3dtoolutil.in') PyTargetAdd('core_module.obj', input='libp3prc.in') PyTargetAdd('core_module.obj', input='libp3downloader.in') PyTargetAdd('core_module.obj', input='libp3express.in') PyTargetAdd('core_module.obj', input='libp3recorder.in') PyTargetAdd('core_module.obj', input='libp3pgraphnodes.in') PyTargetAdd('core_module.obj', input='libp3pgraph.in') PyTargetAdd('core_module.obj', input='libp3cull.in') PyTargetAdd('core_module.obj', input='libp3grutil.in') PyTargetAdd('core_module.obj', input='libp3chan.in') PyTargetAdd('core_module.obj', input='libp3pstatclient.in') PyTargetAdd('core_module.obj', input='libp3char.in') PyTargetAdd('core_module.obj', input='libp3collide.in') PyTargetAdd('core_module.obj', input='libp3device.in') PyTargetAdd('core_module.obj', input='libp3dgraph.in') PyTargetAdd('core_module.obj', input='libp3display.in') PyTargetAdd('core_module.obj', input='libp3pipeline.in') PyTargetAdd('core_module.obj', input='libp3event.in') PyTargetAdd('core_module.obj', input='libp3gobj.in') PyTargetAdd('core_module.obj', input='libp3gsgbase.in') PyTargetAdd('core_module.obj', input='libp3linmath.in') PyTargetAdd('core_module.obj', input='libp3mathutil.in') PyTargetAdd('core_module.obj', input='libp3parametrics.in') PyTargetAdd('core_module.obj', input='libp3pnmimage.in') PyTargetAdd('core_module.obj', input='libp3text.in') PyTargetAdd('core_module.obj', input='libp3tform.in') PyTargetAdd('core_module.obj', input='libp3putil.in') PyTargetAdd('core_module.obj', input='libp3audio.in') PyTargetAdd('core_module.obj', input='libp3nativenet.in') PyTargetAdd('core_module.obj', input='libp3net.in') PyTargetAdd('core_module.obj', input='libp3pgui.in') PyTargetAdd('core_module.obj', input='libp3movies.in') PyTargetAdd('core_module.obj', input='libp3dxml.in') if PkgSkip("FREETYPE")==0: PyTargetAdd('core_module.obj', input='libp3pnmtext.in') PyTargetAdd('core_module.obj', opts=['IMOD:panda3d.core', 'ILIB:core']) PyTargetAdd('core.pyd', input='libp3dtoolbase_igate.obj') PyTargetAdd('core.pyd', input='p3dtoolbase_typeHandle_ext.obj') PyTargetAdd('core.pyd', input='libp3dtoolutil_igate.obj') PyTargetAdd('core.pyd', input='p3dtoolutil_ext_composite.obj') PyTargetAdd('core.pyd', input='libp3prc_igate.obj') PyTargetAdd('core.pyd', input='p3prc_ext_composite.obj') PyTargetAdd('core.pyd', input='libp3downloader_igate.obj') PyTargetAdd('core.pyd', input='p3downloader_stringStream_ext.obj') PyTargetAdd('core.pyd', input='p3express_ext_composite.obj') PyTargetAdd('core.pyd', input='libp3express_igate.obj') PyTargetAdd('core.pyd', input='libp3recorder_igate.obj') PyTargetAdd('core.pyd', input='libp3pgraphnodes_igate.obj') PyTargetAdd('core.pyd', input='libp3pgraph_igate.obj') PyTargetAdd('core.pyd', input='libp3movies_igate.obj') PyTargetAdd('core.pyd', input='libp3grutil_igate.obj') PyTargetAdd('core.pyd', input='libp3chan_igate.obj') PyTargetAdd('core.pyd', input='libp3pstatclient_igate.obj') PyTargetAdd('core.pyd', input='libp3char_igate.obj') PyTargetAdd('core.pyd', input='libp3collide_igate.obj') PyTargetAdd('core.pyd', input='libp3device_igate.obj') PyTargetAdd('core.pyd', input='libp3dgraph_igate.obj') PyTargetAdd('core.pyd', input='libp3display_igate.obj') PyTargetAdd('core.pyd', input='libp3pipeline_igate.obj') PyTargetAdd('core.pyd', input='libp3event_igate.obj') PyTargetAdd('core.pyd', input='libp3gobj_igate.obj') PyTargetAdd('core.pyd', input='libp3gsgbase_igate.obj') PyTargetAdd('core.pyd', input='libp3linmath_igate.obj') PyTargetAdd('core.pyd', input='libp3mathutil_igate.obj') PyTargetAdd('core.pyd', input='libp3parametrics_igate.obj') PyTargetAdd('core.pyd', input='libp3pnmimage_igate.obj') PyTargetAdd('core.pyd', input='libp3text_igate.obj') PyTargetAdd('core.pyd', input='libp3tform_igate.obj') PyTargetAdd('core.pyd', input='libp3putil_igate.obj') PyTargetAdd('core.pyd', input='libp3audio_igate.obj') PyTargetAdd('core.pyd', input='libp3pgui_igate.obj') PyTargetAdd('core.pyd', input='libp3net_igate.obj') PyTargetAdd('core.pyd', input='libp3nativenet_igate.obj') PyTargetAdd('core.pyd', input='libp3dxml_igate.obj') if PkgSkip("FREETYPE")==0: PyTargetAdd('core.pyd', input="libp3pnmtext_igate.obj") PyTargetAdd('core.pyd', input='p3pipeline_pythonThread.obj') PyTargetAdd('core.pyd', input='p3putil_ext_composite.obj') PyTargetAdd('core.pyd', input='p3pnmimage_pfmFile_ext.obj') PyTargetAdd('core.pyd', input='p3event_asyncFuture_ext.obj') PyTargetAdd('core.pyd', input='p3event_pythonTask.obj') PyTargetAdd('core.pyd', input='p3gobj_ext_composite.obj') PyTargetAdd('core.pyd', input='p3pgraph_ext_composite.obj') PyTargetAdd('core.pyd', input='p3display_ext_composite.obj') PyTargetAdd('core.pyd', input='core_module.obj') if not GetLinkAllStatic() and GetTarget() != 'emscripten': PyTargetAdd('core.pyd', input='libp3tinyxml.ilb') PyTargetAdd('core.pyd', input='libp3interrogatedb.dll') PyTargetAdd('core.pyd', input=COMMON_PANDA_LIBS) PyTargetAdd('core.pyd', opts=['WINSOCK2']) # # DIRECTORY: panda/src/vision/ # if (PkgSkip("VISION") == 0) and (not RUNTIME): # We want to know whether we have ffmpeg so that we can override the .avi association. if not PkgSkip("FFMPEG"): DefSymbol("OPENCV", "HAVE_FFMPEG") if not PkgSkip("OPENCV"): DefSymbol("OPENCV", "HAVE_OPENCV") if OPENCV_VER_23: DefSymbol("OPENCV", "OPENCV_VER_23") OPTS=['DIR:panda/src/vision', 'BUILDING:VISION', 'ARTOOLKIT', 'OPENCV', 'DX9', 'DIRECTCAM', 'JPEG', 'EXCEPTIONS'] TargetAdd('p3vision_composite1.obj', opts=OPTS, input='p3vision_composite1.cxx', dep=[ 'dtool_have_ffmpeg.dat', 'dtool_have_opencv.dat', 'dtool_have_directcam.dat', ]) TargetAdd('libp3vision.dll', input='p3vision_composite1.obj') TargetAdd('libp3vision.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3vision.dll', opts=OPTS) OPTS=['DIR:panda/src/vision', 'ARTOOLKIT', 'OPENCV', 'DX9', 'DIRECTCAM', 'JPEG', 'EXCEPTIONS'] IGATEFILES=GetDirectoryContents('panda/src/vision', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3vision.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3vision.in', opts=['IMOD:panda3d.vision', 'ILIB:libp3vision', 'SRCDIR:panda/src/vision']) PyTargetAdd('vision_module.obj', input='libp3vision.in') PyTargetAdd('vision_module.obj', opts=OPTS) PyTargetAdd('vision_module.obj', opts=['IMOD:panda3d.vision', 'ILIB:vision', 'IMPORT:panda3d.core']) PyTargetAdd('vision.pyd', input='vision_module.obj') PyTargetAdd('vision.pyd', input='libp3vision_igate.obj') PyTargetAdd('vision.pyd', input='libp3vision.dll') PyTargetAdd('vision.pyd', input='libp3interrogatedb.dll') PyTargetAdd('vision.pyd', input=COMMON_PANDA_LIBS) # # DIRECTORY: panda/src/rocket/ # if (PkgSkip("ROCKET") == 0) and (not RUNTIME): OPTS=['DIR:panda/src/rocket', 'BUILDING:ROCKET', 'ROCKET', 'PYTHON'] TargetAdd('p3rocket_composite1.obj', opts=OPTS, input='p3rocket_composite1.cxx') TargetAdd('libp3rocket.dll', input='p3rocket_composite1.obj') TargetAdd('libp3rocket.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3rocket.dll', opts=OPTS) OPTS=['DIR:panda/src/rocket', 'ROCKET', 'RTTI', 'EXCEPTIONS'] IGATEFILES=GetDirectoryContents('panda/src/rocket', ["rocketInputHandler.h", "rocketInputHandler.cxx", "rocketRegion.h", "rocketRegion.cxx", "rocketRegion_ext.h"]) TargetAdd('libp3rocket.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3rocket.in', opts=['IMOD:panda3d.rocket', 'ILIB:libp3rocket', 'SRCDIR:panda/src/rocket']) PyTargetAdd('p3rocket_rocketRegion_ext.obj', opts=OPTS, input='rocketRegion_ext.cxx') PyTargetAdd('rocket_module.obj', input='libp3rocket.in') PyTargetAdd('rocket_module.obj', opts=OPTS) PyTargetAdd('rocket_module.obj', opts=['IMOD:panda3d.rocket', 'ILIB:rocket', 'IMPORT:panda3d.core']) PyTargetAdd('rocket.pyd', input='rocket_module.obj') PyTargetAdd('rocket.pyd', input='libp3rocket_igate.obj') PyTargetAdd('rocket.pyd', input='p3rocket_rocketRegion_ext.obj') PyTargetAdd('rocket.pyd', input='libp3rocket.dll') PyTargetAdd('rocket.pyd', input='libp3interrogatedb.dll') PyTargetAdd('rocket.pyd', input=COMMON_PANDA_LIBS) PyTargetAdd('rocket.pyd', opts=['ROCKET']) # # DIRECTORY: panda/src/p3skel # if (PkgSkip('SKEL')==0) and (not RUNTIME): OPTS=['DIR:panda/src/skel', 'BUILDING:PANDASKEL', 'ADVAPI'] TargetAdd('p3skel_composite1.obj', opts=OPTS, input='p3skel_composite1.cxx') OPTS=['DIR:panda/src/skel', 'ADVAPI'] IGATEFILES=GetDirectoryContents("panda/src/skel", ["*.h", "*_composite*.cxx"]) TargetAdd('libp3skel.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3skel.in', opts=['IMOD:panda3d.skel', 'ILIB:libp3skel', 'SRCDIR:panda/src/skel']) # # DIRECTORY: panda/src/p3skel # if (PkgSkip('SKEL')==0) and (not RUNTIME): OPTS=['BUILDING:PANDASKEL', 'ADVAPI'] TargetAdd('libpandaskel.dll', input='p3skel_composite1.obj') TargetAdd('libpandaskel.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandaskel.dll', opts=OPTS) PyTargetAdd('skel_module.obj', input='libp3skel.in') PyTargetAdd('skel_module.obj', opts=['IMOD:panda3d.skel', 'ILIB:skel', 'IMPORT:panda3d.core']) PyTargetAdd('skel.pyd', input='skel_module.obj') PyTargetAdd('skel.pyd', input='libp3skel_igate.obj') PyTargetAdd('skel.pyd', input='libpandaskel.dll') PyTargetAdd('skel.pyd', input='libp3interrogatedb.dll') PyTargetAdd('skel.pyd', input=COMMON_PANDA_LIBS) # # DIRECTORY: panda/src/distort/ # if (PkgSkip('PANDAFX')==0) and (not RUNTIME): OPTS=['DIR:panda/src/distort', 'BUILDING:PANDAFX'] TargetAdd('p3distort_composite1.obj', opts=OPTS, input='p3distort_composite1.cxx') OPTS=['DIR:panda/metalibs/pandafx', 'DIR:panda/src/distort', 'NVIDIACG'] IGATEFILES=GetDirectoryContents('panda/src/distort', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3distort.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3distort.in', opts=['IMOD:panda3d.fx', 'ILIB:libp3distort', 'SRCDIR:panda/src/distort']) # # DIRECTORY: panda/metalibs/pandafx/ # if (PkgSkip('PANDAFX')==0) and (not RUNTIME): OPTS=['DIR:panda/metalibs/pandafx', 'DIR:panda/src/distort', 'BUILDING:PANDAFX', 'NVIDIACG'] TargetAdd('pandafx_pandafx.obj', opts=OPTS, input='pandafx.cxx') TargetAdd('libpandafx.dll', input='pandafx_pandafx.obj') TargetAdd('libpandafx.dll', input='p3distort_composite1.obj') TargetAdd('libpandafx.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandafx.dll', opts=['ADVAPI', 'NVIDIACG']) OPTS=['DIR:panda/metalibs/pandafx', 'DIR:panda/src/distort', 'NVIDIACG'] PyTargetAdd('fx_module.obj', input='libp3distort.in') PyTargetAdd('fx_module.obj', opts=OPTS) PyTargetAdd('fx_module.obj', opts=['IMOD:panda3d.fx', 'ILIB:fx', 'IMPORT:panda3d.core']) PyTargetAdd('fx.pyd', input='fx_module.obj') PyTargetAdd('fx.pyd', input='libp3distort_igate.obj') PyTargetAdd('fx.pyd', input='libpandafx.dll') PyTargetAdd('fx.pyd', input='libp3interrogatedb.dll') PyTargetAdd('fx.pyd', input=COMMON_PANDA_LIBS) # # DIRECTORY: panda/src/vrpn/ # if (PkgSkip("VRPN")==0 and not RUNTIME): OPTS=['DIR:panda/src/vrpn', 'BUILDING:VRPN', 'VRPN'] TargetAdd('p3vrpn_composite1.obj', opts=OPTS, input='p3vrpn_composite1.cxx') TargetAdd('libp3vrpn.dll', input='p3vrpn_composite1.obj') TargetAdd('libp3vrpn.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3vrpn.dll', opts=['VRPN']) OPTS=['DIR:panda/src/vrpn', 'VRPN'] IGATEFILES=GetDirectoryContents('panda/src/vrpn', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3vrpn.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3vrpn.in', opts=['IMOD:panda3d.vrpn', 'ILIB:libp3vrpn', 'SRCDIR:panda/src/vrpn']) PyTargetAdd('vrpn_module.obj', input='libp3vrpn.in') PyTargetAdd('vrpn_module.obj', opts=OPTS) PyTargetAdd('vrpn_module.obj', opts=['IMOD:panda3d.vrpn', 'ILIB:vrpn', 'IMPORT:panda3d.core']) PyTargetAdd('vrpn.pyd', input='vrpn_module.obj') PyTargetAdd('vrpn.pyd', input='libp3vrpn_igate.obj') PyTargetAdd('vrpn.pyd', input='libp3vrpn.dll') PyTargetAdd('vrpn.pyd', input='libp3interrogatedb.dll') PyTargetAdd('vrpn.pyd', input=COMMON_PANDA_LIBS) # # DIRECTORY: panda/src/ffmpeg # if PkgSkip("FFMPEG") == 0 and not RUNTIME: if not PkgSkip("SWSCALE"): DefSymbol("FFMPEG", "HAVE_SWSCALE") if not PkgSkip("SWRESAMPLE"): DefSymbol("FFMPEG", "HAVE_SWRESAMPLE") OPTS=['DIR:panda/src/ffmpeg', 'BUILDING:FFMPEG', 'FFMPEG', 'SWSCALE', 'SWRESAMPLE'] TargetAdd('p3ffmpeg_composite1.obj', opts=OPTS, input='p3ffmpeg_composite1.cxx', dep=[ 'dtool_have_swscale.dat', 'dtool_have_swresample.dat']) TargetAdd('libp3ffmpeg.dll', input='p3ffmpeg_composite1.obj') TargetAdd('libp3ffmpeg.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3ffmpeg.dll', opts=OPTS) # # DIRECTORY: panda/src/audiotraits/ # if PkgSkip("FMODEX") == 0 and not RUNTIME: OPTS=['DIR:panda/src/audiotraits', 'BUILDING:FMOD_AUDIO', 'FMODEX'] TargetAdd('fmod_audio_fmod_audio_composite1.obj', opts=OPTS, input='fmod_audio_composite1.cxx') TargetAdd('libp3fmod_audio.dll', input='fmod_audio_fmod_audio_composite1.obj') TargetAdd('libp3fmod_audio.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3fmod_audio.dll', opts=['MODULE', 'ADVAPI', 'WINUSER', 'WINMM', 'FMODEX']) if PkgSkip("OPENAL") == 0 and not RUNTIME: OPTS=['DIR:panda/src/audiotraits', 'BUILDING:OPENAL_AUDIO', 'OPENAL'] TargetAdd('openal_audio_openal_audio_composite1.obj', opts=OPTS, input='openal_audio_composite1.cxx') TargetAdd('libp3openal_audio.dll', input='openal_audio_openal_audio_composite1.obj') TargetAdd('libp3openal_audio.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3openal_audio.dll', opts=['MODULE', 'ADVAPI', 'WINUSER', 'WINMM', 'WINSHELL', 'WINOLE', 'OPENAL']) # # DIRECTORY: panda/src/downloadertools/ # if (PkgSkip("OPENSSL")==0 and not RTDIST and not RUNTIME and PkgSkip("DEPLOYTOOLS")==0): OPTS=['DIR:panda/src/downloadertools', 'OPENSSL', 'ZLIB', 'ADVAPI', 'WINSOCK2', 'WINSHELL', 'WINGDI', 'WINUSER'] TargetAdd('apply_patch_apply_patch.obj', opts=OPTS, input='apply_patch.cxx') TargetAdd('apply_patch.exe', input=['apply_patch_apply_patch.obj']) TargetAdd('apply_patch.exe', input=COMMON_PANDA_LIBS) TargetAdd('apply_patch.exe', opts=OPTS) TargetAdd('build_patch_build_patch.obj', opts=OPTS, input='build_patch.cxx') TargetAdd('build_patch.exe', input=['build_patch_build_patch.obj']) TargetAdd('build_patch.exe', input=COMMON_PANDA_LIBS) TargetAdd('build_patch.exe', opts=OPTS) if not PkgSkip("ZLIB"): TargetAdd('check_adler_check_adler.obj', opts=OPTS, input='check_adler.cxx') TargetAdd('check_adler.exe', input=['check_adler_check_adler.obj']) TargetAdd('check_adler.exe', input=COMMON_PANDA_LIBS) TargetAdd('check_adler.exe', opts=OPTS) TargetAdd('check_crc_check_crc.obj', opts=OPTS, input='check_crc.cxx') TargetAdd('check_crc.exe', input=['check_crc_check_crc.obj']) TargetAdd('check_crc.exe', input=COMMON_PANDA_LIBS) TargetAdd('check_crc.exe', opts=OPTS) TargetAdd('check_md5_check_md5.obj', opts=OPTS, input='check_md5.cxx') TargetAdd('check_md5.exe', input=['check_md5_check_md5.obj']) TargetAdd('check_md5.exe', input=COMMON_PANDA_LIBS) TargetAdd('check_md5.exe', opts=OPTS) TargetAdd('pdecrypt_pdecrypt.obj', opts=OPTS, input='pdecrypt.cxx') TargetAdd('pdecrypt.exe', input=['pdecrypt_pdecrypt.obj']) TargetAdd('pdecrypt.exe', input=COMMON_PANDA_LIBS) TargetAdd('pdecrypt.exe', opts=OPTS) TargetAdd('pencrypt_pencrypt.obj', opts=OPTS, input='pencrypt.cxx') TargetAdd('pencrypt.exe', input=['pencrypt_pencrypt.obj']) TargetAdd('pencrypt.exe', input=COMMON_PANDA_LIBS) TargetAdd('pencrypt.exe', opts=OPTS) TargetAdd('show_ddb_show_ddb.obj', opts=OPTS, input='show_ddb.cxx') TargetAdd('show_ddb.exe', input=['show_ddb_show_ddb.obj']) TargetAdd('show_ddb.exe', input=COMMON_PANDA_LIBS) TargetAdd('show_ddb.exe', opts=OPTS) # # DIRECTORY: panda/src/downloadertools/ # if (PkgSkip("ZLIB")==0 and not RTDIST and not RUNTIME and PkgSkip("DEPLOYTOOLS")==0): OPTS=['DIR:panda/src/downloadertools', 'ZLIB', 'OPENSSL', 'ADVAPI', 'WINSOCK2', 'WINSHELL', 'WINGDI', 'WINUSER'] TargetAdd('multify_multify.obj', opts=OPTS, input='multify.cxx') TargetAdd('multify.exe', input=['multify_multify.obj']) TargetAdd('multify.exe', input=COMMON_PANDA_LIBS) TargetAdd('multify.exe', opts=OPTS) TargetAdd('pzip_pzip.obj', opts=OPTS, input='pzip.cxx') TargetAdd('pzip.exe', input=['pzip_pzip.obj']) TargetAdd('pzip.exe', input=COMMON_PANDA_LIBS) TargetAdd('pzip.exe', opts=OPTS) TargetAdd('punzip_punzip.obj', opts=OPTS, input='punzip.cxx') TargetAdd('punzip.exe', input=['punzip_punzip.obj']) TargetAdd('punzip.exe', input=COMMON_PANDA_LIBS) TargetAdd('punzip.exe', opts=OPTS) # # DIRECTORY: panda/src/windisplay/ # if (GetTarget() == 'windows' and not RUNTIME): OPTS=['DIR:panda/src/windisplay', 'BUILDING:PANDAWIN'] TargetAdd('p3windisplay_composite1.obj', opts=OPTS+["BIGOBJ"], input='p3windisplay_composite1.cxx') TargetAdd('p3windisplay_windetectdx9.obj', opts=OPTS + ["DX9"], input='winDetectDx9.cxx') TargetAdd('libp3windisplay.dll', input='p3windisplay_composite1.obj') TargetAdd('libp3windisplay.dll', input='p3windisplay_windetectdx9.obj') TargetAdd('libp3windisplay.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3windisplay.dll', opts=['WINIMM', 'WINGDI', 'WINKERNEL', 'WINOLDNAMES', 'WINUSER', 'WINMM',"BIGOBJ"]) # # DIRECTORY: panda/metalibs/pandadx9/ # if GetTarget() == 'windows' and PkgSkip("DX9")==0 and not RUNTIME: OPTS=['DIR:panda/src/dxgsg9', 'BUILDING:PANDADX', 'DX9', 'NVIDIACG', 'CGDX9'] TargetAdd('p3dxgsg9_dxGraphicsStateGuardian9.obj', opts=OPTS, input='dxGraphicsStateGuardian9.cxx') TargetAdd('p3dxgsg9_composite1.obj', opts=OPTS, input='p3dxgsg9_composite1.cxx') OPTS=['DIR:panda/metalibs/pandadx9', 'BUILDING:PANDADX', 'DX9', 'NVIDIACG', 'CGDX9'] TargetAdd('pandadx9_pandadx9.obj', opts=OPTS, input='pandadx9.cxx') TargetAdd('libpandadx9.dll', input='pandadx9_pandadx9.obj') TargetAdd('libpandadx9.dll', input='p3dxgsg9_dxGraphicsStateGuardian9.obj') TargetAdd('libpandadx9.dll', input='p3dxgsg9_composite1.obj') TargetAdd('libpandadx9.dll', input='libp3windisplay.dll') TargetAdd('libpandadx9.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandadx9.dll', opts=['MODULE', 'ADVAPI', 'WINGDI', 'WINKERNEL', 'WINUSER', 'WINMM', 'DX9', 'NVIDIACG', 'CGDX9']) # # DIRECTORY: panda/src/egg/ # if not RUNTIME and not PkgSkip("EGG"): OPTS=['DIR:panda/src/egg', 'BUILDING:PANDAEGG', 'ZLIB', 'BISONPREFIX_eggyy', 'FLEXDASHI'] CreateFile(GetOutputDir()+"/include/parser.h") TargetAdd('p3egg_parser.obj', opts=OPTS, input='parser.yxx') TargetAdd('parser.h', input='p3egg_parser.obj', opts=['DEPENDENCYONLY']) TargetAdd('p3egg_lexer.obj', opts=OPTS, input='lexer.lxx') TargetAdd('p3egg_composite1.obj', opts=OPTS, input='p3egg_composite1.cxx') TargetAdd('p3egg_composite2.obj', opts=OPTS, input='p3egg_composite2.cxx') OPTS=['DIR:panda/src/egg', 'ZLIB'] IGATEFILES=GetDirectoryContents('panda/src/egg', ["*.h", "*_composite*.cxx"]) if "parser.h" in IGATEFILES: IGATEFILES.remove("parser.h") TargetAdd('libp3egg.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3egg.in', opts=['IMOD:panda3d.egg', 'ILIB:libp3egg', 'SRCDIR:panda/src/egg']) PyTargetAdd('p3egg_eggGroupNode_ext.obj', opts=OPTS, input='eggGroupNode_ext.cxx') # # DIRECTORY: panda/src/egg2pg/ # if not RUNTIME and not PkgSkip("EGG"): OPTS=['DIR:panda/src/egg2pg', 'BUILDING:PANDAEGG'] TargetAdd('p3egg2pg_composite1.obj', opts=OPTS, input='p3egg2pg_composite1.cxx') TargetAdd('p3egg2pg_composite2.obj', opts=OPTS, input='p3egg2pg_composite2.cxx') OPTS=['DIR:panda/src/egg2pg'] IGATEFILES=['load_egg_file.h'] TargetAdd('libp3egg2pg.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3egg2pg.in', opts=['IMOD:panda3d.egg', 'ILIB:libp3egg2pg', 'SRCDIR:panda/src/egg2pg']) # # DIRECTORY: panda/src/framework/ # if (not RUNTIME): deps = [] # Framework wants to link in a renderer when building statically, so tell it what is available. if GetLinkAllStatic(): deps = ['dtool_have_gl.dat', 'dtool_have_tinydisplay.dat', 'dtool_have_egg.dat'] if not PkgSkip("GL"): DefSymbol("FRAMEWORK", "HAVE_GL") if not PkgSkip("TINYDISPLAY"): DefSymbol("FRAMEWORK", "HAVE_TINYDISPLAY") if not PkgSkip("EGG"): DefSymbol("FRAMEWORK", "HAVE_EGG") OPTS=['DIR:panda/src/framework', 'BUILDING:FRAMEWORK', 'FRAMEWORK'] TargetAdd('p3framework_composite1.obj', opts=OPTS, input='p3framework_composite1.cxx', dep=deps) TargetAdd('libp3framework.dll', input='p3framework_composite1.obj') TargetAdd('libp3framework.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3framework.dll', opts=['ADVAPI']) # # DIRECTORY: panda/src/glgsg/ # if (not RUNTIME and PkgSkip("GL")==0): OPTS=['DIR:panda/src/glgsg', 'DIR:panda/src/glstuff', 'BUILDING:PANDAGL', 'GL', 'NVIDIACG'] TargetAdd('p3glgsg_config_glgsg.obj', opts=OPTS, input='config_glgsg.cxx') TargetAdd('p3glgsg_glgsg.obj', opts=OPTS, input='glgsg.cxx') # # DIRECTORY: panda/src/glesgsg/ # if (not RUNTIME and PkgSkip("GLES")==0): OPTS=['DIR:panda/src/glesgsg', 'DIR:panda/src/glstuff', 'BUILDING:PANDAGLES', 'GLES'] TargetAdd('p3glesgsg_config_glesgsg.obj', opts=OPTS, input='config_glesgsg.cxx') TargetAdd('p3glesgsg_glesgsg.obj', opts=OPTS, input='glesgsg.cxx') # # DIRECTORY: panda/src/gles2gsg/ # if (not RUNTIME and PkgSkip("GLES2")==0): OPTS=['DIR:panda/src/gles2gsg', 'DIR:panda/src/glstuff', 'BUILDING:PANDAGLES2', 'GLES2'] TargetAdd('p3gles2gsg_config_gles2gsg.obj', opts=OPTS, input='config_gles2gsg.cxx') TargetAdd('p3gles2gsg_gles2gsg.obj', opts=OPTS, input='gles2gsg.cxx') # # DIRECTORY: panda/metalibs/pandaegg/ # if not RUNTIME and not PkgSkip("EGG"): OPTS=['DIR:panda/metalibs/pandaegg', 'DIR:panda/src/egg', 'BUILDING:PANDAEGG'] TargetAdd('pandaegg_pandaegg.obj', opts=OPTS, input='pandaegg.cxx') TargetAdd('libpandaegg.dll', input='pandaegg_pandaegg.obj') TargetAdd('libpandaegg.dll', input='p3egg2pg_composite1.obj') TargetAdd('libpandaegg.dll', input='p3egg2pg_composite2.obj') TargetAdd('libpandaegg.dll', input='p3egg_composite1.obj') TargetAdd('libpandaegg.dll', input='p3egg_composite2.obj') TargetAdd('libpandaegg.dll', input='p3egg_parser.obj') TargetAdd('libpandaegg.dll', input='p3egg_lexer.obj') TargetAdd('libpandaegg.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandaegg.dll', opts=['ADVAPI']) OPTS=['DIR:panda/metalibs/pandaegg', 'DIR:panda/src/egg'] PyTargetAdd('egg_module.obj', input='libp3egg2pg.in') PyTargetAdd('egg_module.obj', input='libp3egg.in') PyTargetAdd('egg_module.obj', opts=OPTS) PyTargetAdd('egg_module.obj', opts=['IMOD:panda3d.egg', 'ILIB:egg', 'IMPORT:panda3d.core']) PyTargetAdd('egg.pyd', input='egg_module.obj') PyTargetAdd('egg.pyd', input='p3egg_eggGroupNode_ext.obj') PyTargetAdd('egg.pyd', input='libp3egg_igate.obj') PyTargetAdd('egg.pyd', input='libp3egg2pg_igate.obj') PyTargetAdd('egg.pyd', input='libpandaegg.dll') PyTargetAdd('egg.pyd', input='libp3interrogatedb.dll') PyTargetAdd('egg.pyd', input=COMMON_PANDA_LIBS) # # DIRECTORY: panda/src/x11display/ # if (GetTarget() not in ['windows', 'darwin'] and PkgSkip("X11")==0 and not RUNTIME): OPTS=['DIR:panda/src/x11display', 'BUILDING:PANDAX11', 'X11'] TargetAdd('p3x11display_composite1.obj', opts=OPTS, input='p3x11display_composite1.cxx') # # DIRECTORY: panda/src/glxdisplay/ # if (GetTarget() not in ['windows', 'darwin'] and PkgSkip("GL")==0 and PkgSkip("X11")==0 and not RUNTIME): OPTS=['DIR:panda/src/glxdisplay', 'BUILDING:PANDAGL', 'GL', 'NVIDIACG', 'CGGL'] TargetAdd('p3glxdisplay_composite1.obj', opts=OPTS, input='p3glxdisplay_composite1.cxx') OPTS=['DIR:panda/metalibs/pandagl', 'BUILDING:PANDAGL', 'GL', 'NVIDIACG', 'CGGL'] TargetAdd('pandagl_pandagl.obj', opts=OPTS, input='pandagl.cxx') TargetAdd('libpandagl.dll', input='p3x11display_composite1.obj') TargetAdd('libpandagl.dll', input='pandagl_pandagl.obj') TargetAdd('libpandagl.dll', input='p3glgsg_config_glgsg.obj') TargetAdd('libpandagl.dll', input='p3glgsg_glgsg.obj') TargetAdd('libpandagl.dll', input='p3glxdisplay_composite1.obj') TargetAdd('libpandagl.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandagl.dll', opts=['MODULE', 'GL', 'NVIDIACG', 'CGGL', 'X11']) # # DIRECTORY: panda/src/cocoadisplay/ # if (GetTarget() == 'darwin' and PkgSkip("COCOA")==0 and PkgSkip("GL")==0 and not RUNTIME): OPTS=['DIR:panda/src/cocoadisplay', 'BUILDING:PANDAGL', 'GL', 'NVIDIACG', 'CGGL'] TargetAdd('p3cocoadisplay_composite1.obj', opts=OPTS, input='p3cocoadisplay_composite1.mm') OPTS=['DIR:panda/metalibs/pandagl', 'BUILDING:PANDAGL', 'GL', 'NVIDIACG', 'CGGL'] TargetAdd('pandagl_pandagl.obj', opts=OPTS, input='pandagl.cxx') TargetAdd('libpandagl.dll', input='pandagl_pandagl.obj') TargetAdd('libpandagl.dll', input='p3glgsg_config_glgsg.obj') TargetAdd('libpandagl.dll', input='p3glgsg_glgsg.obj') TargetAdd('libpandagl.dll', input='p3cocoadisplay_composite1.obj') if (PkgSkip('PANDAFX')==0): TargetAdd('libpandagl.dll', input='libpandafx.dll') TargetAdd('libpandagl.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandagl.dll', opts=['MODULE', 'GL', 'NVIDIACG', 'CGGL', 'COCOA', 'CARBON']) # # DIRECTORY: panda/src/osxdisplay/ # elif (GetTarget() == 'darwin' and PkgSkip("CARBON")==0 and PkgSkip("GL")==0 and not RUNTIME): OPTS=['DIR:panda/src/osxdisplay', 'BUILDING:PANDAGL', 'GL', 'NVIDIACG', 'CGGL'] TargetAdd('p3osxdisplay_composite1.obj', opts=OPTS, input='p3osxdisplay_composite1.cxx') TargetAdd('p3osxdisplay_osxGraphicsWindow.obj', opts=OPTS, input='osxGraphicsWindow.mm') OPTS=['DIR:panda/metalibs/pandagl', 'BUILDING:PANDAGL', 'GL', 'NVIDIACG', 'CGGL'] TargetAdd('pandagl_pandagl.obj', opts=OPTS, input='pandagl.cxx') TargetAdd('libpandagl.dll', input='pandagl_pandagl.obj') TargetAdd('libpandagl.dll', input='p3glgsg_config_glgsg.obj') TargetAdd('libpandagl.dll', input='p3glgsg_glgsg.obj') TargetAdd('libpandagl.dll', input='p3osxdisplay_composite1.obj') TargetAdd('libpandagl.dll', input='p3osxdisplay_osxGraphicsWindow.obj') if (PkgSkip('PANDAFX')==0): TargetAdd('libpandagl.dll', input='libpandafx.dll') TargetAdd('libpandagl.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandagl.dll', opts=['MODULE', 'GL', 'NVIDIACG', 'CGGL', 'CARBON', 'AGL', 'COCOA']) # # DIRECTORY: panda/src/wgldisplay/ # if (GetTarget() == 'windows' and PkgSkip("GL")==0 and not RUNTIME): OPTS=['DIR:panda/src/wgldisplay', 'DIR:panda/src/glstuff', 'BUILDING:PANDAGL', 'NVIDIACG', 'CGGL'] TargetAdd('p3wgldisplay_composite1.obj', opts=OPTS, input='p3wgldisplay_composite1.cxx') OPTS=['DIR:panda/metalibs/pandagl', 'BUILDING:PANDAGL', 'NVIDIACG', 'CGGL'] TargetAdd('pandagl_pandagl.obj', opts=OPTS, input='pandagl.cxx') TargetAdd('libpandagl.dll', input='pandagl_pandagl.obj') TargetAdd('libpandagl.dll', input='p3glgsg_config_glgsg.obj') TargetAdd('libpandagl.dll', input='p3glgsg_glgsg.obj') TargetAdd('libpandagl.dll', input='p3wgldisplay_composite1.obj') TargetAdd('libpandagl.dll', input='libp3windisplay.dll') if (PkgSkip('PANDAFX')==0): TargetAdd('libpandagl.dll', input='libpandafx.dll') TargetAdd('libpandagl.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandagl.dll', opts=['MODULE', 'WINGDI', 'GL', 'WINKERNEL', 'WINOLDNAMES', 'WINUSER', 'WINMM', 'NVIDIACG', 'CGGL']) # # DIRECTORY: panda/src/egldisplay/ # if (PkgSkip("EGL")==0 and PkgSkip("GLES")==0 and PkgSkip("X11")==0 and not RUNTIME): DefSymbol('GLES', 'OPENGLES_1', '') OPTS=['DIR:panda/src/egldisplay', 'DIR:panda/src/glstuff', 'BUILDING:PANDAGLES', 'GLES', 'EGL'] TargetAdd('pandagles_egldisplay_composite1.obj', opts=OPTS, input='p3egldisplay_composite1.cxx') OPTS=['DIR:panda/metalibs/pandagles', 'BUILDING:PANDAGLES', 'GLES', 'EGL'] TargetAdd('pandagles_pandagles.obj', opts=OPTS, input='pandagles.cxx') TargetAdd('libpandagles.dll', input='p3x11display_composite1.obj') TargetAdd('libpandagles.dll', input='pandagles_pandagles.obj') TargetAdd('libpandagles.dll', input='p3glesgsg_config_glesgsg.obj') TargetAdd('libpandagles.dll', input='p3glesgsg_glesgsg.obj') TargetAdd('libpandagles.dll', input='pandagles_egldisplay_composite1.obj') TargetAdd('libpandagles.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandagles.dll', opts=['MODULE', 'GLES', 'EGL', 'X11']) # # DIRECTORY: panda/src/egldisplay/ # if (PkgSkip("EGL")==0 and PkgSkip("GLES2")==0 and PkgSkip("X11")==0 and not RUNTIME): DefSymbol('GLES2', 'OPENGLES_2', '') OPTS=['DIR:panda/src/egldisplay', 'DIR:panda/src/glstuff', 'BUILDING:PANDAGLES2', 'GLES2', 'EGL'] TargetAdd('pandagles2_egldisplay_composite1.obj', opts=OPTS, input='p3egldisplay_composite1.cxx') OPTS=['DIR:panda/metalibs/pandagles2', 'BUILDING:PANDAGLES2', 'GLES2', 'EGL'] TargetAdd('pandagles2_pandagles2.obj', opts=OPTS, input='pandagles2.cxx') TargetAdd('libpandagles2.dll', input='p3x11display_composite1.obj') TargetAdd('libpandagles2.dll', input='pandagles2_pandagles2.obj') TargetAdd('libpandagles2.dll', input='p3gles2gsg_config_gles2gsg.obj') TargetAdd('libpandagles2.dll', input='p3gles2gsg_gles2gsg.obj') TargetAdd('libpandagles2.dll', input='pandagles2_egldisplay_composite1.obj') TargetAdd('libpandagles2.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandagles2.dll', opts=['MODULE', 'GLES2', 'EGL', 'X11']) # # DIRECTORY: panda/src/ode/ # if (PkgSkip("ODE")==0 and not RUNTIME): OPTS=['DIR:panda/src/ode', 'BUILDING:PANDAODE', 'ODE'] TargetAdd('p3ode_composite1.obj', opts=OPTS, input='p3ode_composite1.cxx') TargetAdd('p3ode_composite2.obj', opts=OPTS, input='p3ode_composite2.cxx') TargetAdd('p3ode_composite3.obj', opts=OPTS, input='p3ode_composite3.cxx') OPTS=['DIR:panda/src/ode', 'ODE'] IGATEFILES=GetDirectoryContents('panda/src/ode', ["*.h", "*_composite*.cxx"]) IGATEFILES.remove("odeConvexGeom.h") IGATEFILES.remove("odeHelperStructs.h") TargetAdd('libpandaode.in', opts=OPTS, input=IGATEFILES) TargetAdd('libpandaode.in', opts=['IMOD:panda3d.ode', 'ILIB:libpandaode', 'SRCDIR:panda/src/ode']) PyTargetAdd('p3ode_ext_composite.obj', opts=OPTS, input='p3ode_ext_composite.cxx') # # DIRECTORY: panda/metalibs/pandaode/ # if (PkgSkip("ODE")==0 and not RUNTIME): OPTS=['DIR:panda/metalibs/pandaode', 'BUILDING:PANDAODE', 'ODE'] TargetAdd('pandaode_pandaode.obj', opts=OPTS, input='pandaode.cxx') TargetAdd('libpandaode.dll', input='pandaode_pandaode.obj') TargetAdd('libpandaode.dll', input='p3ode_composite1.obj') TargetAdd('libpandaode.dll', input='p3ode_composite2.obj') TargetAdd('libpandaode.dll', input='p3ode_composite3.obj') TargetAdd('libpandaode.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandaode.dll', opts=['WINUSER', 'ODE']) OPTS=['DIR:panda/metalibs/pandaode', 'ODE'] PyTargetAdd('ode_module.obj', input='libpandaode.in') PyTargetAdd('ode_module.obj', opts=OPTS) PyTargetAdd('ode_module.obj', opts=['IMOD:panda3d.ode', 'ILIB:ode', 'IMPORT:panda3d.core']) PyTargetAdd('ode.pyd', input='ode_module.obj') PyTargetAdd('ode.pyd', input='libpandaode_igate.obj') PyTargetAdd('ode.pyd', input='p3ode_ext_composite.obj') PyTargetAdd('ode.pyd', input='libpandaode.dll') PyTargetAdd('ode.pyd', input='libp3interrogatedb.dll') PyTargetAdd('ode.pyd', input=COMMON_PANDA_LIBS) PyTargetAdd('ode.pyd', opts=['WINUSER', 'ODE']) # # DIRECTORY: panda/src/bullet/ # if (PkgSkip("BULLET")==0 and not RUNTIME): OPTS=['DIR:panda/src/bullet', 'BUILDING:PANDABULLET', 'BULLET'] TargetAdd('p3bullet_composite.obj', opts=OPTS, input='p3bullet_composite.cxx') OPTS=['DIR:panda/src/bullet', 'BULLET'] IGATEFILES=GetDirectoryContents('panda/src/bullet', ["*.h", "*_composite*.cxx"]) TargetAdd('libpandabullet.in', opts=OPTS, input=IGATEFILES) TargetAdd('libpandabullet.in', opts=['IMOD:panda3d.bullet', 'ILIB:libpandabullet', 'SRCDIR:panda/src/bullet']) # # DIRECTORY: panda/metalibs/pandabullet/ # if (PkgSkip("BULLET")==0 and not RUNTIME): OPTS=['DIR:panda/metalibs/pandabullet', 'BUILDING:PANDABULLET', 'BULLET'] TargetAdd('pandabullet_pandabullet.obj', opts=OPTS, input='pandabullet.cxx') TargetAdd('libpandabullet.dll', input='pandabullet_pandabullet.obj') TargetAdd('libpandabullet.dll', input='p3bullet_composite.obj') TargetAdd('libpandabullet.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandabullet.dll', opts=['WINUSER', 'BULLET']) OPTS=['DIR:panda/metalibs/pandabullet', 'BULLET'] PyTargetAdd('bullet_module.obj', input='libpandabullet.in') PyTargetAdd('bullet_module.obj', opts=OPTS) PyTargetAdd('bullet_module.obj', opts=['IMOD:panda3d.bullet', 'ILIB:bullet', 'IMPORT:panda3d.core']) PyTargetAdd('bullet.pyd', input='bullet_module.obj') PyTargetAdd('bullet.pyd', input='libpandabullet_igate.obj') PyTargetAdd('bullet.pyd', input='libpandabullet.dll') PyTargetAdd('bullet.pyd', input='libp3interrogatedb.dll') PyTargetAdd('bullet.pyd', input=COMMON_PANDA_LIBS) PyTargetAdd('bullet.pyd', opts=['WINUSER', 'BULLET']) # # DIRECTORY: panda/src/physx/ # if (PkgSkip("PHYSX")==0): OPTS=['DIR:panda/src/physx', 'BUILDING:PANDAPHYSX', 'PHYSX', 'NOARCH:PPC'] TargetAdd('p3physx_composite.obj', opts=OPTS, input='p3physx_composite.cxx') OPTS=['DIR:panda/src/physx', 'PHYSX', 'NOARCH:PPC'] IGATEFILES=GetDirectoryContents('panda/src/physx', ["*.h", "*_composite*.cxx"]) TargetAdd('libpandaphysx.in', opts=OPTS, input=IGATEFILES) TargetAdd('libpandaphysx.in', opts=['IMOD:panda3d.physx', 'ILIB:libpandaphysx', 'SRCDIR:panda/src/physx']) # # DIRECTORY: panda/metalibs/pandaphysx/ # if (PkgSkip("PHYSX")==0): OPTS=['DIR:panda/metalibs/pandaphysx', 'BUILDING:PANDAPHYSX', 'PHYSX', 'NOARCH:PPC', 'PYTHON'] TargetAdd('pandaphysx_pandaphysx.obj', opts=OPTS, input='pandaphysx.cxx') TargetAdd('libpandaphysx.dll', input='pandaphysx_pandaphysx.obj') TargetAdd('libpandaphysx.dll', input='p3physx_composite.obj') TargetAdd('libpandaphysx.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandaphysx.dll', opts=['WINUSER', 'PHYSX', 'NOARCH:PPC', 'PYTHON']) OPTS=['DIR:panda/metalibs/pandaphysx', 'PHYSX', 'NOARCH:PPC'] PyTargetAdd('physx_module.obj', input='libpandaphysx.in') PyTargetAdd('physx_module.obj', opts=OPTS) PyTargetAdd('physx_module.obj', opts=['IMOD:panda3d.physx', 'ILIB:physx', 'IMPORT:panda3d.core']) PyTargetAdd('physx.pyd', input='physx_module.obj') PyTargetAdd('physx.pyd', input='libpandaphysx_igate.obj') PyTargetAdd('physx.pyd', input='libpandaphysx.dll') PyTargetAdd('physx.pyd', input='libp3interrogatedb.dll') PyTargetAdd('physx.pyd', input=COMMON_PANDA_LIBS) PyTargetAdd('physx.pyd', opts=['WINUSER', 'PHYSX', 'NOARCH:PPC']) # # DIRECTORY: panda/src/physics/ # if (PkgSkip("PANDAPHYSICS")==0) and (not RUNTIME): OPTS=['DIR:panda/src/physics', 'BUILDING:PANDAPHYSICS'] TargetAdd('p3physics_composite1.obj', opts=OPTS, input='p3physics_composite1.cxx') TargetAdd('p3physics_composite2.obj', opts=OPTS, input='p3physics_composite2.cxx') OPTS=['DIR:panda/src/physics'] IGATEFILES=GetDirectoryContents('panda/src/physics', ["*.h", "*_composite*.cxx"]) IGATEFILES.remove("forces.h") TargetAdd('libp3physics.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3physics.in', opts=['IMOD:panda3d.physics', 'ILIB:libp3physics', 'SRCDIR:panda/src/physics']) # # DIRECTORY: panda/src/particlesystem/ # if (PkgSkip("PANDAPHYSICS")==0) and (PkgSkip("PANDAPARTICLESYSTEM")==0) and (not RUNTIME): OPTS=['DIR:panda/src/particlesystem', 'BUILDING:PANDAPHYSICS'] TargetAdd('p3particlesystem_composite1.obj', opts=OPTS, input='p3particlesystem_composite1.cxx') TargetAdd('p3particlesystem_composite2.obj', opts=OPTS, input='p3particlesystem_composite2.cxx') OPTS=['DIR:panda/src/particlesystem'] IGATEFILES=GetDirectoryContents('panda/src/particlesystem', ["*.h", "*_composite*.cxx"]) IGATEFILES.remove('orientedParticle.h') IGATEFILES.remove('orientedParticleFactory.h') IGATEFILES.remove('particlefactories.h') IGATEFILES.remove('emitters.h') IGATEFILES.remove('particles.h') TargetAdd('libp3particlesystem.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3particlesystem.in', opts=['IMOD:panda3d.physics', 'ILIB:libp3particlesystem', 'SRCDIR:panda/src/particlesystem']) # # DIRECTORY: panda/metalibs/pandaphysics/ # if (PkgSkip("PANDAPHYSICS")==0) and (not RUNTIME): OPTS=['DIR:panda/metalibs/pandaphysics', 'BUILDING:PANDAPHYSICS'] TargetAdd('pandaphysics_pandaphysics.obj', opts=OPTS, input='pandaphysics.cxx') TargetAdd('libpandaphysics.dll', input='pandaphysics_pandaphysics.obj') TargetAdd('libpandaphysics.dll', input='p3physics_composite1.obj') TargetAdd('libpandaphysics.dll', input='p3physics_composite2.obj') TargetAdd('libpandaphysics.dll', input='p3particlesystem_composite1.obj') TargetAdd('libpandaphysics.dll', input='p3particlesystem_composite2.obj') TargetAdd('libpandaphysics.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandaphysics.dll', opts=['ADVAPI']) OPTS=['DIR:panda/metalibs/pandaphysics'] PyTargetAdd('physics_module.obj', input='libp3physics.in') if (PkgSkip("PANDAPARTICLESYSTEM")==0): PyTargetAdd('physics_module.obj', input='libp3particlesystem.in') PyTargetAdd('physics_module.obj', opts=OPTS) PyTargetAdd('physics_module.obj', opts=['IMOD:panda3d.physics', 'ILIB:physics', 'IMPORT:panda3d.core']) PyTargetAdd('physics.pyd', input='physics_module.obj') PyTargetAdd('physics.pyd', input='libp3physics_igate.obj') if (PkgSkip("PANDAPARTICLESYSTEM")==0): PyTargetAdd('physics.pyd', input='libp3particlesystem_igate.obj') PyTargetAdd('physics.pyd', input='libpandaphysics.dll') PyTargetAdd('physics.pyd', input='libp3interrogatedb.dll') PyTargetAdd('physics.pyd', input=COMMON_PANDA_LIBS) # # DIRECTORY: panda/src/speedtree/ # if (PkgSkip("SPEEDTREE")==0): OPTS=['DIR:panda/src/speedtree', 'BUILDING:PANDASPEEDTREE', 'SPEEDTREE'] TargetAdd('pandaspeedtree_composite1.obj', opts=OPTS, input='pandaspeedtree_composite1.cxx') IGATEFILES=GetDirectoryContents('panda/src/speedtree', ["*.h", "*_composite*.cxx"]) TargetAdd('libpandaspeedtree.in', opts=OPTS, input=IGATEFILES) TargetAdd('libpandaspeedtree.in', opts=['IMOD:libpandaspeedtree', 'ILIB:libpandaspeedtree', 'SRCDIR:panda/src/speedtree']) PyTargetAdd('libpandaspeedtree_module.obj', input='libpandaspeedtree.in') PyTargetAdd('libpandaspeedtree_module.obj', opts=OPTS) PyTargetAdd('libpandaspeedtree_module.obj', opts=['IMOD:libpandaspeedtree', 'ILIB:libpandaspeedtree']) TargetAdd('libpandaspeedtree.dll', input='pandaspeedtree_composite1.obj') PyTargetAdd('libpandaspeedtree.dll', input='libpandaspeedtree_igate.obj') TargetAdd('libpandaspeedtree.dll', input='libpandaspeedtree_module.obj') TargetAdd('libpandaspeedtree.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandaspeedtree.dll', opts=['SPEEDTREE']) if SDK["SPEEDTREEAPI"] == 'OpenGL': TargetAdd('libpandaspeedtree.dll', opts=['GL', 'NVIDIACG', 'CGGL']) elif SDK["SPEEDTREEAPI"] == 'DirectX9': TargetAdd('libpandaspeedtree.dll', opts=['DX9', 'NVIDIACG', 'CGDX9']) # # DIRECTORY: panda/src/testbed/ # if (not RTDIST and not RUNTIME and PkgSkip("PVIEW")==0): OPTS=['DIR:panda/src/testbed'] TargetAdd('pview_pview.obj', opts=OPTS, input='pview.cxx') TargetAdd('pview.exe', input='pview_pview.obj') TargetAdd('pview.exe', input='libp3framework.dll') if not PkgSkip("EGG"): TargetAdd('pview.exe', input='libpandaegg.dll') TargetAdd('pview.exe', input=COMMON_PANDA_LIBS) TargetAdd('pview.exe', opts=['ADVAPI', 'WINSOCK2', 'WINSHELL']) if GetLinkAllStatic() and not PkgSkip("GL"): TargetAdd('pview.exe', input='libpandagl.dll') # # DIRECTORY: panda/src/android/ # if (not RUNTIME and GetTarget() == 'android'): OPTS=['DIR:panda/src/android'] TargetAdd('org/panda3d/android/NativeIStream.class', opts=OPTS, input='NativeIStream.java') TargetAdd('org/panda3d/android/NativeOStream.class', opts=OPTS, input='NativeOStream.java') TargetAdd('org/panda3d/android/PandaActivity.class', opts=OPTS, input='PandaActivity.java') TargetAdd('org/panda3d/android/PythonActivity.class', opts=OPTS, input='PythonActivity.java') TargetAdd('p3android_composite1.obj', opts=OPTS, input='p3android_composite1.cxx') TargetAdd('libp3android.dll', input='p3android_composite1.obj') TargetAdd('libp3android.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3android.dll', opts=['JNIGRAPHICS']) TargetAdd('android_native_app_glue.obj', opts=OPTS + ['NOHIDDEN'], input='android_native_app_glue.c') TargetAdd('android_main.obj', opts=OPTS, input='android_main.cxx') if (not RTDIST and PkgSkip("PVIEW")==0): TargetAdd('libpview_pview.obj', opts=OPTS, input='pview.cxx') TargetAdd('libpview.dll', input='android_native_app_glue.obj') TargetAdd('libpview.dll', input='android_main.obj') TargetAdd('libpview.dll', input='libpview_pview.obj') TargetAdd('libpview.dll', input='libp3framework.dll') if not PkgSkip("EGG"): TargetAdd('libpview.dll', input='libpandaegg.dll') TargetAdd('libpview.dll', input='libp3android.dll') TargetAdd('libpview.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpview.dll', opts=['MODULE', 'ANDROID']) if (not RTDIST and PkgSkip("PYTHON")==0): OPTS += ['PYTHON'] TargetAdd('ppython_ppython.obj', opts=OPTS, input='python_main.cxx') TargetAdd('libppython.dll', input='android_native_app_glue.obj') TargetAdd('libppython.dll', input='android_main.obj') TargetAdd('libppython.dll', input='ppython_ppython.obj') TargetAdd('libppython.dll', input='libp3framework.dll') TargetAdd('libppython.dll', input='libp3android.dll') TargetAdd('libppython.dll', input=COMMON_PANDA_LIBS) TargetAdd('libppython.dll', opts=['MODULE', 'ANDROID']) # # DIRECTORY: panda/src/androiddisplay/ # if (GetTarget() == 'android' and PkgSkip("EGL")==0 and PkgSkip("GLES")==0 and not RUNTIME): DefSymbol('GLES', 'OPENGLES_1', '') OPTS=['DIR:panda/src/androiddisplay', 'DIR:panda/src/glstuff', 'BUILDING:PANDAGLES', 'GLES', 'EGL'] TargetAdd('pandagles_androiddisplay_composite1.obj', opts=OPTS, input='p3androiddisplay_composite1.cxx') OPTS=['DIR:panda/metalibs/pandagles', 'BUILDING:PANDAGLES', 'GLES', 'EGL'] TargetAdd('pandagles_pandagles.obj', opts=OPTS, input='pandagles.cxx') TargetAdd('libpandagles.dll', input='pandagles_pandagles.obj') TargetAdd('libpandagles.dll', input='p3glesgsg_config_glesgsg.obj') TargetAdd('libpandagles.dll', input='p3glesgsg_glesgsg.obj') TargetAdd('libpandagles.dll', input='pandagles_androiddisplay_composite1.obj') TargetAdd('libpandagles.dll', input='libp3android.dll') TargetAdd('libpandagles.dll', input=COMMON_PANDA_LIBS) TargetAdd('libpandagles.dll', opts=['MODULE', 'GLES', 'EGL']) # # DIRECTORY: panda/src/tinydisplay/ # if (not RUNTIME and (GetTarget() in ('windows', 'darwin') or PkgSkip("X11")==0) and PkgSkip("TINYDISPLAY")==0): OPTS=['DIR:panda/src/tinydisplay', 'BUILDING:TINYDISPLAY'] TargetAdd('p3tinydisplay_composite1.obj', opts=OPTS, input='p3tinydisplay_composite1.cxx') TargetAdd('p3tinydisplay_composite2.obj', opts=OPTS, input='p3tinydisplay_composite2.cxx') TargetAdd('p3tinydisplay_ztriangle_1.obj', opts=OPTS, input='ztriangle_1.cxx') TargetAdd('p3tinydisplay_ztriangle_2.obj', opts=OPTS, input='ztriangle_2.cxx') TargetAdd('p3tinydisplay_ztriangle_3.obj', opts=OPTS, input='ztriangle_3.cxx') TargetAdd('p3tinydisplay_ztriangle_4.obj', opts=OPTS, input='ztriangle_4.cxx') TargetAdd('p3tinydisplay_ztriangle_table.obj', opts=OPTS, input='ztriangle_table.cxx') if GetTarget() == 'darwin': TargetAdd('p3tinydisplay_tinyOsxGraphicsWindow.obj', opts=OPTS, input='tinyOsxGraphicsWindow.mm') TargetAdd('libp3tinydisplay.dll', input='p3tinydisplay_tinyOsxGraphicsWindow.obj') TargetAdd('libp3tinydisplay.dll', opts=['CARBON', 'AGL', 'COCOA']) elif GetTarget() == 'windows': TargetAdd('libp3tinydisplay.dll', input='libp3windisplay.dll') TargetAdd('libp3tinydisplay.dll', opts=['WINIMM', 'WINGDI', 'WINKERNEL', 'WINOLDNAMES', 'WINUSER', 'WINMM']) else: TargetAdd('libp3tinydisplay.dll', input='p3x11display_composite1.obj') TargetAdd('libp3tinydisplay.dll', opts=['X11']) TargetAdd('libp3tinydisplay.dll', input='p3tinydisplay_composite1.obj') TargetAdd('libp3tinydisplay.dll', input='p3tinydisplay_composite2.obj') TargetAdd('libp3tinydisplay.dll', input='p3tinydisplay_ztriangle_1.obj') TargetAdd('libp3tinydisplay.dll', input='p3tinydisplay_ztriangle_2.obj') TargetAdd('libp3tinydisplay.dll', input='p3tinydisplay_ztriangle_3.obj') TargetAdd('libp3tinydisplay.dll', input='p3tinydisplay_ztriangle_4.obj') TargetAdd('libp3tinydisplay.dll', input='p3tinydisplay_ztriangle_table.obj') TargetAdd('libp3tinydisplay.dll', input=COMMON_PANDA_LIBS) # # DIRECTORY: direct/src/directbase/ # if (PkgSkip("DIRECT")==0): OPTS=['DIR:direct/src/directbase'] TargetAdd('p3directbase_directbase.obj', opts=OPTS+['BUILDING:DIRECT'], input='directbase.cxx') # # DIRECTORY: direct/src/dcparser/ # if (PkgSkip("DIRECT")==0): OPTS=['DIR:direct/src/dcparser', 'BUILDING:DIRECT_DCPARSER', 'WITHINPANDA', 'BISONPREFIX_dcyy'] CreateFile(GetOutputDir()+"/include/dcParser.h") PyTargetAdd('p3dcparser_dcParser.obj', opts=OPTS, input='dcParser.yxx') #TargetAdd('dcParser.h', input='p3dcparser_dcParser.obj', opts=['DEPENDENCYONLY']) PyTargetAdd('p3dcparser_dcLexer.obj', opts=OPTS, input='dcLexer.lxx') PyTargetAdd('p3dcparser_composite1.obj', opts=OPTS, input='p3dcparser_composite1.cxx') PyTargetAdd('p3dcparser_composite2.obj', opts=OPTS, input='p3dcparser_composite2.cxx') OPTS=['DIR:direct/src/dcparser', 'WITHINPANDA'] IGATEFILES=GetDirectoryContents('direct/src/dcparser', ["*.h", "*_composite*.cxx"]) if "dcParser.h" in IGATEFILES: IGATEFILES.remove("dcParser.h") if "dcmsgtypes.h" in IGATEFILES: IGATEFILES.remove('dcmsgtypes.h') TargetAdd('libp3dcparser.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3dcparser.in', opts=['IMOD:panda3d.direct', 'ILIB:libp3dcparser', 'SRCDIR:direct/src/dcparser']) # # DIRECTORY: direct/src/deadrec/ # if (PkgSkip("DIRECT")==0): OPTS=['DIR:direct/src/deadrec', 'BUILDING:DIRECT'] TargetAdd('p3deadrec_composite1.obj', opts=OPTS, input='p3deadrec_composite1.cxx') OPTS=['DIR:direct/src/deadrec'] IGATEFILES=GetDirectoryContents('direct/src/deadrec', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3deadrec.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3deadrec.in', opts=['IMOD:panda3d.direct', 'ILIB:libp3deadrec', 'SRCDIR:direct/src/deadrec']) # # DIRECTORY: direct/src/distributed/ # if (PkgSkip("DIRECT")==0): OPTS=['DIR:direct/src/distributed', 'DIR:direct/src/dcparser', 'WITHINPANDA', 'BUILDING:DIRECT', 'OPENSSL'] TargetAdd('p3distributed_config_distributed.obj', opts=OPTS, input='config_distributed.cxx') PyTargetAdd('p3distributed_cConnectionRepository.obj', opts=OPTS, input='cConnectionRepository.cxx') PyTargetAdd('p3distributed_cDistributedSmoothNodeBase.obj', opts=OPTS, input='cDistributedSmoothNodeBase.cxx') OPTS=['DIR:direct/src/distributed', 'WITHINPANDA', 'OPENSSL'] IGATEFILES=GetDirectoryContents('direct/src/distributed', ["*.h", "*.cxx"]) TargetAdd('libp3distributed.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3distributed.in', opts=['IMOD:panda3d.direct', 'ILIB:libp3distributed', 'SRCDIR:direct/src/distributed']) # # DIRECTORY: direct/src/interval/ # if (PkgSkip("DIRECT")==0): OPTS=['DIR:direct/src/interval', 'BUILDING:DIRECT'] TargetAdd('p3interval_composite1.obj', opts=OPTS, input='p3interval_composite1.cxx') OPTS=['DIR:direct/src/interval'] IGATEFILES=GetDirectoryContents('direct/src/interval', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3interval.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3interval.in', opts=['IMOD:panda3d.direct', 'ILIB:libp3interval', 'SRCDIR:direct/src/interval']) # # DIRECTORY: direct/src/showbase/ # if (PkgSkip("DIRECT")==0): OPTS=['DIR:direct/src/showbase', 'BUILDING:DIRECT'] TargetAdd('p3showbase_showBase.obj', opts=OPTS, input='showBase.cxx') if GetTarget() == 'darwin': TargetAdd('p3showbase_showBase_assist.obj', opts=OPTS, input='showBase_assist.mm') OPTS=['DIR:direct/src/showbase'] IGATEFILES=GetDirectoryContents('direct/src/showbase', ["*.h", "showBase.cxx"]) TargetAdd('libp3showbase.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3showbase.in', opts=['IMOD:panda3d.direct', 'ILIB:libp3showbase', 'SRCDIR:direct/src/showbase']) # # DIRECTORY: direct/src/motiontrail/ # if (PkgSkip("DIRECT")==0): OPTS=['DIR:direct/src/motiontrail', 'BUILDING:DIRECT'] TargetAdd('p3motiontrail_cMotionTrail.obj', opts=OPTS, input='cMotionTrail.cxx') TargetAdd('p3motiontrail_config_motiontrail.obj', opts=OPTS, input='config_motiontrail.cxx') OPTS=['DIR:direct/src/motiontrail'] IGATEFILES=GetDirectoryContents('direct/src/motiontrail', ["*.h", "cMotionTrail.cxx"]) TargetAdd('libp3motiontrail.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3motiontrail.in', opts=['IMOD:panda3d.direct', 'ILIB:libp3motiontrail', 'SRCDIR:direct/src/motiontrail']) # # DIRECTORY: direct/metalibs/direct/ # if (PkgSkip("DIRECT")==0): TargetAdd('libp3direct.dll', input='p3directbase_directbase.obj') TargetAdd('libp3direct.dll', input='p3showbase_showBase.obj') if GetTarget() == 'darwin': TargetAdd('libp3direct.dll', input='p3showbase_showBase_assist.obj') TargetAdd('libp3direct.dll', input='p3deadrec_composite1.obj') TargetAdd('libp3direct.dll', input='p3interval_composite1.obj') TargetAdd('libp3direct.dll', input='p3motiontrail_config_motiontrail.obj') TargetAdd('libp3direct.dll', input='p3motiontrail_cMotionTrail.obj') TargetAdd('libp3direct.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3direct.dll', opts=['ADVAPI', 'OPENSSL', 'WINUSER', 'WINGDI']) PyTargetAdd('direct_module.obj', input='libp3dcparser.in') PyTargetAdd('direct_module.obj', input='libp3showbase.in') PyTargetAdd('direct_module.obj', input='libp3deadrec.in') PyTargetAdd('direct_module.obj', input='libp3interval.in') PyTargetAdd('direct_module.obj', input='libp3distributed.in') PyTargetAdd('direct_module.obj', input='libp3motiontrail.in') PyTargetAdd('direct_module.obj', opts=['IMOD:panda3d.direct', 'ILIB:direct', 'IMPORT:panda3d.core']) PyTargetAdd('direct.pyd', input='libp3dcparser_igate.obj') PyTargetAdd('direct.pyd', input='libp3showbase_igate.obj') PyTargetAdd('direct.pyd', input='libp3deadrec_igate.obj') PyTargetAdd('direct.pyd', input='libp3interval_igate.obj') PyTargetAdd('direct.pyd', input='libp3distributed_igate.obj') PyTargetAdd('direct.pyd', input='libp3motiontrail_igate.obj') # These are part of direct.pyd, not libp3direct.dll, because they rely on # the Python libraries. If a C++ user needs these modules, we can move them # back and filter out the Python-specific code. PyTargetAdd('direct.pyd', input='p3dcparser_composite1.obj') PyTargetAdd('direct.pyd', input='p3dcparser_composite2.obj') PyTargetAdd('direct.pyd', input='p3dcparser_dcParser.obj') PyTargetAdd('direct.pyd', input='p3dcparser_dcLexer.obj') PyTargetAdd('direct.pyd', input='p3distributed_config_distributed.obj') PyTargetAdd('direct.pyd', input='p3distributed_cConnectionRepository.obj') PyTargetAdd('direct.pyd', input='p3distributed_cDistributedSmoothNodeBase.obj') PyTargetAdd('direct.pyd', input='direct_module.obj') PyTargetAdd('direct.pyd', input='libp3direct.dll') PyTargetAdd('direct.pyd', input='libp3interrogatedb.dll') PyTargetAdd('direct.pyd', input=COMMON_PANDA_LIBS) PyTargetAdd('direct.pyd', opts=['OPENSSL', 'WINUSER', 'WINGDI', 'WINSOCK2']) # # DIRECTORY: direct/src/dcparse/ # if (PkgSkip("PYTHON")==0 and PkgSkip("DIRECT")==0 and not RTDIST and not RUNTIME): OPTS=['DIR:direct/src/dcparse', 'DIR:direct/src/dcparser', 'WITHINPANDA', 'ADVAPI'] PyTargetAdd('dcparse_dcparse.obj', opts=OPTS, input='dcparse.cxx') PyTargetAdd('p3dcparse.exe', input='p3dcparser_composite1.obj') PyTargetAdd('p3dcparse.exe', input='p3dcparser_composite2.obj') PyTargetAdd('p3dcparse.exe', input='p3dcparser_dcParser.obj') PyTargetAdd('p3dcparse.exe', input='p3dcparser_dcLexer.obj') PyTargetAdd('p3dcparse.exe', input='dcparse_dcparse.obj') PyTargetAdd('p3dcparse.exe', input='libp3direct.dll') PyTargetAdd('p3dcparse.exe', input=COMMON_PANDA_LIBS) PyTargetAdd('p3dcparse.exe', input='libp3pystub.lib') PyTargetAdd('p3dcparse.exe', opts=['ADVAPI']) # # DIRECTORY: direct/src/plugin/ # if (RTDIST or RUNTIME): # Explicitly define this as we don't include dtool_config.h here. if GetTarget() not in ('windows', 'darwin'): DefSymbol("RUNTIME", "HAVE_X11", "1") OPTS=['DIR:direct/src/plugin', 'BUILDING:P3D_PLUGIN', 'RUNTIME', 'OPENSSL'] TargetAdd('plugin_common.obj', opts=OPTS, input='plugin_common_composite1.cxx') OPTS += ['ZLIB', 'MSIMG'] TargetAdd('plugin_plugin.obj', opts=OPTS, input='p3d_plugin_composite1.cxx') TargetAdd('plugin_mkdir_complete.obj', opts=OPTS, input='mkdir_complete.cxx') TargetAdd('plugin_wstring_encode.obj', opts=OPTS, input='wstring_encode.cxx') TargetAdd('plugin_parse_color.obj', opts=OPTS, input='parse_color.cxx') TargetAdd('plugin_get_twirl_data.obj', opts=OPTS, input='get_twirl_data.cxx') TargetAdd('plugin_find_root_dir.obj', opts=OPTS, input='find_root_dir.cxx') if GetTarget() == 'darwin': TargetAdd('plugin_find_root_dir_assist.obj', opts=OPTS, input='find_root_dir_assist.mm') TargetAdd('plugin_binaryXml.obj', opts=OPTS, input='binaryXml.cxx') TargetAdd('plugin_fileSpec.obj', opts=OPTS, input='fileSpec.cxx') TargetAdd('plugin_handleStream.obj', opts=OPTS, input='handleStream.cxx') TargetAdd('plugin_handleStreamBuf.obj', opts=OPTS, input='handleStreamBuf.cxx') if (RTDIST): for fname in ("p3d_plugin.dll", "libp3d_plugin_static.ilb"): TargetAdd(fname, input='plugin_plugin.obj') TargetAdd(fname, input='plugin_mkdir_complete.obj') TargetAdd(fname, input='plugin_wstring_encode.obj') TargetAdd(fname, input='plugin_parse_color.obj') TargetAdd(fname, input='plugin_find_root_dir.obj') if GetTarget() == 'darwin': TargetAdd(fname, input='plugin_find_root_dir_assist.obj') TargetAdd(fname, input='plugin_fileSpec.obj') TargetAdd(fname, input='plugin_binaryXml.obj') TargetAdd(fname, input='plugin_handleStream.obj') TargetAdd(fname, input='plugin_handleStreamBuf.obj') TargetAdd(fname, input='libp3tinyxml.ilb') if GetTarget() == 'darwin': TargetAdd(fname, input='libp3subprocbuffer.ilb') TargetAdd(fname, opts=['OPENSSL', 'ZLIB', 'X11', 'ADVAPI', 'WINUSER', 'WINGDI', 'WINSHELL', 'WINCOMCTL', 'WINOLE', 'MSIMG']) TargetAdd("libp3d_plugin_static.ilb", input='plugin_get_twirl_data.obj') if (PkgSkip("PYTHON")==0 and RTDIST): # Freeze VFSImporter and its dependency modules into p3dpython. # Mark panda3d.core as a dependency to make sure to build that first. TargetAdd('p3dpython_frozen.obj', input='VFSImporter.py', opts=['DIR:direct/src/showbase', 'FREEZE_STARTUP']) TargetAdd('p3dpython_frozen.obj', dep='core.pyd') OPTS += ['PYTHON'] TargetAdd('p3dpython_p3dpython_composite1.obj', opts=OPTS, input='p3dpython_composite1.cxx') TargetAdd('p3dpython_p3dPythonMain.obj', opts=OPTS, input='p3dPythonMain.cxx') TargetAdd('p3dpython.exe', input='p3dpython_p3dpython_composite1.obj') TargetAdd('p3dpython.exe', input='p3dpython_p3dPythonMain.obj') TargetAdd('p3dpython.exe', input='p3dpython_frozen.obj') TargetAdd('p3dpython.exe', input=COMMON_PANDA_LIBS) TargetAdd('p3dpython.exe', input='libp3tinyxml.ilb') TargetAdd('p3dpython.exe', input='libp3interrogatedb.dll') TargetAdd('p3dpython.exe', opts=['PYTHON', 'WINUSER']) TargetAdd('libp3dpython.dll', input='p3dpython_p3dpython_composite1.obj') TargetAdd('libp3dpython.dll', input='p3dpython_frozen.obj') TargetAdd('libp3dpython.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3dpython.dll', input='libp3tinyxml.ilb') TargetAdd('libp3dpython.dll', input='libp3interrogatedb.dll') TargetAdd('libp3dpython.dll', opts=['PYTHON', 'WINUSER']) if GetTarget() == 'windows': DefSymbol("NON_CONSOLE", "NON_CONSOLE", "") OPTS.append("NON_CONSOLE") TargetAdd('p3dpythonw_p3dpython_composite1.obj', opts=OPTS, input='p3dpython_composite1.cxx') TargetAdd('p3dpythonw_p3dPythonMain.obj', opts=OPTS, input='p3dPythonMain.cxx') TargetAdd('p3dpythonw.exe', input='p3dpythonw_p3dpython_composite1.obj') TargetAdd('p3dpythonw.exe', input='p3dpythonw_p3dPythonMain.obj') TargetAdd('p3dpythonw.exe', input='p3dpython_frozen.obj') TargetAdd('p3dpythonw.exe', input=COMMON_PANDA_LIBS) TargetAdd('p3dpythonw.exe', input='libp3tinyxml.ilb') TargetAdd('p3dpythonw.exe', input='libp3interrogatedb.dll') TargetAdd('p3dpythonw.exe', opts=['SUBSYSTEM:WINDOWS', 'WINUSER']) if (PkgSkip("OPENSSL")==0 and RTDIST and False): OPTS=['DIR:direct/src/plugin', 'DIR:panda/src/express', 'OPENSSL'] if GetTarget() == 'darwin': OPTS += ['OPT:2'] if (PkgSkip("FLTK")==0): OPTS.append("FLTK") TargetAdd('plugin_p3dCert.obj', opts=OPTS, input='p3dCert.cxx') TargetAdd('plugin_p3dCert_strings.obj', opts=OPTS, input='p3dCert_strings.cxx') TargetAdd('p3dcert.exe', input='plugin_mkdir_complete.obj') TargetAdd('p3dcert.exe', input='plugin_wstring_encode.obj') TargetAdd('p3dcert.exe', input='plugin_p3dCert.obj') TargetAdd('p3dcert.exe', input='plugin_p3dCert_strings.obj') OPTS=['SUBSYSTEM:WINDOWS', 'OPENSSL', 'FLTK', 'X11', 'WINCOMCTL', 'WINSOCK', 'WINGDI', 'WINUSER', 'ADVAPI', 'WINOLE', 'WINSHELL', 'SUBSYSTEM:WINDOWS'] if GetTarget() == 'darwin': OPTS += ['OPT:2'] TargetAdd('p3dcert.exe', opts=OPTS) elif (PkgSkip("WX")==0): OPTS += ["WX", "RTTI"] TargetAdd('plugin_p3dCert.obj', opts=OPTS, input='p3dCert_wx.cxx') TargetAdd('p3dcert.exe', input='plugin_mkdir_complete.obj') TargetAdd('p3dcert.exe', input='plugin_wstring_encode.obj') TargetAdd('p3dcert.exe', input='plugin_p3dCert.obj') OPTS=['SUBSYSTEM:WINDOWS', 'OPENSSL', 'WX', 'CARBON', 'WINOLE', 'WINOLEAUT', 'WINUSER', 'ADVAPI', 'WINSHELL', 'WINCOMCTL', 'WINGDI', 'WINCOMDLG'] if GetTarget() == "darwin": OPTS += ['GL', 'OPT:2'] TargetAdd('p3dcert.exe', opts=OPTS) # # DIRECTORY: direct/src/plugin_npapi/ # if RUNTIME: OPTS=['DIR:direct/src/plugin_npapi', 'RUNTIME', 'GTK2'] if GetTarget() == 'windows': nppanda3d_rc = {"name" : "Panda3D Game Engine Plug-in", "version" : VERSION, "description" : "Runs 3-D games and interactive applets", "filename" : "nppanda3d.dll", "mimetype" : "application/x-panda3d", "extension" : "p3d", "filedesc" : "Panda3D applet"} TargetAdd('nppanda3d.res', opts=OPTS, winrc=nppanda3d_rc) elif GetTarget() == 'darwin': TargetAdd('nppanda3d.rsrc', opts=OPTS, input='nppanda3d.r') OPTS += ['GTK2'] TargetAdd('plugin_npapi_nppanda3d_composite1.obj', opts=OPTS, input='nppanda3d_composite1.cxx') TargetAdd('nppanda3d.plugin', input='plugin_common.obj') TargetAdd('nppanda3d.plugin', input='plugin_parse_color.obj') TargetAdd('nppanda3d.plugin', input='plugin_get_twirl_data.obj') TargetAdd('nppanda3d.plugin', input='plugin_wstring_encode.obj') TargetAdd('nppanda3d.plugin', input='plugin_npapi_nppanda3d_composite1.obj') if GetTarget() == 'windows': TargetAdd('nppanda3d.plugin', input='nppanda3d.res') TargetAdd('nppanda3d.plugin', input='nppanda3d.def', ipath=OPTS) elif GetTarget() == 'darwin': TargetAdd('nppanda3d.plugin', input='nppanda3d.rsrc') TargetAdd('nppanda3d.plugin', input='nppanda3d.plist', ipath=OPTS) TargetAdd('nppanda3d.plugin', input='plugin_find_root_dir_assist.obj') TargetAdd('nppanda3d.plugin', input='libp3tinyxml.ilb') TargetAdd('nppanda3d.plugin', opts=['OPENSSL', 'WINGDI', 'WINUSER', 'WINSHELL', 'WINOLE', 'CARBON']) # # DIRECTORY: direct/src/plugin_activex/ # if (RUNTIME and GetTarget() == 'windows' and PkgSkip("MFC")==0): OPTS=['DIR:direct/src/plugin_activex', 'RUNTIME', 'ACTIVEX', 'MFC'] DefSymbol('ACTIVEX', '_USRDLL', '') DefSymbol('ACTIVEX', '_WINDLL', '') DefSymbol('ACTIVEX', '_AFXDLL', '') DefSymbol('ACTIVEX', '_MBCS', '') TargetAdd('P3DActiveX.tlb', opts=OPTS, input='P3DActiveX.idl') TargetAdd('P3DActiveX.res', opts=OPTS, input='P3DActiveX.rc') TargetAdd('plugin_activex_p3dactivex_composite1.obj', opts=OPTS, input='p3dactivex_composite1.cxx') TargetAdd('p3dactivex.ocx', input='plugin_common.obj') TargetAdd('p3dactivex.ocx', input='plugin_parse_color.obj') TargetAdd('p3dactivex.ocx', input='plugin_get_twirl_data.obj') TargetAdd('p3dactivex.ocx', input='plugin_wstring_encode.obj') TargetAdd('p3dactivex.ocx', input='plugin_activex_p3dactivex_composite1.obj') TargetAdd('p3dactivex.ocx', input='P3DActiveX.res') TargetAdd('p3dactivex.ocx', input='P3DActiveX.def', ipath=OPTS) TargetAdd('p3dactivex.ocx', input='libp3tinyxml.ilb') TargetAdd('p3dactivex.ocx', opts=['MFC', 'WINSOCK2', 'OPENSSL', 'WINGDI', 'WINUSER']) # # DIRECTORY: direct/src/plugin_standalone/ # if (RUNTIME): OPTS=['DIR:direct/src/plugin_standalone', 'RUNTIME', 'OPENSSL'] TargetAdd('plugin_standalone_panda3d.obj', opts=OPTS, input='panda3d.cxx') TargetAdd('plugin_standalone_panda3dBase.obj', opts=OPTS, input='panda3dBase.cxx') if GetTarget() == 'windows': panda3d_rc = {"name" : "Panda3D Game Engine Plug-in", "version" : VERSION, "description" : "Runs 3-D games and interactive applets", "filename" : "panda3d.exe", "mimetype" : "application/x-panda3d", "extension" : "p3d", "filedesc" : "Panda3D applet", "icon" : "panda3d.ico"} TargetAdd('panda3d.res', opts=OPTS, winrc=panda3d_rc) TargetAdd('plugin_standalone_panda3dMain.obj', opts=OPTS, input='panda3dMain.cxx') TargetAdd('panda3d.exe', input='plugin_standalone_panda3d.obj') TargetAdd('panda3d.exe', input='plugin_standalone_panda3dMain.obj') TargetAdd('panda3d.exe', input='plugin_standalone_panda3dBase.obj') TargetAdd('panda3d.exe', input='plugin_common.obj') TargetAdd('panda3d.exe', input='plugin_wstring_encode.obj') if GetTarget() == 'darwin': TargetAdd('panda3d.exe', input='plugin_find_root_dir_assist.obj') elif GetTarget() == 'windows': TargetAdd('panda3d.exe', input='panda3d.res') TargetAdd('panda3d.exe', input='libpandaexpress.dll') TargetAdd('panda3d.exe', input='libp3dtoolconfig.dll') TargetAdd('panda3d.exe', input='libp3dtool.dll') #TargetAdd('panda3d.exe', input='libp3pystub.lib') TargetAdd('panda3d.exe', input='libp3tinyxml.ilb') TargetAdd('panda3d.exe', opts=['NOICON', 'OPENSSL', 'ZLIB', 'WINGDI', 'WINUSER', 'WINSHELL', 'ADVAPI', 'WINSOCK2', 'WINOLE', 'CARBON']) if (GetTarget() == 'darwin'): TargetAdd('plugin_standalone_panda3dMac.obj', opts=OPTS, input='panda3dMac.cxx') TargetAdd('Panda3D.app', input='plugin_standalone_panda3d.obj') TargetAdd('Panda3D.app', input='plugin_standalone_panda3dMac.obj') TargetAdd('Panda3D.app', input='plugin_standalone_panda3dBase.obj') TargetAdd('Panda3D.app', input='plugin_common.obj') TargetAdd('Panda3D.app', input='plugin_find_root_dir_assist.obj') TargetAdd('Panda3D.app', input='libpandaexpress.dll') TargetAdd('Panda3D.app', input='libp3dtoolconfig.dll') TargetAdd('Panda3D.app', input='libp3dtool.dll') #TargetAdd('Panda3D.app', input='libp3pystub.lib') TargetAdd('Panda3D.app', input='libp3tinyxml.ilb') TargetAdd('Panda3D.app', input='panda3d_mac.plist', ipath=OPTS) TargetAdd('Panda3D.app', input='models/plugin_images/panda3d.icns') TargetAdd('Panda3D.app', opts=['OPENSSL', 'ZLIB', 'WINGDI', 'WINUSER', 'WINSHELL', 'ADVAPI', 'WINSOCK2', 'WINOLE', 'CARBON']) elif (GetTarget() == 'windows'): TargetAdd('plugin_standalone_panda3dWinMain.obj', opts=OPTS, input='panda3dWinMain.cxx') TargetAdd('panda3dw.exe', input='plugin_standalone_panda3d.obj') TargetAdd('panda3dw.exe', input='plugin_standalone_panda3dWinMain.obj') TargetAdd('panda3dw.exe', input='plugin_standalone_panda3dBase.obj') TargetAdd('panda3dw.exe', input='plugin_wstring_encode.obj') TargetAdd('panda3dw.exe', input='plugin_common.obj') TargetAdd('panda3dw.exe', input='libpandaexpress.dll') TargetAdd('panda3dw.exe', input='libp3dtoolconfig.dll') TargetAdd('panda3dw.exe', input='libp3dtool.dll') #TargetAdd('panda3dw.exe', input='libp3pystub.lib') TargetAdd('panda3dw.exe', input='libp3tinyxml.ilb') TargetAdd('panda3dw.exe', opts=['SUBSYSTEM:WINDOWS', 'OPENSSL', 'ZLIB', 'WINGDI', 'WINUSER', 'WINSHELL', 'ADVAPI', 'WINSOCK2', 'WINOLE', 'CARBON']) if (RTDIST): OPTS=['BUILDING:P3D_PLUGIN', 'DIR:direct/src/plugin_standalone', 'DIR:direct/src/plugin', 'DIR:dtool/src/dtoolbase', 'DIR:dtool/src/dtoolutil', 'DIR:dtool/src/pystub', 'DIR:dtool/src/prc', 'DIR:dtool/src/dconfig', 'DIR:panda/src/express', 'DIR:panda/src/downloader', 'RUNTIME', 'P3DEMBED', 'OPENSSL', 'ZLIB'] # This is arguably a big fat ugly hack, but doing it otherwise would complicate the build process considerably. DefSymbol("P3DEMBED", "LINK_ALL_STATIC", "") TargetAdd('plugin_standalone_panda3dBase.obj', opts=OPTS, input='panda3dBase.cxx') TargetAdd('plugin_standalone_p3dEmbedMain.obj', opts=OPTS, input='p3dEmbedMain.cxx') TargetAdd('plugin_standalone_p3dEmbed.obj', opts=OPTS, input='p3dEmbed.cxx') #TargetAdd('plugin_standalone_pystub.obj', opts=OPTS, input='pystub.cxx') TargetAdd('plugin_standalone_dtoolbase_composite1.obj', opts=OPTS, input='p3dtoolbase_composite1.cxx') TargetAdd('plugin_standalone_dtoolbase_composite2.obj', opts=OPTS, input='p3dtoolbase_composite2.cxx') TargetAdd('plugin_standalone_lookup3.obj', opts=OPTS, input='lookup3.c') TargetAdd('plugin_standalone_indent.obj', opts=OPTS, input='indent.cxx') TargetAdd('plugin_standalone_dtoolutil_composite1.obj', opts=OPTS, input='p3dtoolutil_composite1.cxx') TargetAdd('plugin_standalone_dtoolutil_composite2.obj', opts=OPTS, input='p3dtoolutil_composite2.cxx') if (GetTarget() == 'darwin'): TargetAdd('plugin_standalone_dtoolutil_filename_assist.obj', opts=OPTS, input='filename_assist.mm') TargetAdd('plugin_standalone_prc_composite1.obj', opts=OPTS, input='p3prc_composite1.cxx') TargetAdd('plugin_standalone_prc_composite2.obj', opts=OPTS, input='p3prc_composite2.cxx') TargetAdd('plugin_standalone_express_composite1.obj', opts=OPTS, input='p3express_composite1.cxx') TargetAdd('plugin_standalone_express_composite2.obj', opts=OPTS, input='p3express_composite2.cxx') TargetAdd('plugin_standalone_downloader_composite1.obj', opts=OPTS, input='p3downloader_composite1.cxx') TargetAdd('plugin_standalone_downloader_composite2.obj', opts=OPTS, input='p3downloader_composite2.cxx') TargetAdd('p3dembed.exe', input='plugin_standalone_panda3dBase.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_p3dEmbedMain.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_p3dEmbed.obj') #TargetAdd('p3dembed.exe', input='plugin_standalone_pystub.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_dtoolbase_composite1.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_dtoolbase_composite2.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_lookup3.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_indent.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_dtoolutil_composite1.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_dtoolutil_composite2.obj') if GetTarget() == 'darwin': TargetAdd('p3dembed.exe', input='plugin_standalone_dtoolutil_filename_assist.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_prc_composite1.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_prc_composite2.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_express_composite1.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_express_composite2.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_downloader_composite1.obj') TargetAdd('p3dembed.exe', input='plugin_standalone_downloader_composite2.obj') TargetAdd('p3dembed.exe', input='plugin_common.obj') if GetTarget() == 'darwin': TargetAdd('p3dembed.exe', input='plugin_find_root_dir_assist.obj') TargetAdd('p3dembed.exe', input='libp3subprocbuffer.ilb') TargetAdd('p3dembed.exe', input='libp3tinyxml.ilb') TargetAdd('p3dembed.exe', input='libp3d_plugin_static.ilb') TargetAdd('p3dembed.exe', opts=['NOICON', 'WINGDI', 'WINSOCK2', 'ZLIB', 'WINUSER', 'OPENSSL', 'WINOLE', 'CARBON', 'MSIMG', 'WINCOMCTL', 'ADVAPI', 'WINSHELL', 'X11']) if GetTarget() == 'windows': OPTS.append("P3DEMBEDW") DefSymbol("P3DEMBEDW", "P3DEMBEDW", "") TargetAdd('plugin_standalone_p3dEmbedWinMain.obj', opts=OPTS, input='p3dEmbedMain.cxx') TargetAdd('p3dembedw.exe', input='plugin_standalone_panda3dBase.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_p3dEmbedWinMain.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_p3dEmbed.obj') #TargetAdd('p3dembedw.exe', input='plugin_standalone_pystub.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_dtoolbase_composite1.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_dtoolbase_composite2.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_lookup3.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_indent.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_dtoolutil_composite1.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_dtoolutil_composite2.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_prc_composite1.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_prc_composite2.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_express_composite1.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_express_composite2.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_downloader_composite1.obj') TargetAdd('p3dembedw.exe', input='plugin_standalone_downloader_composite2.obj') TargetAdd('p3dembedw.exe', input='plugin_common.obj') TargetAdd('p3dembedw.exe', input='libp3tinyxml.ilb') TargetAdd('p3dembedw.exe', input='libp3d_plugin_static.ilb') TargetAdd('p3dembedw.exe', opts=['SUBSYSTEM:WINDOWS', 'NOICON', 'WINGDI', 'WINSOCK2', 'ZLIB', 'WINUSER', 'OPENSSL', 'WINOLE', 'MSIMG', 'WINCOMCTL', 'ADVAPI', 'WINSHELL']) # # DIRECTORY: pandatool/src/pandatoolbase/ # if (PkgSkip("PANDATOOL")==0): OPTS=['DIR:pandatool/src/pandatoolbase'] TargetAdd('p3pandatoolbase_composite1.obj', opts=OPTS, input='p3pandatoolbase_composite1.cxx') TargetAdd('libp3pandatoolbase.lib', input='p3pandatoolbase_composite1.obj') # # DIRECTORY: pandatool/src/converter/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/converter'] TargetAdd('p3converter_somethingToEggConverter.obj', opts=OPTS, input='somethingToEggConverter.cxx') TargetAdd('p3converter_eggToSomethingConverter.obj', opts=OPTS, input='eggToSomethingConverter.cxx') TargetAdd('libp3converter.lib', input='p3converter_somethingToEggConverter.obj') TargetAdd('libp3converter.lib', input='p3converter_eggToSomethingConverter.obj') # # DIRECTORY: pandatool/src/progbase/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/progbase', 'ZLIB'] TargetAdd('p3progbase_composite1.obj', opts=OPTS, input='p3progbase_composite1.cxx') TargetAdd('libp3progbase.lib', input='p3progbase_composite1.obj') # # DIRECTORY: pandatool/src/eggbase/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/eggbase'] TargetAdd('p3eggbase_composite1.obj', opts=OPTS, input='p3eggbase_composite1.cxx') TargetAdd('libp3eggbase.lib', input='p3eggbase_composite1.obj') # # DIRECTORY: pandatool/src/bam/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/bam'] TargetAdd('bam-info_bamInfo.obj', opts=OPTS, input='bamInfo.cxx') TargetAdd('bam-info.exe', input='bam-info_bamInfo.obj') TargetAdd('bam-info.exe', input='libp3progbase.lib') TargetAdd('bam-info.exe', input='libp3pandatoolbase.lib') TargetAdd('bam-info.exe', input=COMMON_PANDA_LIBS) TargetAdd('bam-info.exe', opts=['ADVAPI', 'FFTW']) if not PkgSkip("EGG"): TargetAdd('bam2egg_bamToEgg.obj', opts=OPTS, input='bamToEgg.cxx') TargetAdd('bam2egg.exe', input='bam2egg_bamToEgg.obj') TargetAdd('bam2egg.exe', input=COMMON_EGG2X_LIBS) TargetAdd('bam2egg.exe', opts=['ADVAPI', 'FFTW']) TargetAdd('egg2bam_eggToBam.obj', opts=OPTS, input='eggToBam.cxx') TargetAdd('egg2bam.exe', input='egg2bam_eggToBam.obj') TargetAdd('egg2bam.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg2bam.exe', opts=['ADVAPI', 'FFTW']) # # DIRECTORY: pandatool/src/cvscopy/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/cvscopy'] TargetAdd('p3cvscopy_composite1.obj', opts=OPTS, input='p3cvscopy_composite1.cxx') TargetAdd('libp3cvscopy.lib', input='p3cvscopy_composite1.obj') # # DIRECTORY: pandatool/src/daeegg/ # if not PkgSkip("PANDATOOL") and not PkgSkip("FCOLLADA") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/daeegg', 'FCOLLADA'] TargetAdd('p3daeegg_composite1.obj', opts=OPTS, input='p3daeegg_composite1.cxx') TargetAdd('libp3daeegg.lib', input='p3daeegg_composite1.obj') TargetAdd('libp3daeegg.lib', opts=['FCOLLADA', 'CARBON']) # # DIRECTORY: pandatool/src/assimp # if not PkgSkip("PANDATOOL") and not PkgSkip("ASSIMP"): OPTS=['DIR:pandatool/src/assimp', 'BUILDING:ASSIMP', 'ASSIMP', 'MODULE'] TargetAdd('p3assimp_composite1.obj', opts=OPTS, input='p3assimp_composite1.cxx') TargetAdd('libp3assimp.dll', input='p3assimp_composite1.obj') TargetAdd('libp3assimp.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3assimp.dll', opts=OPTS+['ZLIB']) # # DIRECTORY: pandatool/src/daeprogs/ # if not PkgSkip("PANDATOOL") and not PkgSkip("FCOLLADA") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/daeprogs', 'FCOLLADA'] TargetAdd('dae2egg_daeToEgg.obj', opts=OPTS, input='daeToEgg.cxx') TargetAdd('dae2egg.exe', input='dae2egg_daeToEgg.obj') TargetAdd('dae2egg.exe', input='libp3daeegg.lib') TargetAdd('dae2egg.exe', input=COMMON_EGG2X_LIBS) TargetAdd('dae2egg.exe', opts=['WINUSER', 'FCOLLADA', 'CARBON']) # # DIRECTORY: pandatool/src/dxf/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/dxf'] TargetAdd('p3dxf_composite1.obj', opts=OPTS, input='p3dxf_composite1.cxx') TargetAdd('libp3dxf.lib', input='p3dxf_composite1.obj') # # DIRECTORY: pandatool/src/dxfegg/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/dxfegg'] TargetAdd('p3dxfegg_dxfToEggConverter.obj', opts=OPTS, input='dxfToEggConverter.cxx') TargetAdd('p3dxfegg_dxfToEggLayer.obj', opts=OPTS, input='dxfToEggLayer.cxx') TargetAdd('libp3dxfegg.lib', input='p3dxfegg_dxfToEggConverter.obj') TargetAdd('libp3dxfegg.lib', input='p3dxfegg_dxfToEggLayer.obj') # # DIRECTORY: pandatool/src/dxfprogs/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/dxfprogs'] TargetAdd('dxf-points_dxfPoints.obj', opts=OPTS, input='dxfPoints.cxx') TargetAdd('dxf-points.exe', input='dxf-points_dxfPoints.obj') TargetAdd('dxf-points.exe', input='libp3progbase.lib') TargetAdd('dxf-points.exe', input='libp3dxf.lib') TargetAdd('dxf-points.exe', input='libp3pandatoolbase.lib') TargetAdd('dxf-points.exe', input=COMMON_PANDA_LIBS) TargetAdd('dxf-points.exe', opts=['ADVAPI', 'FFTW']) if not PkgSkip("EGG"): TargetAdd('dxf2egg_dxfToEgg.obj', opts=OPTS, input='dxfToEgg.cxx') TargetAdd('dxf2egg.exe', input='dxf2egg_dxfToEgg.obj') TargetAdd('dxf2egg.exe', input='libp3dxfegg.lib') TargetAdd('dxf2egg.exe', input='libp3dxf.lib') TargetAdd('dxf2egg.exe', input=COMMON_EGG2X_LIBS) TargetAdd('dxf2egg.exe', opts=['ADVAPI', 'FFTW']) TargetAdd('egg2dxf_eggToDXF.obj', opts=OPTS, input='eggToDXF.cxx') TargetAdd('egg2dxf_eggToDXFLayer.obj', opts=OPTS, input='eggToDXFLayer.cxx') TargetAdd('egg2dxf.exe', input='egg2dxf_eggToDXF.obj') TargetAdd('egg2dxf.exe', input='egg2dxf_eggToDXFLayer.obj') TargetAdd('egg2dxf.exe', input='libp3dxf.lib') TargetAdd('egg2dxf.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg2dxf.exe', opts=['ADVAPI', 'FFTW']) # # DIRECTORY: pandatool/src/objegg/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/objegg'] TargetAdd('p3objegg_objToEggConverter.obj', opts=OPTS, input='objToEggConverter.cxx') TargetAdd('p3objegg_eggToObjConverter.obj', opts=OPTS, input='eggToObjConverter.cxx') TargetAdd('p3objegg_config_objegg.obj', opts=OPTS, input='config_objegg.cxx') TargetAdd('libp3objegg.lib', input='p3objegg_objToEggConverter.obj') TargetAdd('libp3objegg.lib', input='p3objegg_eggToObjConverter.obj') TargetAdd('libp3objegg.lib', input='p3objegg_config_objegg.obj') # # DIRECTORY: pandatool/src/objprogs/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/objprogs'] TargetAdd('obj2egg_objToEgg.obj', opts=OPTS, input='objToEgg.cxx') TargetAdd('obj2egg.exe', input='obj2egg_objToEgg.obj') TargetAdd('obj2egg.exe', input='libp3objegg.lib') TargetAdd('obj2egg.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg2obj_eggToObj.obj', opts=OPTS, input='eggToObj.cxx') TargetAdd('egg2obj.exe', input='egg2obj_eggToObj.obj') TargetAdd('egg2obj.exe', input='libp3objegg.lib') TargetAdd('egg2obj.exe', input=COMMON_EGG2X_LIBS) # # DIRECTORY: pandatool/src/palettizer/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/palettizer'] TargetAdd('p3palettizer_composite1.obj', opts=OPTS, input='p3palettizer_composite1.cxx') TargetAdd('libp3palettizer.lib', input='p3palettizer_composite1.obj') # # DIRECTORY: pandatool/src/egg-mkfont/ # if not PkgSkip("FREETYPE") and not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/egg-mkfont', 'DIR:pandatool/src/palettizer', 'FREETYPE'] TargetAdd('egg-mkfont_eggMakeFont.obj', opts=OPTS, input='eggMakeFont.cxx') TargetAdd('egg-mkfont_rangeDescription.obj', opts=OPTS, input='rangeDescription.cxx') TargetAdd('egg-mkfont_rangeIterator.obj', opts=OPTS, input='rangeIterator.cxx') TargetAdd('egg-mkfont.exe', input='egg-mkfont_eggMakeFont.obj') TargetAdd('egg-mkfont.exe', input='egg-mkfont_rangeDescription.obj') TargetAdd('egg-mkfont.exe', input='egg-mkfont_rangeIterator.obj') TargetAdd('egg-mkfont.exe', input='libp3palettizer.lib') TargetAdd('egg-mkfont.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-mkfont.exe', opts=['ADVAPI', 'FREETYPE']) # # DIRECTORY: pandatool/src/eggcharbase/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/eggcharbase', 'ZLIB'] TargetAdd('p3eggcharbase_composite1.obj', opts=OPTS, input='p3eggcharbase_composite1.cxx') TargetAdd('libp3eggcharbase.lib', input='p3eggcharbase_composite1.obj') # # DIRECTORY: pandatool/src/egg-optchar/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/egg-optchar'] TargetAdd('egg-optchar_config_egg_optchar.obj', opts=OPTS, input='config_egg_optchar.cxx') TargetAdd('egg-optchar_eggOptchar.obj', opts=OPTS, input='eggOptchar.cxx') TargetAdd('egg-optchar_eggOptcharUserData.obj', opts=OPTS, input='eggOptcharUserData.cxx') TargetAdd('egg-optchar_vertexMembership.obj', opts=OPTS, input='vertexMembership.cxx') TargetAdd('egg-optchar.exe', input='egg-optchar_config_egg_optchar.obj') TargetAdd('egg-optchar.exe', input='egg-optchar_eggOptchar.obj') TargetAdd('egg-optchar.exe', input='egg-optchar_eggOptcharUserData.obj') TargetAdd('egg-optchar.exe', input='egg-optchar_vertexMembership.obj') TargetAdd('egg-optchar.exe', input='libp3eggcharbase.lib') TargetAdd('egg-optchar.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-optchar.exe', opts=['ADVAPI', 'FREETYPE']) # # DIRECTORY: pandatool/src/egg-palettize/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/egg-palettize', 'DIR:pandatool/src/palettizer'] TargetAdd('egg-palettize_eggPalettize.obj', opts=OPTS, input='eggPalettize.cxx') TargetAdd('egg-palettize.exe', input='egg-palettize_eggPalettize.obj') TargetAdd('egg-palettize.exe', input='libp3palettizer.lib') TargetAdd('egg-palettize.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-palettize.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/egg-qtess/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/egg-qtess'] TargetAdd('egg-qtess_composite1.obj', opts=OPTS, input='egg-qtess_composite1.cxx') TargetAdd('egg-qtess.exe', input='egg-qtess_composite1.obj') TargetAdd('egg-qtess.exe', input='libp3eggbase.lib') TargetAdd('egg-qtess.exe', input='libp3progbase.lib') TargetAdd('egg-qtess.exe', input='libp3converter.lib') TargetAdd('egg-qtess.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-qtess.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/eggprogs/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/eggprogs'] TargetAdd('egg-crop_eggCrop.obj', opts=OPTS, input='eggCrop.cxx') TargetAdd('egg-crop.exe', input='egg-crop_eggCrop.obj') TargetAdd('egg-crop.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-crop.exe', opts=['ADVAPI']) TargetAdd('egg-make-tube_eggMakeTube.obj', opts=OPTS, input='eggMakeTube.cxx') TargetAdd('egg-make-tube.exe', input='egg-make-tube_eggMakeTube.obj') TargetAdd('egg-make-tube.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-make-tube.exe', opts=['ADVAPI']) TargetAdd('egg-texture-cards_eggTextureCards.obj', opts=OPTS, input='eggTextureCards.cxx') TargetAdd('egg-texture-cards.exe', input='egg-texture-cards_eggTextureCards.obj') TargetAdd('egg-texture-cards.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-texture-cards.exe', opts=['ADVAPI']) TargetAdd('egg-topstrip_eggTopstrip.obj', opts=OPTS, input='eggTopstrip.cxx') TargetAdd('egg-topstrip.exe', input='egg-topstrip_eggTopstrip.obj') TargetAdd('egg-topstrip.exe', input='libp3eggcharbase.lib') TargetAdd('egg-topstrip.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-topstrip.exe', opts=['ADVAPI']) TargetAdd('egg-trans_eggTrans.obj', opts=OPTS, input='eggTrans.cxx') TargetAdd('egg-trans.exe', input='egg-trans_eggTrans.obj') TargetAdd('egg-trans.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-trans.exe', opts=['ADVAPI']) TargetAdd('egg2c_eggToC.obj', opts=OPTS, input='eggToC.cxx') TargetAdd('egg2c.exe', input='egg2c_eggToC.obj') TargetAdd('egg2c.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg2c.exe', opts=['ADVAPI']) TargetAdd('egg-rename_eggRename.obj', opts=OPTS, input='eggRename.cxx') TargetAdd('egg-rename.exe', input='egg-rename_eggRename.obj') TargetAdd('egg-rename.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-rename.exe', opts=['ADVAPI']) TargetAdd('egg-retarget-anim_eggRetargetAnim.obj', opts=OPTS, input='eggRetargetAnim.cxx') TargetAdd('egg-retarget-anim.exe', input='egg-retarget-anim_eggRetargetAnim.obj') TargetAdd('egg-retarget-anim.exe', input='libp3eggcharbase.lib') TargetAdd('egg-retarget-anim.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-retarget-anim.exe', opts=['ADVAPI']) TargetAdd('egg-list-textures_eggListTextures.obj', opts=OPTS, input='eggListTextures.cxx') TargetAdd('egg-list-textures.exe', input='egg-list-textures_eggListTextures.obj') TargetAdd('egg-list-textures.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg-list-textures.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/flt/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/flt', 'ZLIB'] TargetAdd('p3flt_composite1.obj', opts=OPTS, input='p3flt_composite1.cxx') TargetAdd('libp3flt.lib', input=['p3flt_composite1.obj']) # # DIRECTORY: pandatool/src/fltegg/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/fltegg'] TargetAdd('p3fltegg_fltToEggConverter.obj', opts=OPTS, input='fltToEggConverter.cxx') TargetAdd('p3fltegg_fltToEggLevelState.obj', opts=OPTS, input='fltToEggLevelState.cxx') TargetAdd('libp3fltegg.lib', input=['p3fltegg_fltToEggConverter.obj', 'p3fltegg_fltToEggLevelState.obj']) # # DIRECTORY: pandatool/src/fltprogs/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/fltprogs', 'DIR:pandatool/src/flt', 'DIR:pandatool/src/cvscopy'] TargetAdd('flt-info_fltInfo.obj', opts=OPTS, input='fltInfo.cxx') TargetAdd('flt-info.exe', input='flt-info_fltInfo.obj') TargetAdd('flt-info.exe', input='libp3flt.lib') TargetAdd('flt-info.exe', input='libp3progbase.lib') TargetAdd('flt-info.exe', input='libp3pandatoolbase.lib') TargetAdd('flt-info.exe', input=COMMON_PANDA_LIBS) TargetAdd('flt-info.exe', opts=['ADVAPI']) TargetAdd('flt-trans_fltTrans.obj', opts=OPTS, input='fltTrans.cxx') TargetAdd('flt-trans.exe', input='flt-trans_fltTrans.obj') TargetAdd('flt-trans.exe', input='libp3flt.lib') TargetAdd('flt-trans.exe', input='libp3progbase.lib') TargetAdd('flt-trans.exe', input='libp3pandatoolbase.lib') TargetAdd('flt-trans.exe', input=COMMON_PANDA_LIBS) TargetAdd('flt-trans.exe', opts=['ADVAPI']) TargetAdd('fltcopy_fltCopy.obj', opts=OPTS, input='fltCopy.cxx') TargetAdd('fltcopy.exe', input='fltcopy_fltCopy.obj') TargetAdd('fltcopy.exe', input='libp3cvscopy.lib') TargetAdd('fltcopy.exe', input='libp3flt.lib') TargetAdd('fltcopy.exe', input='libp3progbase.lib') TargetAdd('fltcopy.exe', input='libp3pandatoolbase.lib') TargetAdd('fltcopy.exe', input=COMMON_PANDA_LIBS) TargetAdd('fltcopy.exe', opts=['ADVAPI']) if not PkgSkip("EGG"): TargetAdd('egg2flt_eggToFlt.obj', opts=OPTS, input='eggToFlt.cxx') TargetAdd('egg2flt.exe', input='egg2flt_eggToFlt.obj') TargetAdd('egg2flt.exe', input='libp3flt.lib') TargetAdd('egg2flt.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg2flt.exe', opts=['ADVAPI']) TargetAdd('flt2egg_fltToEgg.obj', opts=OPTS, input='fltToEgg.cxx') TargetAdd('flt2egg.exe', input='flt2egg_fltToEgg.obj') TargetAdd('flt2egg.exe', input='libp3flt.lib') TargetAdd('flt2egg.exe', input='libp3fltegg.lib') TargetAdd('flt2egg.exe', input=COMMON_EGG2X_LIBS) TargetAdd('flt2egg.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/imagebase/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/imagebase'] TargetAdd('p3imagebase_composite1.obj', opts=OPTS, input='p3imagebase_composite1.cxx') TargetAdd('libp3imagebase.lib', input='p3imagebase_composite1.obj') # # DIRECTORY: pandatool/src/imageprogs/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/imageprogs'] TargetAdd('image-info_imageInfo.obj', opts=OPTS, input='imageInfo.cxx') TargetAdd('image-info.exe', input='image-info_imageInfo.obj') TargetAdd('image-info.exe', input='libp3imagebase.lib') TargetAdd('image-info.exe', input='libp3progbase.lib') TargetAdd('image-info.exe', input='libp3pandatoolbase.lib') TargetAdd('image-info.exe', input=COMMON_PANDA_LIBS) TargetAdd('image-info.exe', opts=['ADVAPI']) TargetAdd('image-resize_imageResize.obj', opts=OPTS, input='imageResize.cxx') TargetAdd('image-resize.exe', input='image-resize_imageResize.obj') TargetAdd('image-resize.exe', input='libp3imagebase.lib') TargetAdd('image-resize.exe', input='libp3progbase.lib') TargetAdd('image-resize.exe', input='libp3pandatoolbase.lib') TargetAdd('image-resize.exe', input=COMMON_PANDA_LIBS) TargetAdd('image-resize.exe', opts=['ADVAPI']) TargetAdd('image-trans_imageTrans.obj', opts=OPTS, input='imageTrans.cxx') TargetAdd('image-trans.exe', input='image-trans_imageTrans.obj') TargetAdd('image-trans.exe', input='libp3imagebase.lib') TargetAdd('image-trans.exe', input='libp3progbase.lib') TargetAdd('image-trans.exe', input='libp3pandatoolbase.lib') TargetAdd('image-trans.exe', input=COMMON_PANDA_LIBS) TargetAdd('image-trans.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/pfmprogs/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/pfmprogs'] TargetAdd('pfm-trans_pfmTrans.obj', opts=OPTS, input='pfmTrans.cxx') TargetAdd('pfm-trans.exe', input='pfm-trans_pfmTrans.obj') TargetAdd('pfm-trans.exe', input='libp3progbase.lib') TargetAdd('pfm-trans.exe', input='libp3pandatoolbase.lib') TargetAdd('pfm-trans.exe', input=COMMON_PANDA_LIBS) TargetAdd('pfm-trans.exe', opts=['ADVAPI']) TargetAdd('pfm-bba_pfmBba.obj', opts=OPTS, input='pfmBba.cxx') TargetAdd('pfm-bba_config_pfmprogs.obj', opts=OPTS, input='config_pfmprogs.cxx') TargetAdd('pfm-bba.exe', input='pfm-bba_pfmBba.obj') TargetAdd('pfm-bba.exe', input='pfm-bba_config_pfmprogs.obj') TargetAdd('pfm-bba.exe', input='libp3progbase.lib') TargetAdd('pfm-bba.exe', input='libp3pandatoolbase.lib') TargetAdd('pfm-bba.exe', input=COMMON_PANDA_LIBS) TargetAdd('pfm-bba.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/lwo/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/lwo'] TargetAdd('p3lwo_composite1.obj', opts=OPTS, input='p3lwo_composite1.cxx') TargetAdd('libp3lwo.lib', input='p3lwo_composite1.obj') # # DIRECTORY: pandatool/src/lwoegg/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/lwoegg'] TargetAdd('p3lwoegg_composite1.obj', opts=OPTS, input='p3lwoegg_composite1.cxx') TargetAdd('libp3lwoegg.lib', input='p3lwoegg_composite1.obj') # # DIRECTORY: pandatool/src/lwoprogs/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/lwoprogs', 'DIR:pandatool/src/lwo'] TargetAdd('lwo-scan_lwoScan.obj', opts=OPTS, input='lwoScan.cxx') TargetAdd('lwo-scan.exe', input='lwo-scan_lwoScan.obj') TargetAdd('lwo-scan.exe', input='libp3lwo.lib') TargetAdd('lwo-scan.exe', input='libp3progbase.lib') TargetAdd('lwo-scan.exe', input='libp3pandatoolbase.lib') TargetAdd('lwo-scan.exe', input=COMMON_PANDA_LIBS) TargetAdd('lwo-scan.exe', opts=['ADVAPI']) if not PkgSkip("EGG"): TargetAdd('lwo2egg_lwoToEgg.obj', opts=OPTS, input='lwoToEgg.cxx') TargetAdd('lwo2egg.exe', input='lwo2egg_lwoToEgg.obj') TargetAdd('lwo2egg.exe', input='libp3lwo.lib') TargetAdd('lwo2egg.exe', input='libp3lwoegg.lib') TargetAdd('lwo2egg.exe', input=COMMON_EGG2X_LIBS) TargetAdd('lwo2egg.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/maya/ # for VER in MAYAVERSIONS: VNUM=VER[4:] if not PkgSkip(VER) and not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/maya', VER] TargetAdd('maya'+VNUM+'_composite1.obj', opts=OPTS, input='p3maya_composite1.cxx') TargetAdd('libmaya'+VNUM+'.lib', input='maya'+VNUM+'_composite1.obj') # # DIRECTORY: pandatool/src/mayaegg/ # for VER in MAYAVERSIONS: VNUM=VER[4:] if not PkgSkip(VER) and not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/mayaegg', 'DIR:pandatool/src/maya', VER] TargetAdd('mayaegg'+VNUM+'_loader.obj', opts=OPTS, input='mayaEggLoader.cxx') TargetAdd('mayaegg'+VNUM+'_composite1.obj', opts=OPTS, input='p3mayaegg_composite1.cxx') TargetAdd('libmayaegg'+VNUM+'.lib', input='mayaegg'+VNUM+'_loader.obj') TargetAdd('libmayaegg'+VNUM+'.lib', input='mayaegg'+VNUM+'_composite1.obj') # # DIRECTORY: pandatool/src/maxegg/ # for VER in MAXVERSIONS: VNUM=VER[3:] if not PkgSkip(VER) and not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/maxegg', VER, "WINCOMCTL", "WINCOMDLG", "WINUSER", "MSFORSCOPE", "RTTI"] TargetAdd('maxEgg'+VNUM+'.res', opts=OPTS, input='maxEgg.rc') TargetAdd('maxegg'+VNUM+'_loader.obj', opts=OPTS, input='maxEggLoader.cxx') TargetAdd('maxegg'+VNUM+'_composite1.obj', opts=OPTS, input='p3maxegg_composite1.cxx') TargetAdd('maxegg'+VNUM+'.dlo', input='maxegg'+VNUM+'_composite1.obj') TargetAdd('maxegg'+VNUM+'.dlo', input='maxEgg'+VNUM+'.res') TargetAdd('maxegg'+VNUM+'.dlo', input='maxEgg.def', ipath=OPTS) TargetAdd('maxegg'+VNUM+'.dlo', input=COMMON_EGG2X_LIBS) TargetAdd('maxegg'+VNUM+'.dlo', opts=OPTS) # # DIRECTORY: pandatool/src/maxprogs/ # for VER in MAXVERSIONS: VNUM=VER[3:] if not PkgSkip(VER) and not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/maxprogs', VER, "WINCOMCTL", "WINCOMDLG", "WINUSER", "MSFORSCOPE", "RTTI"] TargetAdd('maxImportRes.res', opts=OPTS, input='maxImportRes.rc') TargetAdd('maxprogs'+VNUM+'_maxeggimport.obj', opts=OPTS, input='maxEggImport.cxx') TargetAdd('maxeggimport'+VNUM+'.dle', input='maxegg'+VNUM+'_loader.obj') TargetAdd('maxeggimport'+VNUM+'.dle', input='maxprogs'+VNUM+'_maxeggimport.obj') TargetAdd('maxeggimport'+VNUM+'.dle', input='libpandaegg.dll') TargetAdd('maxeggimport'+VNUM+'.dle', input='libpanda.dll') TargetAdd('maxeggimport'+VNUM+'.dle', input='libpandaexpress.dll') TargetAdd('maxeggimport'+VNUM+'.dle', input='maxImportRes.res') TargetAdd('maxeggimport'+VNUM+'.dle', input='maxEggImport.def', ipath=OPTS) TargetAdd('maxeggimport'+VNUM+'.dle', input=COMMON_DTOOL_LIBS) TargetAdd('maxeggimport'+VNUM+'.dle', opts=OPTS) # # DIRECTORY: pandatool/src/vrml/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/vrml', 'ZLIB', 'BISONPREFIX_vrmlyy'] CreateFile(GetOutputDir()+"/include/vrmlParser.h") TargetAdd('p3vrml_vrmlParser.obj', opts=OPTS, input='vrmlParser.yxx') TargetAdd('vrmlParser.h', input='p3vrml_vrmlParser.obj', opts=['DEPENDENCYONLY']) TargetAdd('p3vrml_vrmlLexer.obj', opts=OPTS, input='vrmlLexer.lxx') TargetAdd('p3vrml_parse_vrml.obj', opts=OPTS, input='parse_vrml.cxx') TargetAdd('p3vrml_standard_nodes.obj', opts=OPTS, input='standard_nodes.cxx') TargetAdd('p3vrml_vrmlNode.obj', opts=OPTS, input='vrmlNode.cxx') TargetAdd('p3vrml_vrmlNodeType.obj', opts=OPTS, input='vrmlNodeType.cxx') TargetAdd('libp3vrml.lib', input='p3vrml_parse_vrml.obj') TargetAdd('libp3vrml.lib', input='p3vrml_standard_nodes.obj') TargetAdd('libp3vrml.lib', input='p3vrml_vrmlNode.obj') TargetAdd('libp3vrml.lib', input='p3vrml_vrmlNodeType.obj') TargetAdd('libp3vrml.lib', input='p3vrml_vrmlParser.obj') TargetAdd('libp3vrml.lib', input='p3vrml_vrmlLexer.obj') # # DIRECTORY: pandatool/src/vrmlegg/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/vrmlegg', 'DIR:pandatool/src/vrml'] TargetAdd('p3vrmlegg_indexedFaceSet.obj', opts=OPTS, input='indexedFaceSet.cxx') TargetAdd('p3vrmlegg_vrmlAppearance.obj', opts=OPTS, input='vrmlAppearance.cxx') TargetAdd('p3vrmlegg_vrmlToEggConverter.obj', opts=OPTS, input='vrmlToEggConverter.cxx') TargetAdd('libp3vrmlegg.lib', input='p3vrmlegg_indexedFaceSet.obj') TargetAdd('libp3vrmlegg.lib', input='p3vrmlegg_vrmlAppearance.obj') TargetAdd('libp3vrmlegg.lib', input='p3vrmlegg_vrmlToEggConverter.obj') # # DIRECTORY: pandatool/src/xfile/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/xfile', 'ZLIB', 'BISONPREFIX_xyy', 'FLEXDASHI'] CreateFile(GetOutputDir()+"/include/xParser.h") TargetAdd('p3xfile_xParser.obj', opts=OPTS, input='xParser.yxx') TargetAdd('xParser.h', input='p3xfile_xParser.obj', opts=['DEPENDENCYONLY']) TargetAdd('p3xfile_xLexer.obj', opts=OPTS, input='xLexer.lxx') TargetAdd('p3xfile_composite1.obj', opts=OPTS, input='p3xfile_composite1.cxx') TargetAdd('libp3xfile.lib', input='p3xfile_composite1.obj') TargetAdd('libp3xfile.lib', input='p3xfile_xParser.obj') TargetAdd('libp3xfile.lib', input='p3xfile_xLexer.obj') # # DIRECTORY: pandatool/src/xfileegg/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): OPTS=['DIR:pandatool/src/xfileegg', 'DIR:pandatool/src/xfile'] TargetAdd('p3xfileegg_composite1.obj', opts=OPTS, input='p3xfileegg_composite1.cxx') TargetAdd('libp3xfileegg.lib', input='p3xfileegg_composite1.obj') # # DIRECTORY: pandatool/src/ptloader/ # if not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): if not PkgSkip("FCOLLADA"): DefSymbol("FCOLLADA", "HAVE_FCOLLADA") OPTS=['DIR:pandatool/src/ptloader', 'DIR:pandatool/src/flt', 'DIR:pandatool/src/lwo', 'DIR:pandatool/src/xfile', 'DIR:pandatool/src/xfileegg', 'DIR:pandatool/src/daeegg', 'BUILDING:PTLOADER', 'FCOLLADA'] TargetAdd('p3ptloader_config_ptloader.obj', opts=OPTS, input='config_ptloader.cxx', dep='dtool_have_fcollada.dat') TargetAdd('p3ptloader_loaderFileTypePandatool.obj', opts=OPTS, input='loaderFileTypePandatool.cxx') TargetAdd('libp3ptloader.dll', input='p3ptloader_config_ptloader.obj') TargetAdd('libp3ptloader.dll', input='p3ptloader_loaderFileTypePandatool.obj') TargetAdd('libp3ptloader.dll', input='libp3fltegg.lib') TargetAdd('libp3ptloader.dll', input='libp3flt.lib') TargetAdd('libp3ptloader.dll', input='libp3lwoegg.lib') TargetAdd('libp3ptloader.dll', input='libp3lwo.lib') TargetAdd('libp3ptloader.dll', input='libp3dxfegg.lib') TargetAdd('libp3ptloader.dll', input='libp3dxf.lib') TargetAdd('libp3ptloader.dll', input='libp3objegg.lib') TargetAdd('libp3ptloader.dll', input='libp3vrmlegg.lib') TargetAdd('libp3ptloader.dll', input='libp3vrml.lib') TargetAdd('libp3ptloader.dll', input='libp3xfileegg.lib') TargetAdd('libp3ptloader.dll', input='libp3xfile.lib') if (PkgSkip("FCOLLADA")==0): TargetAdd('libp3ptloader.dll', input='libp3daeegg.lib') TargetAdd('libp3ptloader.dll', input='libp3eggbase.lib') TargetAdd('libp3ptloader.dll', input='libp3progbase.lib') TargetAdd('libp3ptloader.dll', input='libp3converter.lib') TargetAdd('libp3ptloader.dll', input='libp3pandatoolbase.lib') TargetAdd('libp3ptloader.dll', input='libpandaegg.dll') TargetAdd('libp3ptloader.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3ptloader.dll', opts=['MODULE', 'ADVAPI', 'FCOLLADA', 'WINUSER']) # # DIRECTORY: pandatool/src/miscprogs/ # # This is a bit of an esoteric tool, and it causes issues because # it conflicts with tools of the same name in different packages. #if (PkgSkip("PANDATOOL")==0): # OPTS=['DIR:pandatool/src/miscprogs'] # TargetAdd('bin2c_binToC.obj', opts=OPTS, input='binToC.cxx') # TargetAdd('bin2c.exe', input='bin2c_binToC.obj') # TargetAdd('bin2c.exe', input='libp3progbase.lib') # TargetAdd('bin2c.exe', input='libp3pandatoolbase.lib') # TargetAdd('bin2c.exe', input=COMMON_PANDA_LIBS) # TargetAdd('bin2c.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/pstatserver/ # if (PkgSkip("PANDATOOL")==0): OPTS=['DIR:pandatool/src/pstatserver'] TargetAdd('p3pstatserver_composite1.obj', opts=OPTS, input='p3pstatserver_composite1.cxx') TargetAdd('libp3pstatserver.lib', input='p3pstatserver_composite1.obj') # # DIRECTORY: pandatool/src/text-stats/ # if (PkgSkip("PANDATOOL")==0): OPTS=['DIR:pandatool/src/text-stats'] TargetAdd('text-stats_textMonitor.obj', opts=OPTS, input='textMonitor.cxx') TargetAdd('text-stats_textStats.obj', opts=OPTS, input='textStats.cxx') TargetAdd('text-stats.exe', input='text-stats_textMonitor.obj') TargetAdd('text-stats.exe', input='text-stats_textStats.obj') TargetAdd('text-stats.exe', input='libp3progbase.lib') TargetAdd('text-stats.exe', input='libp3pstatserver.lib') TargetAdd('text-stats.exe', input='libp3pandatoolbase.lib') TargetAdd('text-stats.exe', input=COMMON_PANDA_LIBS) TargetAdd('text-stats.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/vrmlprogs/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/vrmlprogs', 'DIR:pandatool/src/vrml', 'DIR:pandatool/src/vrmlegg'] TargetAdd('vrml-trans_vrmlTrans.obj', opts=OPTS, input='vrmlTrans.cxx') TargetAdd('vrml-trans.exe', input='vrml-trans_vrmlTrans.obj') TargetAdd('vrml-trans.exe', input='libp3vrml.lib') TargetAdd('vrml-trans.exe', input='libp3progbase.lib') TargetAdd('vrml-trans.exe', input='libp3pandatoolbase.lib') TargetAdd('vrml-trans.exe', input=COMMON_PANDA_LIBS) TargetAdd('vrml-trans.exe', opts=['ADVAPI']) if not PkgSkip("EGG"): TargetAdd('vrml2egg_vrmlToEgg.obj', opts=OPTS, input='vrmlToEgg.cxx') TargetAdd('vrml2egg.exe', input='vrml2egg_vrmlToEgg.obj') TargetAdd('vrml2egg.exe', input='libp3vrmlegg.lib') TargetAdd('vrml2egg.exe', input='libp3vrml.lib') TargetAdd('vrml2egg.exe', input=COMMON_EGG2X_LIBS) TargetAdd('vrml2egg.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/win-stats/ # DIRECTORY: pandatool/src/gtk-stats/ # if (PkgSkip("PANDATOOL")==0 and (GetTarget() == 'windows' or PkgSkip("GTK2")==0)): if GetTarget() == 'windows': OPTS=['DIR:pandatool/src/win-stats'] TargetAdd('pstats_composite1.obj', opts=OPTS, input='winstats_composite1.cxx') else: OPTS=['DIR:pandatool/src/gtk-stats', 'GTK2'] TargetAdd('pstats_composite1.obj', opts=OPTS, input='gtkstats_composite1.cxx') TargetAdd('pstats.exe', input='pstats_composite1.obj') TargetAdd('pstats.exe', input='libp3pstatserver.lib') TargetAdd('pstats.exe', input='libp3progbase.lib') TargetAdd('pstats.exe', input='libp3pandatoolbase.lib') TargetAdd('pstats.exe', input=COMMON_PANDA_LIBS) TargetAdd('pstats.exe', opts=['SUBSYSTEM:WINDOWS', 'WINSOCK', 'WINIMM', 'WINGDI', 'WINKERNEL', 'WINOLDNAMES', 'WINUSER', 'WINMM', 'GTK2']) # # DIRECTORY: pandatool/src/xfileprogs/ # if not PkgSkip("PANDATOOL"): OPTS=['DIR:pandatool/src/xfileprogs', 'DIR:pandatool/src/xfile', 'DIR:pandatool/src/xfileegg'] TargetAdd('x-trans_xFileTrans.obj', opts=OPTS, input='xFileTrans.cxx') TargetAdd('x-trans.exe', input='x-trans_xFileTrans.obj') TargetAdd('x-trans.exe', input='libp3progbase.lib') TargetAdd('x-trans.exe', input='libp3xfile.lib') TargetAdd('x-trans.exe', input='libp3pandatoolbase.lib') TargetAdd('x-trans.exe', input=COMMON_PANDA_LIBS) TargetAdd('x-trans.exe', opts=['ADVAPI']) if not PkgSkip("EGG"): TargetAdd('egg2x_eggToX.obj', opts=OPTS, input='eggToX.cxx') TargetAdd('egg2x.exe', input='egg2x_eggToX.obj') TargetAdd('egg2x.exe', input='libp3xfileegg.lib') TargetAdd('egg2x.exe', input='libp3xfile.lib') TargetAdd('egg2x.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg2x.exe', opts=['ADVAPI']) TargetAdd('x2egg_xFileToEgg.obj', opts=OPTS, input='xFileToEgg.cxx') TargetAdd('x2egg.exe', input='x2egg_xFileToEgg.obj') TargetAdd('x2egg.exe', input='libp3xfileegg.lib') TargetAdd('x2egg.exe', input='libp3xfile.lib') TargetAdd('x2egg.exe', input=COMMON_EGG2X_LIBS) TargetAdd('x2egg.exe', opts=['ADVAPI']) # # DIRECTORY: pandatool/src/mayaprogs/ # for VER in MAYAVERSIONS: VNUM = VER[4:] if not PkgSkip(VER) and not PkgSkip("PANDATOOL") and not PkgSkip("EGG"): if GetTarget() == 'darwin' and int(VNUM) >= 2012: ARCH_OPTS = ['NOARCH:PPC', 'NOARCH:I386'] if len(OSX_ARCHS) != 0 and 'x86_64' not in OSX_ARCHS: continue elif GetTarget() == 'darwin' and int(VNUM) >= 2009: ARCH_OPTS = ['NOARCH:PPC'] elif GetTarget() == 'darwin': ARCH_OPTS = ['NOARCH:X86_64'] else: ARCH_OPTS = [] OPTS=['DIR:pandatool/src/mayaprogs', 'DIR:pandatool/src/maya', 'DIR:pandatool/src/mayaegg', 'DIR:pandatool/src/cvscopy', 'BUILDING:MISC', VER] + ARCH_OPTS TargetAdd('mayaeggimport'+VNUM+'_mayaeggimport.obj', opts=OPTS, input='mayaEggImport.cxx') TargetAdd('mayaeggimport'+VNUM+'.mll', input='mayaegg'+VNUM+'_loader.obj') TargetAdd('mayaeggimport'+VNUM+'.mll', input='mayaeggimport'+VNUM+'_mayaeggimport.obj') TargetAdd('mayaeggimport'+VNUM+'.mll', input='libpandaegg.dll') TargetAdd('mayaeggimport'+VNUM+'.mll', input=COMMON_PANDA_LIBS) #if GetTarget() == 'windows': # TargetAdd('mayaeggimport'+VNUM+'.mll', input='libp3pystub.lib') TargetAdd('mayaeggimport'+VNUM+'.mll', opts=['ADVAPI', VER]+ARCH_OPTS) TargetAdd('mayaloader'+VNUM+'_config_mayaloader.obj', opts=OPTS, input='config_mayaloader.cxx') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='mayaloader'+VNUM+'_config_mayaloader.obj') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libmayaegg'+VNUM+'.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3ptloader.dll') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libmaya'+VNUM+'.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3fltegg.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3flt.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3lwoegg.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3lwo.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3dxfegg.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3dxf.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3objegg.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3vrmlegg.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3vrml.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3xfileegg.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3xfile.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3eggbase.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3progbase.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3converter.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libp3pandatoolbase.lib') TargetAdd('libp3mayaloader'+VNUM+'.dll', input='libpandaegg.dll') TargetAdd('libp3mayaloader'+VNUM+'.dll', input=COMMON_PANDA_LIBS) TargetAdd('libp3mayaloader'+VNUM+'.dll', opts=['ADVAPI', VER]+ARCH_OPTS) TargetAdd('mayapview'+VNUM+'_mayaPview.obj', opts=OPTS, input='mayaPview.cxx') TargetAdd('libmayapview'+VNUM+'.mll', input='mayapview'+VNUM+'_mayaPview.obj') TargetAdd('libmayapview'+VNUM+'.mll', input='libmayaegg'+VNUM+'.lib') TargetAdd('libmayapview'+VNUM+'.mll', input='libmaya'+VNUM+'.lib') TargetAdd('libmayapview'+VNUM+'.mll', input='libp3framework.dll') if GetTarget() == 'windows': TargetAdd('libmayapview'+VNUM+'.mll', input=COMMON_EGG2X_LIBS) else: TargetAdd('libmayapview'+VNUM+'.mll', input=COMMON_EGG2X_LIBS) TargetAdd('libmayapview'+VNUM+'.mll', opts=['ADVAPI', VER]+ARCH_OPTS) TargetAdd('maya2egg'+VNUM+'_mayaToEgg.obj', opts=OPTS, input='mayaToEgg.cxx') TargetAdd('maya2egg'+VNUM+'_bin.exe', input='maya2egg'+VNUM+'_mayaToEgg.obj') TargetAdd('maya2egg'+VNUM+'_bin.exe', input='libmayaegg'+VNUM+'.lib') TargetAdd('maya2egg'+VNUM+'_bin.exe', input='libmaya'+VNUM+'.lib') if GetTarget() == 'windows': TargetAdd('maya2egg'+VNUM+'_bin.exe', input=COMMON_EGG2X_LIBS) else: TargetAdd('maya2egg'+VNUM+'_bin.exe', input=COMMON_EGG2X_LIBS) TargetAdd('maya2egg'+VNUM+'_bin.exe', opts=['ADVAPI', VER]+ARCH_OPTS) TargetAdd('egg2maya'+VNUM+'_eggToMaya.obj', opts=OPTS, input='eggToMaya.cxx') TargetAdd('egg2maya'+VNUM+'_bin.exe', input='egg2maya'+VNUM+'_eggToMaya.obj') TargetAdd('egg2maya'+VNUM+'_bin.exe', input='libmayaegg'+VNUM+'.lib') TargetAdd('egg2maya'+VNUM+'_bin.exe', input='libmaya'+VNUM+'.lib') if GetTarget() == 'windows': TargetAdd('egg2maya'+VNUM+'_bin.exe', input=COMMON_EGG2X_LIBS) else: TargetAdd('egg2maya'+VNUM+'_bin.exe', input=COMMON_EGG2X_LIBS) TargetAdd('egg2maya'+VNUM+'_bin.exe', opts=['ADVAPI', VER]+ARCH_OPTS) TargetAdd('mayacopy'+VNUM+'_mayaCopy.obj', opts=OPTS, input='mayaCopy.cxx') TargetAdd('mayacopy'+VNUM+'_bin.exe', input='mayacopy'+VNUM+'_mayaCopy.obj') TargetAdd('mayacopy'+VNUM+'_bin.exe', input='libp3cvscopy.lib') TargetAdd('mayacopy'+VNUM+'_bin.exe', input='libmaya'+VNUM+'.lib') if GetTarget() == 'windows': TargetAdd('mayacopy'+VNUM+'_bin.exe', input=COMMON_EGG2X_LIBS) else: TargetAdd('mayacopy'+VNUM+'_bin.exe', input=COMMON_EGG2X_LIBS) TargetAdd('mayacopy'+VNUM+'_bin.exe', opts=['ADVAPI', VER]+ARCH_OPTS) TargetAdd('mayasavepview'+VNUM+'_mayaSavePview.obj', opts=OPTS, input='mayaSavePview.cxx') TargetAdd('libmayasavepview'+VNUM+'.mll', input='mayasavepview'+VNUM+'_mayaSavePview.obj') TargetAdd('libmayasavepview'+VNUM+'.mll', opts=['ADVAPI', VER]+ARCH_OPTS) TargetAdd('mayapath'+VNUM+'.obj', opts=OPTS, input='mayapath.cxx') TargetAdd('maya2egg'+VNUM+'.exe', input='mayapath'+VNUM+'.obj') TargetAdd('maya2egg'+VNUM+'.exe', input='libpandaexpress.dll') TargetAdd('maya2egg'+VNUM+'.exe', input=COMMON_DTOOL_LIBS) TargetAdd('maya2egg'+VNUM+'.exe', opts=['ADVAPI']+ARCH_OPTS) TargetAdd('egg2maya'+VNUM+'.exe', input='mayapath'+VNUM+'.obj') TargetAdd('egg2maya'+VNUM+'.exe', input='libpandaexpress.dll') TargetAdd('egg2maya'+VNUM+'.exe', input=COMMON_DTOOL_LIBS) TargetAdd('egg2maya'+VNUM+'.exe', opts=['ADVAPI']+ARCH_OPTS) TargetAdd('mayacopy'+VNUM+'.exe', input='mayapath'+VNUM+'.obj') TargetAdd('mayacopy'+VNUM+'.exe', input='libpandaexpress.dll') TargetAdd('mayacopy'+VNUM+'.exe', input=COMMON_DTOOL_LIBS) TargetAdd('mayacopy'+VNUM+'.exe', opts=['ADVAPI']+ARCH_OPTS) # # DIRECTORY: contrib/src/ai/ # if (PkgSkip("CONTRIB")==0 and not RUNTIME): OPTS=['DIR:contrib/src/ai', 'BUILDING:PANDAAI'] TargetAdd('p3ai_composite1.obj', opts=OPTS, input='p3ai_composite1.cxx') TargetAdd('libpandaai.dll', input='p3ai_composite1.obj') TargetAdd('libpandaai.dll', input=COMMON_PANDA_LIBS) OPTS=['DIR:contrib/src/ai'] IGATEFILES=GetDirectoryContents('contrib/src/ai', ["*.h", "*_composite*.cxx"]) TargetAdd('libpandaai.in', opts=OPTS, input=IGATEFILES) TargetAdd('libpandaai.in', opts=['IMOD:panda3d.ai', 'ILIB:libpandaai', 'SRCDIR:contrib/src/ai']) PyTargetAdd('ai_module.obj', input='libpandaai.in') PyTargetAdd('ai_module.obj', opts=OPTS) PyTargetAdd('ai_module.obj', opts=['IMOD:panda3d.ai', 'ILIB:ai', 'IMPORT:panda3d.core']) PyTargetAdd('ai.pyd', input='ai_module.obj') PyTargetAdd('ai.pyd', input='libpandaai_igate.obj') PyTargetAdd('ai.pyd', input='libpandaai.dll') PyTargetAdd('ai.pyd', input='libp3interrogatedb.dll') PyTargetAdd('ai.pyd', input=COMMON_PANDA_LIBS) # # DIRECTORY: contrib/src/rplight/ # if not PkgSkip("CONTRIB") and not PkgSkip("PYTHON") and not RUNTIME: OPTS=['DIR:contrib/src/rplight', 'BUILDING:RPLIGHT'] TargetAdd('p3rplight_composite1.obj', opts=OPTS, input='p3rplight_composite1.cxx') IGATEFILES=GetDirectoryContents('contrib/src/rplight', ["*.h", "*_composite*.cxx"]) TargetAdd('libp3rplight.in', opts=OPTS, input=IGATEFILES) TargetAdd('libp3rplight.in', opts=['IMOD:panda3d._rplight', 'ILIB:libp3rplight', 'SRCDIR:contrib/src/rplight']) PyTargetAdd('rplight_module.obj', input='libp3rplight.in') PyTargetAdd('rplight_module.obj', opts=OPTS) PyTargetAdd('rplight_module.obj', opts=['IMOD:panda3d._rplight', 'ILIB:_rplight', 'IMPORT:panda3d.core']) PyTargetAdd('_rplight.pyd', input='rplight_module.obj') PyTargetAdd('_rplight.pyd', input='libp3rplight_igate.obj') PyTargetAdd('_rplight.pyd', input='p3rplight_composite1.obj') PyTargetAdd('_rplight.pyd', input='libp3interrogatedb.dll') PyTargetAdd('_rplight.pyd', input=COMMON_PANDA_LIBS) # # Generate the models directory and samples directory # if not PkgSkip("DIRECT") and not RUNTIME and not PkgSkip("EGG"): model_extensions = ["*.egg"] # Check if we have access to an flt2egg utility, either self-compiled or on the system. if ((PkgSkip("PANDATOOL")==0 and GetHost()==GetTarget()) or LocateBinary('flt2egg')): model_extensions.append("*.flt") for model in GetDirectoryContents("dmodels/src/misc", model_extensions): if (PkgSkip("ZLIB")==0 and PkgSkip("DEPLOYTOOLS")==0 and not RTDIST): newname = model[:-4] + ".egg.pz" else: newname = model[:-4] + ".egg" TargetAdd(GetOutputDir()+"/models/misc/"+newname, input="dmodels/src/misc/"+model) for model in GetDirectoryContents("dmodels/src/gui", model_extensions): if (PkgSkip("ZLIB")==0 and PkgSkip("DEPLOYTOOLS")==0 and not RTDIST): newname = model[:-4] + ".egg.pz" else: newname = model[:-4] + ".egg" TargetAdd(GetOutputDir()+"/models/gui/"+newname, input="dmodels/src/gui/"+model) for model in GetDirectoryContents("models", model_extensions): if (PkgSkip("ZLIB")==0 and PkgSkip("DEPLOYTOOLS")==0 and not RTDIST): newname = model[:-4] + ".egg.pz" else: newname = model[:-4] + ".egg" TargetAdd(GetOutputDir()+"/models/"+newname, input="models/"+model) if not PkgSkip("DIRECT") and not RUNTIME: CopyAllFiles(GetOutputDir()+"/models/audio/sfx/", "dmodels/src/audio/sfx/", ".wav") CopyAllFiles(GetOutputDir()+"/models/icons/", "dmodels/src/icons/", ".gif") CopyAllFiles(GetOutputDir()+"/models/maps/", "models/maps/", ".jpg") CopyAllFiles(GetOutputDir()+"/models/maps/", "models/maps/", ".png") CopyAllFiles(GetOutputDir()+"/models/maps/", "models/maps/", ".rgb") CopyAllFiles(GetOutputDir()+"/models/maps/", "models/maps/", ".rgba") CopyAllFiles(GetOutputDir()+"/models/maps/", "dmodels/src/maps/", ".jpg") CopyAllFiles(GetOutputDir()+"/models/maps/", "dmodels/src/maps/", ".png") CopyAllFiles(GetOutputDir()+"/models/maps/", "dmodels/src/maps/", ".rgb") CopyAllFiles(GetOutputDir()+"/models/maps/", "dmodels/src/maps/", ".rgba") # # Build the rtdist. # if (RTDIST): OPTS=['DIR:direct/src/p3d'] TargetAdd('_panda3d', opts=OPTS, input='panda3d.pdef') TargetAdd('_coreapi', opts=OPTS, input='coreapi.pdef') TargetAdd('_thirdparty', opts=OPTS, input='thirdparty.pdef') # # If we have a host URL and distributor, we can make .p3d deployment tools. # if not PkgSkip("DIRECT") and not PkgSkip("DEPLOYTOOLS") and not RUNTIME and not RTDIST and HOST_URL and DISTRIBUTOR: OPTS=['DIR:direct/src/p3d'] TargetAdd('packp3d.p3d', opts=OPTS, input='panda3d.pdef') TargetAdd('pdeploy.p3d', opts=OPTS, input='panda3d.pdef') TargetAdd('pmerge.p3d', opts=OPTS, input='panda3d.pdef') TargetAdd('ppackage.p3d', opts=OPTS, input='panda3d.pdef') TargetAdd('ppatcher.p3d', opts=OPTS, input='panda3d.pdef') ########################################################################################## # # Dependency-Based Distributed Build System. # ########################################################################################## DEPENDENCYQUEUE=[] for target in TARGET_LIST: name = target.name inputs = target.inputs opts = target.opts deps = target.deps DEPENDENCYQUEUE.append([CompileAnything, [name, inputs, opts], [name], deps, []]) def BuildWorker(taskqueue, donequeue): while True: try: task = taskqueue.get(timeout=1) except: ProgressOutput(None, "Waiting for tasks...") task = taskqueue.get() sys.stdout.flush() if (task == 0): return try: task[0](*task[1]) donequeue.put(task) except: donequeue.put(0) def AllSourcesReady(task, pending): sources = task[3] for x in sources: if (x in pending): return 0 sources = task[1][1] for x in sources: if (x in pending): return 0 altsources = task[4] for x in altsources: if (x in pending): return 0 return 1 def ParallelMake(tasklist): # Create the communication queues. donequeue = queue.Queue() taskqueue = queue.Queue() # Build up a table listing all the pending targets #task = [CompileAnything, [name, inputs, opts], [name], deps, []] # task[2] = [name] # task[3] = deps # The python tool package, in particular fltegg seems to throw parallelmake off # A hack for now is to divide the tasklist into two parts, one to be built in parallel # and another subpart to be built sequentially. The most time consuming part of the process # is the c++ code generation anyways. tasklist_seq = [] i = 0 while i < len(tasklist): if tasklist[i][2][0].endswith('.egg') | tasklist[i][2][0].endswith('.egg.pz'): break i += 1 if i < len(tasklist): tasklist_seq = tasklist[i:] tasklist = tasklist[:i] iNumStartingTasks = len(tasklist) pending = {} for task in tasklist: for target in task[2]: pending[target] = 1 # Create the workers for slave in range(THREADCOUNT): th = threading.Thread(target=BuildWorker, args=[taskqueue, donequeue]) th.setDaemon(1) th.start() # Feed tasks to the workers. tasksqueued = 0 while True: if (tasksqueued < THREADCOUNT): extras = [] for task in tasklist: if (tasksqueued < THREADCOUNT) and (AllSourcesReady(task, pending)): if (NeedsBuild(task[2], task[3])): tasksqueued += 1 taskqueue.put(task) else: for target in task[2]: del pending[target] else: extras.append(task) tasklist = extras sys.stdout.flush() if (tasksqueued == 0): break donetask = donequeue.get() if (donetask == 0): exit("Build process aborting.") sys.stdout.flush() tasksqueued -= 1 JustBuilt(donetask[2], donetask[3]) for target in donetask[2]: del pending[target] # Kill the workers. for slave in range(THREADCOUNT): taskqueue.put(0) # Make sure there aren't any unsatisfied tasks if len(tasklist) > 0: exit("Dependency problems: " + str(len(tasklist)) + " tasks not finished. First task unsatisfied: "+str(tasklist[0][2])) SequentialMake(tasklist_seq) def SequentialMake(tasklist): i = 0 for task in tasklist: if (NeedsBuild(task[2], task[3])): task[0](*task[1] + [(i * 100.0) / len(tasklist)]) JustBuilt(task[2], task[3]) i += 1 def RunDependencyQueue(tasklist): if (THREADCOUNT!=0): ParallelMake(tasklist) else: SequentialMake(tasklist) try: RunDependencyQueue(DEPENDENCYQUEUE) finally: SaveDependencyCache() # Run the test suite. if RUNTESTS: cmdstr = BracketNameWithQuotes(SDK["PYTHONEXEC"].replace('\\', '/')) if sys.version_info >= (2, 6): cmdstr += " -B" cmdstr += " -m pytest tests" if GetVerbose(): cmdstr += " --verbose" oscmd(cmdstr) ########################################################################################## # # The Installers # # Under windows, we can build an 'exe' package using NSIS # Under linux, we can build a 'deb' package or an 'rpm' package. # Under OSX, we can make a 'dmg' package. # ########################################################################################## if INSTALLER: ProgressOutput(100.0, "Building installer") from makepackage import MakeInstaller MakeInstaller(version=VERSION, outputdir=GetOutputDir(), optimize=GetOptimize(), compressor=COMPRESSOR, debversion=DEBVERSION, rpmrelease=RPMRELEASE, runtime=RUNTIME) if WHEEL: ProgressOutput(100.0, "Building wheel") from makewheel import makewheel makewheel(WHLVERSION, GetOutputDir()) ########################################################################################## # # Print final status report. # ########################################################################################## WARNINGS.append("Elapsed Time: "+PrettyTime(time.time() - STARTTIME)) printStatus("Makepanda Final Status Report", WARNINGS) print(GetColor("green") + "Build successfully finished, elapsed time: " + PrettyTime(time.time() - STARTTIME) + GetColor())
bsd-3-clause
tttthemanCorp/CardmeleonAppEngine
piston/authentication/basic.py
2267
import binascii from django.contrib.auth import authenticate from django.contrib.auth.models import User, AnonymousUser from django.http import HttpResponse class HttpBasicAuthentication(object): """ Basic HTTP authenticater. Synopsis: Authentication handlers must implement two methods: - `is_authenticated`: Will be called when checking for authentication. Receives a `request` object, please set your `User` object on `request.user`, otherwise return False (or something that evaluates to False.) - `challenge`: In cases where `is_authenticated` returns False, the result of this method will be returned. This will usually be a `HttpResponse` object with some kind of challenge headers and 401 code on it. """ def __init__(self, auth_func=authenticate, realm='API'): self.auth_func = auth_func self.realm = realm def is_authenticated(self, request): auth_string = request.META.get('HTTP_AUTHORIZATION', None) if not auth_string: return False try: (authmeth, auth) = auth_string.split(" ", 1) if not authmeth.lower() == 'basic': return False auth = auth.strip().decode('base64') (username, password) = auth.split(':', 1) except (ValueError, binascii.Error): return False request.user = self.auth_func(username=username, password=password) \ or AnonymousUser() return not request.user in (False, None, AnonymousUser()) def challenge(self): resp = HttpResponse("Authorization Required") resp['WWW-Authenticate'] = 'Basic realm="%s"' % self.realm resp.status_code = 401 return resp def __repr__(self): return u'<HTTPBasic: realm=%s>' % self.realm class HttpBasicSimple(HttpBasicAuthentication): def __init__(self, realm, username, password): self.user = User.objects.get(username=username) self.password = password super(HttpBasicSimple, self).__init__(auth_func=self.hash, realm=realm) def hash(self, username, password): if username == self.user.username and password == self.password: return self.user
bsd-3-clause
highweb-project/highweb-webcl-html5spec
storage/browser/fileapi/file_system_operation_runner.cc
24451
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "storage/browser/fileapi/file_system_operation_runner.h" #include <stdint.h> #include <tuple> #include <utility> #include "base/bind.h" #include "base/macros.h" #include "base/stl_util.h" #include "base/thread_task_runner_handle.h" #include "net/url_request/url_request_context.h" #include "storage/browser/blob/blob_url_request_job_factory.h" #include "storage/browser/blob/shareable_file_reference.h" #include "storage/browser/fileapi/file_observers.h" #include "storage/browser/fileapi/file_stream_writer.h" #include "storage/browser/fileapi/file_system_context.h" #include "storage/browser/fileapi/file_writer_delegate.h" namespace storage { typedef FileSystemOperationRunner::OperationID OperationID; class FileSystemOperationRunner::BeginOperationScoper : public base::SupportsWeakPtr< FileSystemOperationRunner::BeginOperationScoper> { public: BeginOperationScoper() {} private: DISALLOW_COPY_AND_ASSIGN(BeginOperationScoper); }; FileSystemOperationRunner::OperationHandle::OperationHandle() {} FileSystemOperationRunner::OperationHandle::OperationHandle( const OperationHandle& other) = default; FileSystemOperationRunner::OperationHandle::~OperationHandle() {} FileSystemOperationRunner::~FileSystemOperationRunner() { } void FileSystemOperationRunner::Shutdown() { operations_.Clear(); } OperationID FileSystemOperationRunner::CreateFile( const FileSystemURL& url, bool exclusive, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, url); operation->CreateFile( url, exclusive, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::CreateDirectory( const FileSystemURL& url, bool exclusive, bool recursive, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, url); operation->CreateDirectory( url, exclusive, recursive, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::Copy( const FileSystemURL& src_url, const FileSystemURL& dest_url, CopyOrMoveOption option, ErrorBehavior error_behavior, const CopyProgressCallback& progress_callback, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(dest_url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, dest_url); PrepareForRead(handle.id, src_url); operation->Copy(src_url, dest_url, option, error_behavior, progress_callback.is_null() ? CopyProgressCallback() : base::Bind(&FileSystemOperationRunner::OnCopyProgress, AsWeakPtr(), handle, progress_callback), base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::Move( const FileSystemURL& src_url, const FileSystemURL& dest_url, CopyOrMoveOption option, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(dest_url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, dest_url); PrepareForWrite(handle.id, src_url); operation->Move( src_url, dest_url, option, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::DirectoryExists( const FileSystemURL& url, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForRead(handle.id, url); operation->DirectoryExists( url, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::FileExists( const FileSystemURL& url, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForRead(handle.id, url); operation->FileExists( url, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::GetMetadata( const FileSystemURL& url, int fields, const GetMetadataCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidGetMetadata(handle, callback, error, base::File::Info()); return handle.id; } PrepareForRead(handle.id, url); operation->GetMetadata(url, fields, base::Bind(&FileSystemOperationRunner::DidGetMetadata, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::ReadDirectory( const FileSystemURL& url, const ReadDirectoryCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidReadDirectory(handle, callback, error, std::vector<DirectoryEntry>(), false); return handle.id; } PrepareForRead(handle.id, url); operation->ReadDirectory( url, base::Bind(&FileSystemOperationRunner::DidReadDirectory, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::Remove( const FileSystemURL& url, bool recursive, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, url); operation->Remove( url, recursive, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::Write( const net::URLRequestContext* url_request_context, const FileSystemURL& url, scoped_ptr<storage::BlobDataHandle> blob, int64_t offset, const WriteCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidWrite(handle, callback, error, 0, true); return handle.id; } scoped_ptr<FileStreamWriter> writer( file_system_context_->CreateFileStreamWriter(url, offset)); if (!writer) { // Write is not supported. DidWrite(handle, callback, base::File::FILE_ERROR_SECURITY, 0, true); return handle.id; } scoped_ptr<FileWriterDelegate> writer_delegate(new FileWriterDelegate( std::move(writer), url.mount_option().flush_policy())); scoped_ptr<net::URLRequest> blob_request( storage::BlobProtocolHandler::CreateBlobRequest( std::move(blob), url_request_context, writer_delegate.get())); PrepareForWrite(handle.id, url); operation->Write(url, std::move(writer_delegate), std::move(blob_request), base::Bind(&FileSystemOperationRunner::DidWrite, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::Truncate( const FileSystemURL& url, int64_t length, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, url); operation->Truncate( url, length, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } void FileSystemOperationRunner::Cancel( OperationID id, const StatusCallback& callback) { if (ContainsKey(finished_operations_, id)) { DCHECK(!ContainsKey(stray_cancel_callbacks_, id)); stray_cancel_callbacks_[id] = callback; return; } FileSystemOperation* operation = operations_.Lookup(id); if (!operation) { // There is no operation with |id|. callback.Run(base::File::FILE_ERROR_INVALID_OPERATION); return; } operation->Cancel(callback); } OperationID FileSystemOperationRunner::TouchFile( const FileSystemURL& url, const base::Time& last_access_time, const base::Time& last_modified_time, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, url); operation->TouchFile( url, last_access_time, last_modified_time, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::OpenFile( const FileSystemURL& url, int file_flags, const OpenFileCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidOpenFile(handle, callback, base::File(error), base::Closure()); return handle.id; } if (file_flags & (base::File::FLAG_CREATE | base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_OPEN_TRUNCATED | base::File::FLAG_WRITE | base::File::FLAG_EXCLUSIVE_WRITE | base::File::FLAG_DELETE_ON_CLOSE | base::File::FLAG_WRITE_ATTRIBUTES)) { PrepareForWrite(handle.id, url); } else { PrepareForRead(handle.id, url); } operation->OpenFile( url, file_flags, base::Bind(&FileSystemOperationRunner::DidOpenFile, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::CreateSnapshotFile( const FileSystemURL& url, const SnapshotFileCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidCreateSnapshot(handle, callback, error, base::File::Info(), base::FilePath(), NULL); return handle.id; } PrepareForRead(handle.id, url); operation->CreateSnapshotFile( url, base::Bind(&FileSystemOperationRunner::DidCreateSnapshot, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::CopyInForeignFile( const base::FilePath& src_local_disk_path, const FileSystemURL& dest_url, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(dest_url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, dest_url); operation->CopyInForeignFile( src_local_disk_path, dest_url, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::RemoveFile( const FileSystemURL& url, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, url); operation->RemoveFile( url, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::RemoveDirectory( const FileSystemURL& url, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, url); operation->RemoveDirectory( url, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::CopyFileLocal( const FileSystemURL& src_url, const FileSystemURL& dest_url, CopyOrMoveOption option, const CopyFileProgressCallback& progress_callback, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(src_url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForRead(handle.id, src_url); PrepareForWrite(handle.id, dest_url); operation->CopyFileLocal( src_url, dest_url, option, progress_callback, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } OperationID FileSystemOperationRunner::MoveFileLocal( const FileSystemURL& src_url, const FileSystemURL& dest_url, CopyOrMoveOption option, const StatusCallback& callback) { base::File::Error error = base::File::FILE_OK; FileSystemOperation* operation = file_system_context_->CreateFileSystemOperation(src_url, &error); BeginOperationScoper scope; OperationHandle handle = BeginOperation(operation, scope.AsWeakPtr()); if (!operation) { DidFinish(handle, callback, error); return handle.id; } PrepareForWrite(handle.id, src_url); PrepareForWrite(handle.id, dest_url); operation->MoveFileLocal( src_url, dest_url, option, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback)); return handle.id; } base::File::Error FileSystemOperationRunner::SyncGetPlatformPath( const FileSystemURL& url, base::FilePath* platform_path) { base::File::Error error = base::File::FILE_OK; scoped_ptr<FileSystemOperation> operation( file_system_context_->CreateFileSystemOperation(url, &error)); if (!operation.get()) return error; return operation->SyncGetPlatformPath(url, platform_path); } FileSystemOperationRunner::FileSystemOperationRunner( FileSystemContext* file_system_context) : file_system_context_(file_system_context) {} void FileSystemOperationRunner::DidFinish( const OperationHandle& handle, const StatusCallback& callback, base::File::Error rv) { if (handle.scope) { finished_operations_.insert(handle.id); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FileSystemOperationRunner::DidFinish, AsWeakPtr(), handle, callback, rv)); return; } callback.Run(rv); FinishOperation(handle.id); } void FileSystemOperationRunner::DidGetMetadata( const OperationHandle& handle, const GetMetadataCallback& callback, base::File::Error rv, const base::File::Info& file_info) { if (handle.scope) { finished_operations_.insert(handle.id); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FileSystemOperationRunner::DidGetMetadata, AsWeakPtr(), handle, callback, rv, file_info)); return; } callback.Run(rv, file_info); FinishOperation(handle.id); } void FileSystemOperationRunner::DidReadDirectory( const OperationHandle& handle, const ReadDirectoryCallback& callback, base::File::Error rv, const std::vector<DirectoryEntry>& entries, bool has_more) { if (handle.scope) { finished_operations_.insert(handle.id); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FileSystemOperationRunner::DidReadDirectory, AsWeakPtr(), handle, callback, rv, entries, has_more)); return; } callback.Run(rv, entries, has_more); if (rv != base::File::FILE_OK || !has_more) FinishOperation(handle.id); } void FileSystemOperationRunner::DidWrite(const OperationHandle& handle, const WriteCallback& callback, base::File::Error rv, int64_t bytes, bool complete) { if (handle.scope) { finished_operations_.insert(handle.id); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FileSystemOperationRunner::DidWrite, AsWeakPtr(), handle, callback, rv, bytes, complete)); return; } callback.Run(rv, bytes, complete); if (rv != base::File::FILE_OK || complete) FinishOperation(handle.id); } void FileSystemOperationRunner::DidOpenFile( const OperationHandle& handle, const OpenFileCallback& callback, base::File file, const base::Closure& on_close_callback) { if (handle.scope) { finished_operations_.insert(handle.id); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FileSystemOperationRunner::DidOpenFile, AsWeakPtr(), handle, callback, Passed(&file), on_close_callback)); return; } callback.Run(std::move(file), on_close_callback); FinishOperation(handle.id); } void FileSystemOperationRunner::DidCreateSnapshot( const OperationHandle& handle, const SnapshotFileCallback& callback, base::File::Error rv, const base::File::Info& file_info, const base::FilePath& platform_path, const scoped_refptr<storage::ShareableFileReference>& file_ref) { if (handle.scope) { finished_operations_.insert(handle.id); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FileSystemOperationRunner::DidCreateSnapshot, AsWeakPtr(), handle, callback, rv, file_info, platform_path, file_ref)); return; } callback.Run(rv, file_info, platform_path, file_ref); FinishOperation(handle.id); } void FileSystemOperationRunner::OnCopyProgress( const OperationHandle& handle, const CopyProgressCallback& callback, FileSystemOperation::CopyProgressType type, const FileSystemURL& source_url, const FileSystemURL& dest_url, int64_t size) { if (handle.scope) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind( &FileSystemOperationRunner::OnCopyProgress, AsWeakPtr(), handle, callback, type, source_url, dest_url, size)); return; } callback.Run(type, source_url, dest_url, size); } void FileSystemOperationRunner::PrepareForWrite(OperationID id, const FileSystemURL& url) { if (file_system_context_->GetUpdateObservers(url.type())) { file_system_context_->GetUpdateObservers(url.type())->Notify( &FileUpdateObserver::OnStartUpdate, std::make_tuple(url)); } write_target_urls_[id].insert(url); } void FileSystemOperationRunner::PrepareForRead(OperationID id, const FileSystemURL& url) { if (file_system_context_->GetAccessObservers(url.type())) { file_system_context_->GetAccessObservers(url.type())->Notify( &FileAccessObserver::OnAccess, std::make_tuple(url)); } } FileSystemOperationRunner::OperationHandle FileSystemOperationRunner::BeginOperation( FileSystemOperation* operation, base::WeakPtr<BeginOperationScoper> scope) { OperationHandle handle; handle.id = operations_.Add(operation); handle.scope = scope; return handle; } void FileSystemOperationRunner::FinishOperation(OperationID id) { OperationToURLSet::iterator found = write_target_urls_.find(id); if (found != write_target_urls_.end()) { const FileSystemURLSet& urls = found->second; for (FileSystemURLSet::const_iterator iter = urls.begin(); iter != urls.end(); ++iter) { if (file_system_context_->GetUpdateObservers(iter->type())) { file_system_context_->GetUpdateObservers(iter->type())->Notify( &FileUpdateObserver::OnEndUpdate, std::make_tuple(*iter)); } } write_target_urls_.erase(found); } // IDMap::Lookup fails if the operation is NULL, so we don't check // operations_.Lookup(id) here. operations_.Remove(id); finished_operations_.erase(id); // Dispatch stray cancel callback if exists. std::map<OperationID, StatusCallback>::iterator found_cancel = stray_cancel_callbacks_.find(id); if (found_cancel != stray_cancel_callbacks_.end()) { // This cancel has been requested after the operation has finished, // so report that we failed to stop it. found_cancel->second.Run(base::File::FILE_ERROR_INVALID_OPERATION); stray_cancel_callbacks_.erase(found_cancel); } } } // namespace storage
bsd-3-clause
ksclarke/jiiify
src/main/java/info/freelibrary/jiiify/verticles/ImageIndexVerticle.java
3892
package info.freelibrary.jiiify.verticles; import static info.freelibrary.jiiify.Constants.FAILURE_RESPONSE; import static info.freelibrary.jiiify.Constants.FILE_PATH_KEY; import static info.freelibrary.jiiify.Constants.ID_KEY; import static info.freelibrary.jiiify.Constants.IIIF_PATH_KEY; import static info.freelibrary.jiiify.Constants.SOLR_SERVICE_KEY; import static info.freelibrary.jiiify.Constants.SUCCESS_RESPONSE; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.naming.ConfigurationException; import org.javatuples.KeyValue; import info.freelibrary.jiiify.Constants; import info.freelibrary.jiiify.MessageCodes; import info.freelibrary.jiiify.SolrMetadata; import info.freelibrary.jiiify.services.SolrService; import info.freelibrary.jiiify.util.SolrUtils; import info.freelibrary.util.Logger; import info.freelibrary.util.LoggerFactory; import io.vertx.core.AsyncResult; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; /** * A verticle that indexes basic image metadata. * * @author <a href="mailto:ksclarke@ksclarke.io">Kevin S. Clarke</a> */ public class ImageIndexVerticle extends AbstractJiiifyVerticle implements SolrMetadata { private static final Logger LOGGER = LoggerFactory.getLogger(ImageIndexVerticle.class, Constants.MESSAGES); @Override public void start() throws ConfigurationException, IOException { final SolrService service = SolrService.createProxy(vertx, SOLR_SERVICE_KEY); final List<KeyValue<String, ?>> fields = new ArrayList<>(); // We listen for new images that we should add to our browse list getJsonConsumer().handler(message -> { final JsonObject json = message.body(); final String id = json.getString(ID_KEY); final String filePath = json.getString(FILE_PATH_KEY); final String thumbnail = json.getString(IIIF_PATH_KEY); final String action = json.getString(ACTION_TYPE); fields.add(KeyValue.with(ID_KEY, id)); fields.add(KeyValue.with(ITEM_TYPE_KEY, "image")); if (filePath != null) { fields.add(KeyValue.with(FILE_NAME_KEY, new File(filePath).getName())); } if (thumbnail != null) { fields.add(KeyValue.with(THUMBNAIL_KEY, thumbnail)); } if (action.equals(SolrMetadata.INDEX_ACTION)) { LOGGER.debug(MessageCodes.DBG_117, id); service.index(SolrUtils.getSimpleIndexDoc(fields), handler -> { handleResponse(handler, message); }); } else if (action.equals(SolrMetadata.UPDATE_ACTION)) { LOGGER.debug(MessageCodes.DBG_118, id); service.index(SolrUtils.getSimpleUpdateDoc(fields), handler -> { handleResponse(handler, message); }); } else { LOGGER.error(MessageCodes.EXC_085, id); } }).exceptionHandler(exceptionHandler -> { LOGGER.error(exceptionHandler.getMessage(), exceptionHandler); }); } private void handleResponse(final AsyncResult<String> aHandler, final Message<JsonObject> aMessage) { if (aHandler.succeeded()) { LOGGER.debug(MessageCodes.DBG_101, aMessage.body()); aMessage.reply(SUCCESS_RESPONSE); } else { if (aHandler.cause() != null) { LOGGER.error(MessageCodes.EXC_053, aMessage.body(), aHandler.cause().getMessage()); } else { LOGGER.error(MessageCodes.EXC_053, aMessage.body(), LOGGER.getMessage(MessageCodes.EXC_086)); } aMessage.reply(FAILURE_RESPONSE); } } @Override protected Logger getLogger() { return LOGGER; } }
bsd-3-clause
compgen-io/ngsutilsj
src/java/io/compgen/ngsutils/annotation/BedCountAnnotationSource.java
1171
package io.compgen.ngsutils.annotation; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import io.compgen.common.IterUtils; import io.compgen.ngsutils.bed.BedReader; import io.compgen.ngsutils.bed.BedRecord; import io.compgen.ngsutils.bed.BedRecordCount; /** * Loads annotations from a BED file * * @author mbreese * */ public class BedCountAnnotationSource extends AbstractAnnotationSource<BedRecordCount> { public BedCountAnnotationSource(String filename) throws FileNotFoundException, IOException { loadFile(new FileInputStream(new File(filename))); } public BedCountAnnotationSource(InputStream is) throws FileNotFoundException, IOException { loadFile(is); } protected void loadFile(InputStream is) throws IOException { for (BedRecord record: IterUtils.wrap(BedReader.readInputStream(is))) { addAnnotation(record.getCoord(), new BedRecordCount(record)); } } @Override public String[] getAnnotationNames() { return new String[] { "name", "score", "count" }; } }
bsd-3-clause
yubo/govs
cmd/govs/handler.go
8391
/* * Copyright 2016 Xiaomi Corporation. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. * * Authors: Yu Bo <yubo@xiaomi.com> */ package main import ( "flag" "fmt" "os" "github.com/yubo/gotool/flags" "github.com/yubo/govs" ) func init() { flags.CommandLine.Usage = fmt.Sprintf("Usage: %s COMMAND [OPTIONS] host[:port]\n\n", os.Args[0]) // version flags.NewCommand("version", "show dpvs version information", version_handle, flag.ExitOnError) // status cmd := flags.NewCommand("stats", "get dpvs stats io stats", stats_handle, flag.ExitOnError) cmd.StringVar(&govs.CmdOpt.Typ, "t", "io", "type of the stats name(io/w/we/dev/ctl/mem)") cmd.IntVar(&govs.CmdOpt.Id, "i", -1, "id of the stats object") // flush flags.NewCommand("flush", "Flush the virtual service", flush_handle, flag.ExitOnError) // zero cmd = flags.NewCommand("zero", "zero conters in Service/all", zero_handle, flag.ExitOnError) cmd.StringVar(&govs.CmdOpt.TCP, "t", "", "tcp service") cmd.StringVar(&govs.CmdOpt.UDP, "u", "", "udp service") // timeout cmd = flags.NewCommand("timeout", "show/set timeout", timeout_handle, flag.ExitOnError) cmd.StringVar(&govs.CmdOpt.Timeout_s, "set", "", "set <tcp,tcp_fin,udp>") // list cmd = flags.NewCommand("list", "list -t|u host:[port]", list_handle, flag.ExitOnError) cmd.StringVar(&govs.CmdOpt.TCP, "t", "", "tcp service") cmd.StringVar(&govs.CmdOpt.UDP, "u", "", "udp service") cmd.BoolVar(&govs.CmdOpt.L, "G", false, "get local address") // add cmd = flags.NewCommand("add", "add vs/rs/laddr", add_handle, flag.ExitOnError) cmd.StringVar(&govs.CmdOpt.TCP, "t", "", "tcp service") cmd.StringVar(&govs.CmdOpt.UDP, "u", "", "udp service") cmd.Var(&govs.CmdOpt.Netmask, "m", "netmask default 0.0.0.0") cmd.StringVar(&govs.CmdOpt.Sched_name, "sched", "rr", "the service sched name rr/wrr") cmd.UintVar(&govs.CmdOpt.Flags, "flags", 0, "the service flags") // adddest cmd.Var(&govs.CmdOpt.Daddr, "dest", "service-address is host[:port]") cmd.UintVar(&govs.CmdOpt.Conn_flags, "conn_flags", 0, "the conn flags") cmd.IntVar(&govs.CmdOpt.Weight, "weight", 0, "capacity of real server") cmd.UintVar(&govs.CmdOpt.U_threshold, "x", 0, "upper threshold of connections") cmd.UintVar(&govs.CmdOpt.L_threshold, "y", 0, "lower threshold of connections") // addladdr cmd.Var(&govs.CmdOpt.Lip, "laddr", "local-address is host") // edit cmd = flags.NewCommand("edit", "edit vs/rs/laddr", edit_handle, flag.ExitOnError) cmd.StringVar(&govs.CmdOpt.TCP, "t", "", "tcp service") cmd.StringVar(&govs.CmdOpt.UDP, "u", "", "udp service") cmd.StringVar(&govs.CmdOpt.Sched_name, "sched", "rr", "the service sched name") cmd.UintVar(&govs.CmdOpt.Flags, "flags", 0, "the service flags") // editdest cmd.Var(&govs.CmdOpt.Daddr, "dest", "service-address is host[:port]") cmd.UintVar(&govs.CmdOpt.Conn_flags, "conn_flags", 0, "the conn flags") cmd.IntVar(&govs.CmdOpt.Weight, "weight", 0, "capacity of real server") cmd.UintVar(&govs.CmdOpt.U_threshold, "x", 0, "upper threshold of connections") cmd.UintVar(&govs.CmdOpt.L_threshold, "y", 0, "lower threshold of connections") // editladdr cmd.Var(&govs.CmdOpt.Lip, "laddr", "local-address is host") // del cmd = flags.NewCommand("del", "del vs/rs/laddr", del_handle, flag.ExitOnError) cmd.StringVar(&govs.CmdOpt.TCP, "t", "", "tcp service") cmd.StringVar(&govs.CmdOpt.UDP, "u", "", "udp service") // deldest cmd.Var(&govs.CmdOpt.Daddr, "dest", "service-address is host[:port]") // delladdr cmd.Var(&govs.CmdOpt.Lip, "laddr", "local-address is host") } func version_handle(arg interface{}) { if err, version := govs.Get_version(); err != nil { fmt.Println(err) } else { fmt.Println(version) } } func info_handle(arg interface{}) { if err, info := govs.Get_version(); err != nil { fmt.Println(err) } else { fmt.Println(info) } } func timeout_handle(arg interface{}) { opt := arg.(*govs.CallOptions) o := &opt.Opt if o.Timeout_s != "" { if timeout, err := govs.Set_timeout(o); err != nil { fmt.Println(err) } else { fmt.Println(timeout) } } else { if timeout, err := govs.Get_timeout(o); err != nil { fmt.Println(err) } else { fmt.Println(timeout) } } } func list_svc_handle(o *govs.CmdOptions) { ret, err := govs.Get_service(o) if err != nil { fmt.Println(err) return } if ret.Code != 0 { fmt.Println(ret.Msg) return } fmt.Println(govs.Svc_title()) if !o.L { fmt.Println(govs.Dest_title()) } else { fmt.Println(govs.Laddr_title()) } fmt.Println(ret) if !o.L { dests, err := govs.Get_dests(o) if err != nil { fmt.Println(err) return } fmt.Println(dests) } else { laddrs, err := govs.Get_laddrs(o) if err != nil { fmt.Println(err) return } fmt.Println(laddrs) } return } func list_svcs_handle(o *govs.CmdOptions) { ret, err := govs.Get_services(o) if err != nil { fmt.Println(err) return } if ret.Code != 0 { fmt.Println(ret.Msg) return } fmt.Println(govs.Svc_title()) if !o.L { fmt.Println(govs.Dest_title()) } else { fmt.Println(govs.Laddr_title()) } for _, svc := range ret.Services { fmt.Println(svc) o.Addr.Ip = svc.Addr o.Addr.Port = svc.Port o.Protocol = govs.Protocol(svc.Protocol) if !o.L { dests, err := govs.Get_dests(o) if err != nil || dests.Code != 0 || len(dests.Dests) == 0 { //fmt.Println(err) continue } fmt.Println(dests) } else { laddrs, err := govs.Get_laddrs(o) if err != nil || laddrs.Code != 0 || len(laddrs.Laddrs) == 0 { //fmt.Println(err) return } fmt.Println(laddrs) } } } func list_handle(arg interface{}) { opt := arg.(*govs.CallOptions) govs.Parse_service(opt) o := &opt.Opt if o.Addr.Ip != 0 { list_svc_handle(o) return } list_svcs_handle(o) } func flush_handle(arg interface{}) { if reply, err := govs.Set_flush(nil); err != nil { fmt.Println(err) } else { fmt.Println(reply) } } func zero_handle(arg interface{}) { opt := arg.(*govs.CallOptions) govs.Parse_service(opt) if reply, err := govs.Set_zero(&opt.Opt); err != nil { fmt.Println(err) } else { fmt.Println(reply) } } func add_handle(arg interface{}) { var err error var reply *govs.Vs_cmd_r opt := arg.(*govs.CallOptions) if err := govs.Parse_service(opt); err != nil { fmt.Println(err) return } o := &opt.Opt if o.Lip != 0 { reply, err = govs.Set_addladdr(o) } else if o.Daddr.Ip != 0 { reply, err = govs.Set_adddest(o) } else { reply, err = govs.Set_add(o) } if err != nil { fmt.Println(err) } else { fmt.Println(reply) } } func edit_handle(arg interface{}) { var err error var reply *govs.Vs_cmd_r opt := arg.(*govs.CallOptions) if err := govs.Parse_service(opt); err != nil { fmt.Println(err) return } o := &opt.Opt if o.Daddr.Ip != 0 { reply, err = govs.Set_editdest(o) } else { reply, err = govs.Set_edit(o) } if err != nil { fmt.Println(err) } else { fmt.Println(reply) } } func del_handle(arg interface{}) { var err error var reply *govs.Vs_cmd_r opt := arg.(*govs.CallOptions) if err := govs.Parse_service(opt); err != nil { fmt.Println(err) return } o := &opt.Opt if o.Lip != 0 { reply, err = govs.Set_delladdr(o) } else if o.Daddr.Ip != 0 { reply, err = govs.Set_deldest(o) } else { reply, err = govs.Set_del(o) } if err != nil { fmt.Println(err) } else { fmt.Println(reply) } } func stats_handle(arg interface{}) { id := govs.CmdOpt.Id switch govs.CmdOpt.Typ { case "io": relay, err := govs.Get_stats_io(id) if err != nil { fmt.Println(err) return } fmt.Printf("%+v\n", relay) case "w": relay, err := govs.Get_stats_worker(id) if err != nil { fmt.Println(err) return } fmt.Println(relay) case "we": relay, err := govs.Get_estats_worker(id) if err != nil { fmt.Println(err) return } fmt.Println(relay) case "dev": relay, err := govs.Get_stats_dev(id) if err != nil { fmt.Println(err) return } fmt.Println(relay) case "ctl": relay, err := govs.Get_stats_ctl() if err != nil { fmt.Println(err) return } fmt.Println(relay) case "mem": relay, err := govs.Get_stats_mem() if err != nil { fmt.Println(err) return } fmt.Println(relay) default: fmt.Println("govs stats -t io/worker/dev/ctl") } }
bsd-3-clause
kimniyom/history
controllers/SearchController.php
4480
<?php namespace app\controllers; use Yii; use yii\web\Controller; use yii\helpers\Json; use app\models\Google_map; use yii\helpers\Url; class SearchController extends Controller { public $layout = "admin-lte"; public function actionIndex() { return $this->render('index'); } //คนหาคนตาม CID ชื่อ นามสกุล ดึงมาทั้งจังหวัด public function actionSearch_patient() { $model = new \app\models\SearchModel(); $request = \Yii::$app->request; $cid = $request->post('cid'); $name = $request->post('name'); $surname = $request->post('lname'); $result = $model->PatientSearch(trim($cid), trim($name), trim($surname)); return $this->renderPartial('patient', [ "result" => $result, ]); } //ข้อมูลประวัติการรับบริการ public function actionGet_service() { $cid = \Yii::$app->request->post('cid'); $model = new \app\models\SearchModel(); //Add Log $columns = array( "person_cid" => $cid, "owner" => Yii::$app->session['userId'], "create_date" => date("Y-m-d H:i:s") ); Yii::$app->db->createCommand() ->insert("log_open",$columns) ->execute(); $result = $model->GetService($cid); return $this->renderPartial('service', [ "result" => $result, ]); } //ข้อมูลประวัติการรับบริการ public function actionGet_service_full() { $cid = \Yii::$app->request->post('cid'); $model = new \app\models\SearchModel(); $result = $model->GetService($cid); return $this->renderPartial('service_full', [ "result" => $result, ]); } //ข้อมูลเบื้องต้น public function actionGet_detail_person() { $address_model = new \app\models\Address(); $Map = new Google_map(); $Map->SetCenter("16.940225, 99.074165"); $cid = \Yii::$app->request->post('cid'); $model = new \app\models\SearchModel(); $result = $model->GetPersonInfo($cid); $address = $address_model->Get_address_person($result['HOSPCODE'], $result['PID']); //find()->where(['HOSPCODE' => $result['HOSPCODE'], 'PID' => $result['PID']])->one(); //$link = Url::toRoute('search/kml_ampur_all', true); $latlong = $address_model->Get_home($result['HID'], $result['HOSPCODE']); if ($latlong['LATITUDE'] == "" || $latlong['LONGITUDE'] == "") { $lat = ""; $long = ""; $Markers = ""; } else { $lat = $latlong['LATITUDE']; $long = $latlong['LONGITUDE']; $content = $result['PERSONNAME']; $Markers = $Map->SetMarker("1", $lat, $long, $content, ''); } $Map->SetArea(''); $Map->Zoom("10"); $Map->Maptype(""); //Type ROADMAP,SATELLITE ,HYBRID ,TERRAIN $Marker = $Markers; $Map->Marker($Marker); $map_person = $Map->Render(); //echo $map; return $this->renderPartial('detail_person', [ "model" => $result, "address" => $address, "map" => $map_person, ]); } //ข้อมูลได้รับการวินิจฉัย public function actionGet_diag() { $hospCode = \Yii::$app->request->post('hospcode'); $pid = \Yii::$app->request->post('pid'); $seq = \Yii::$app->request->post('seq'); $model = new \app\models\SearchModel(); $result = $model->GetDiag($hospCode, $pid, $seq); return $this->renderPartial('diagnosis', [ "result" => $result, ]); } //ข้อมูลการรับบริการในคิวนั้น public function actionGet_service_detail() { $hospCode = \Yii::$app->request->post('hospcode'); $cid = \Yii::$app->request->post('cid'); $seq = \Yii::$app->request->post('seq'); $model = new \app\models\SearchModel(); $result = $model->GetServiceDetail($hospCode, $cid, $seq); return $this->renderPartial('service_detail', [ "model" => $result, ]); } }
bsd-3-clause
antoinecarme/pyaf
tests/artificial/transf_None/trend_Lag1Trend/cycle_12/ar_12/test_artificial_32_None_Lag1Trend_12_12_100.py
261
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 12, transform = "None", sigma = 0.0, exog_count = 100, ar_order = 12);
bsd-3-clause
volpejoaquin/yan
php/pacienteDelInfo.php
296
<?php $link = mysql_connect('localhost', 'root', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('yani') or die('Could not select database'); mysql_query("DELETE FROM paciente_info WHERE id = ".$_POST['id']); // Closing connection mysql_close($link); ?>
bsd-3-clause
bdezonia/zorbage
src/main/java/example/OutOfBoundsData.java
10705
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (c) 2016-2021 Barry DeZonia All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the <copyright holder> 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 <COPYRIGHT HOLDER> 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. */ package example; import nom.bdezonia.zorbage.algebra.G; import nom.bdezonia.zorbage.algorithm.ConvolveND; import nom.bdezonia.zorbage.algorithm.FFT; import nom.bdezonia.zorbage.algorithm.Fill; import nom.bdezonia.zorbage.data.DimensionedDataSource; import nom.bdezonia.zorbage.data.DimensionedStorage; import nom.bdezonia.zorbage.data.ProcedurePaddedDimensionedDataSource; import nom.bdezonia.zorbage.datasource.FixedSizeDataSource; import nom.bdezonia.zorbage.datasource.IndexedDataSource; import nom.bdezonia.zorbage.datasource.ProcedurePaddedDataSource; import nom.bdezonia.zorbage.oob.nd.ConstantNdOOB; import nom.bdezonia.zorbage.oob.nd.CyclicNdOOB; import nom.bdezonia.zorbage.oob.nd.EdgeNdOOB; import nom.bdezonia.zorbage.oob.nd.MirrorNdOOB; import nom.bdezonia.zorbage.oob.nd.NanNdOOB; import nom.bdezonia.zorbage.oob.nd.ZeroNdOOB; import nom.bdezonia.zorbage.oob.oned.ConstantOOB; import nom.bdezonia.zorbage.oob.oned.CyclicOOB; import nom.bdezonia.zorbage.oob.oned.EdgeOOB; import nom.bdezonia.zorbage.oob.oned.MirrorOOB; import nom.bdezonia.zorbage.oob.oned.NanOOB; import nom.bdezonia.zorbage.oob.oned.ZeroOOB; import nom.bdezonia.zorbage.type.complex.float32.ComplexFloat32Member; import nom.bdezonia.zorbage.type.real.float32.Float32Algebra; import nom.bdezonia.zorbage.type.real.float32.Float32Member; /** * @author Barry DeZonia */ class OutOfBoundsData { /* * Sometimes you use an algorithm that can query data point values which are out of * the bounds of the dataset of interest. Zorbage provides a mechanism for padding * datasets so that (probably neutral) values can pass through an algorithm without * corrupting the output values. */ /* * This can be apparent in 1-d datasets if you consider the case of finding the FFT * of a dataset. The current FFT algorithm requires an input dataset whose length * is a power of 2. In order to pass any size list of data to the FFT algorithm * Zorbage allows you to pad a dataset with appropriate values. Then you wrap the * dataset so that any observer thinks its list's length is a power of two. Maybe * an example will be helpful here. */ void example1() { // Make an unusual size list IndexedDataSource<ComplexFloat32Member> data = nom.bdezonia.zorbage.storage.Storage.allocate(G.CFLT.construct(), 413); // 413 long weirdSize = data.size(); // 512 long perfectSize = FFT.enclosingPowerOf2(weirdSize); // Fill our input list with random data Fill.compute(G.CFLT, G.CFLT.random(), data); // Now make sure querying it outside its bounds will return the value zero. The // ZeroOOB procedure does the heavy lifting. The ProcedurePaddedDataSource returns // values from its underlying data source when the coordinates queried are within // its bounds and returns the result from a procedure call when they are out. IndexedDataSource<ComplexFloat32Member> paddedData = new ProcedurePaddedDataSource<>( G.CFLT, data, new ZeroOOB<>(G.CFLT, data.size())); // The FFT wants a power of two size. make the list have a perfect size. IndexedDataSource<ComplexFloat32Member> perfectSizedData = new FixedSizeDataSource<>(perfectSize, paddedData); // Allocate the destination data list IndexedDataSource<ComplexFloat32Member> fftData = nom.bdezonia.zorbage.storage.Storage.allocate(G.CFLT.construct(), perfectSize); // The fft algorithm will hit every location (0 to 511). The out of bounds procedure // will return 0 when the original data is queried beyond location 412. The extra // zero values will have no effect on the final results FFT.compute(G.CFLT, G.FLT, perfectSizedData, fftData); } // There are other predefined 1-d out of bounds behaviors. Here is a quick tour of them. @SuppressWarnings("unused") void example2() { IndexedDataSource<Float32Member> data = nom.bdezonia.zorbage.storage.Storage.allocate(G.FLT.construct(), 100); // pad with a constant like 0.4 IndexedDataSource<Float32Member> constantPad = new ProcedurePaddedDataSource<>( G.FLT, data, new ConstantOOB<>(G.FLT, data.size(), G.FLT.construct("0.4"))); // pad in a cyclic fashion // imagine list = [0, 1, 2, 3] // then with cyclic oob // list[3] == 3 // list[4] == 0 // list[5] == 1 // list[6] == 2 // list[7] == 3 // list[8] == 0 // list[9] == 1 IndexedDataSource<Float32Member> cyclicPad = new ProcedurePaddedDataSource<>( G.FLT, data, new CyclicOOB<>(data)); // pad from the edges // imagine list = [1, 2, 3, 4] // then with edge oob // etc. // list[-2] == 1 // list[-1] == 1 // list[0] == 1 // list[1] == 2 // list[2] == 3 // list[3] == 4 // list[4] == 4 // list[5] == 4 // etc. IndexedDataSource<Float32Member> edgePad = new ProcedurePaddedDataSource<>( G.FLT, data, new EdgeOOB<>(data)); // pad in a mirrored fashion // imagine list = [1, 2, 3, 4] // then with mirrored oob // etc. // list[-6] == 3 // list[-5] == 4 // list[-4] == 4 // list[-3] == 3 // list[-2] == 2 // list[-1] == 1 // list[0] == 1 // list[1] == 2 // list[2] == 3 // list[3] == 4 // list[4] == 4 // list[5] == 3 // list[4] == 2 // list[5] == 1 // list[4] == 1 // list[5] == 2 // etc. IndexedDataSource<Float32Member> mirrorPad = new ProcedurePaddedDataSource<>( G.FLT, data, new MirrorOOB<>(data)); // pad with NaN IndexedDataSource<Float32Member> nanPad = new ProcedurePaddedDataSource<>( G.FLT, data, new NanOOB<>(G.FLT, data.size())); // pad with 0.0 IndexedDataSource<Float32Member> zeroPad = new ProcedurePaddedDataSource<>( G.FLT, data, new ZeroOOB<>(G.FLT, data.size())); } /* * Zorbage has similar capabilities in the n-d domain rather than 1-d domain. One * example where these become useful is when doing convolutions on n-d datasets. */ void example3() { // original dims of input data long[] dims = new long[] {640,480}; // make input DimensionedDataSource<Float32Member> input = DimensionedStorage.allocate(G.FLT.construct(), dims); // assume here we've filled it with some values // now pad it so id we request an out of bounds pixel we get a 0 ProcedurePaddedDimensionedDataSource<Float32Algebra,Float32Member> paddedInput = new ProcedurePaddedDimensionedDataSource<>( G.FLT, input, new ZeroNdOOB<>(G.FLT, input)); // make an output dataset that has the same dims as the original dataset DimensionedDataSource<Float32Member> output = DimensionedStorage.allocate(G.FLT.construct(), dims); // make a 3x3 convolution filter DimensionedDataSource<Float32Member> filter = DimensionedStorage.allocate(G.FLT.construct(), new long[] {3,3}); // assume we've set the nine filter values to something sensible // run a convolution. the convolve algorithm will slide the window around on the // padded image and will poke outside the bounds of the original image. the padded // image just returns zero for these places. and this has no effect on the computed // output values. ConvolveND.compute(G.FLT, filter, paddedInput, output); } // There are other predefined n-d out of bounds behaviors. Here is a quick tour of them. // Note that their behavior matches their 1-d counterparts documented above. The // following code just shows you how to construct them. @SuppressWarnings("unused") void example4() { // make input DimensionedDataSource<Float32Member> input = DimensionedStorage.allocate(G.FLT.construct(), new long[] {1024, 1024}); // make constant padded input DimensionedDataSource<Float32Member> constantPad = new ProcedurePaddedDimensionedDataSource<>( G.FLT, input, new ConstantNdOOB<>(G.FLT, input, G.FLT.construct("1.3"))); // make cyclic padded input DimensionedDataSource<Float32Member> cyclicPad = new ProcedurePaddedDimensionedDataSource<>( G.FLT, input, new CyclicNdOOB<>(input)); // make edge padded input DimensionedDataSource<Float32Member> edgePad = new ProcedurePaddedDimensionedDataSource<>( G.FLT, input, new EdgeNdOOB<>(input)); // make mirror padded input DimensionedDataSource<Float32Member> mirrorPad = new ProcedurePaddedDimensionedDataSource<>( G.FLT, input, new MirrorNdOOB<>(input)); // make NaN padded input DimensionedDataSource<Float32Member> nanPad = new ProcedurePaddedDimensionedDataSource<>( G.FLT, input, new NanNdOOB<>(G.FLT, input)); // make zero padded input DimensionedDataSource<Float32Member> zeroPad = new ProcedurePaddedDimensionedDataSource<>( G.FLT, input, new ZeroNdOOB<>(G.FLT, input)); } }
bsd-3-clause
CartoDB/cartodb
lib/assets/javascripts/new-dashboard/store/mutations/tileset.js
183
export function setLoadingTilesets (state) { state.loadingTilesets = true; } export function setTilesets (state, data) { state.tilesets = data; state.loadingTilesets = false; }
bsd-3-clause
souldigital/silverstripe-eventmanagement
code/pages/RegistrableEvent.php
10566
<?php /** * A calendar event that can people can register to attend. */ class RegistrableEvent extends CalendarEvent { private static $db = array( 'TicketGenerator' => 'Varchar(255)', 'OneRegPerEmail' => 'Boolean', 'RequireLoggedIn' => 'Boolean', 'RegistrationTimeLimit' => 'Int', 'RegEmailConfirm' => 'Boolean', 'EmailConfirmMessage' => 'Varchar(255)', 'ConfirmTimeLimit' => 'Int', 'AfterConfirmTitle' => 'Varchar(255)', 'AfterConfirmContent' => 'HTMLText', 'UnRegEmailConfirm' => 'Boolean', 'AfterConfUnregTitle' => 'Varchar(255)', 'AfterConfUnregContent' => 'HTMLText', 'EmailNotifyChanges' => 'Boolean', 'NotifyChangeFields' => 'Text', 'AfterRegTitle' => 'Varchar(255)', 'AfterRegContent' => 'HTMLText', 'AfterUnregTitle' => 'Varchar(255)', 'AfterUnregContent' => 'HTMLText' ); private static $has_many = array( 'Tickets' => 'EventTicket', 'DateTimes' => 'RegistrableDateTime' ); private static $defaults = array( 'RegistrationTimeLimit' => 900, 'AfterRegTitle' => 'Thanks For Registering', 'AfterRegContent' => '<p>Thanks for registering! We look forward to seeing you.</p>', 'EmailConfirmMessage' => 'Important: You must check your emails and confirm your registration before it is valid.', 'ConfirmTimeLimit' => 21600, 'AfterConfirmTitle' => 'Registration Confirmed', 'AfterConfirmContent' => '<p>Thanks! Your registration has been confirmed</p>', 'AfterUnregTitle' => 'Registration Canceled', 'AfterUnregContent' => '<p>Your registration has been canceled.</p>', 'AfterConfUnregTitle' => 'Un-Registration Confirmed', 'AfterConfUnregContent' => '<p>Your registration has been canceled.</p>', 'NotifyChangeFields' => 'StartDate,EndDate,StartTime,EndTime' ); private static $icon = "eventmanagement/images/date_edit.png"; private static $description = "An event that can be registered for."; public function getCMSFields() { SiteTree::disableCMSFieldsExtensions(); $fields = parent::getCMSFields(); SiteTree::enableCMSFieldsExtensions(); $fields->insertAfter( new ToggleCompositeField( 'AfterRegistrationContent', _t('EventRegistration.AFTER_REG_CONTENT', 'After Registration Content'), array( new TextField('AfterRegTitle', _t('EventRegistration.TITLE', 'Title')), new HtmlEditorField('AfterRegContent', _t('EventRegistration.CONTENT', 'Content')) ) ), 'Content' ); $fields->insertAfter( new ToggleCompositeField( 'AfterUnRegistrationContent', _t('EventRegistration.AFTER_UNREG_CONTENT', 'After Un-Registration Content'), array( new TextField('AfterUnregTitle', _t('EventRegistration.TITLE', 'Title')), new HtmlEditorField('AfterUnregContent', _t('EventRegistration.CONTENT', 'Content')) ) ), 'AfterRegistrationContent' ); if ($this->RegEmailConfirm) { $fields->addFieldToTab('Root.Main', new ToggleCompositeField( 'AfterRegistrationConfirmation', _t('EventRegistration.AFTER_REG_CONFIRM_CONTENT', 'After Registration Confirmation Content'), array( new TextField('AfterConfirmTitle', _t('EventRegistration.TITLE', 'Title')), new HtmlEditorField('AfterConfirmContent', _t('EventRegistration.CONTENT', 'Content')) ) )); } if ($this->UnRegEmailConfirm) { $fields->addFieldToTab('Root.Main', new ToggleCompositeField( 'AfterUnRegistrationConfirmation', _t('EventRegistration.AFTER_UNREG_CONFIRM_CONTENT', 'After Un-Registration Confirmation Content'), array( new TextField('AfterConfUnregTitle', _t('EventRegistration.TITLE', 'Title')), new HtmlEditorField('AfterConfUnregContent', _t('EventRegistration.CONTENT', 'Content')) ) )); } $fields->addFieldToTab('Root.Tickets', new GridField( 'Tickets', 'Ticket Types', $this->Tickets(), GridFieldConfig_RecordEditor::create() )); $generators = ClassInfo::implementorsOf('EventRegistrationTicketGenerator'); if ($generators) { foreach ($generators as $generator) { $instance = new $generator(); $generators[$generator] = $instance->getGeneratorTitle(); } $generator = new DropdownField( 'TicketGenerator', _t('EventRegistration.TICKET_GENERATOR', 'Ticket generator'), $generators ); $generator->setEmptyString(_t('EventManagement.NONE', '(None)')); $generator->setDescription(_t( 'EventManagement.TICKET_GENERATOR_NOTE', 'The ticket generator is used to generate a ticket file for the user to download.' )); $fields->addFieldToTab('Root.Tickets', $generator); } $regGridFieldConfig = GridFieldConfig_Base::create() ->removeComponentsByType('GridFieldAddNewButton') ->removeComponentsByType('GridFieldDeleteAction') ->addComponents( new GridFieldButtonRow('after'), new GridFieldPrintButton('buttons-after-left'), new GridFieldExportButton('buttons-after-left') ); $regGrids = array( new GridField('Registrations', _t('EventManagement.REGISTRATIONS', 'Registrations'), $this->DateTimes()->relation('Registrations')->filter('Status', 'Valid'), $regGridFieldConfig ) ); $cancelled = $this->DateTimes() ->relation('Registrations') ->filter('Status', 'Canceled'); if($cancelled->exists()){ $regGrids[] = new GridField('CanceledRegistrations', _t('EventManagement.CANCELLATIONS', 'Cancellations'), $cancelled, $regGridFieldConfig ); } $fields->addFieldsToTab('Root.Registrations', $regGrids); if ($this->RegEmailConfirm) { $fields->addFieldToTab('Root.Registrations', new ToggleCompositeField( 'UnconfirmedRegistrations', _t('EventManagement.UNCONFIRMED_REGISTRATIONS', 'Unconfirmed Registrations'), array( new GridField( 'UnconfirmedRegistrations', '', $this->DateTimes()->relation('Registrations')->filter('Status', 'Unconfirmed') ) ) )); } $this->extend('updateCMSFields',$fields); return $fields; } public function getSettingsFields() { $fields = parent::getSettingsFields(); Requirements::javascript('eventmanagement/javascript/cms.js'); $fields->addFieldsToTab('Root.Registration', array( new CheckboxField( 'OneRegPerEmail', _t('EventManagement.ONE_REG_PER_EMAIL', 'Limit to one registration per email address?') ), new CheckboxField( 'RequireLoggedIn', _t('EventManagement.REQUIRE_LOGGED_IN', 'Require users to be logged in to register?') ), $limit = new NumericField( 'RegistrationTimeLimit', _t('EventManagement.REG_TIME_LIMIT', 'Registration time limit') ), )); $limit->setDescription(_t( 'EventManagement.REG_TIME_LIMIT_NOTE', 'The time limit to complete registration, in seconds. Set to 0 to disable place holding.' )); $fields->addFieldsToTab('Root.Email', array( new CheckboxField( 'RegEmailConfirm', _t('EventManagement.REQ_EMAIL_CONFIRM', 'Require email confirmation to complete free registrations?') ), $info = new TextField( 'EmailConfirmMessage', _t('EventManagement.EMAIL_CONFIRM_INFO', 'Email confirmation information') ), $limit = new NumericField( 'ConfirmTimeLimit', _t('EventManagement.EMAIL_CONFIRM_TIME_LIMIT', 'Email confirmation time limit') ), new CheckboxField( 'UnRegEmailConfirm', _t('EventManagement.REQ_UN_REG_EMAIL_CONFIRM', 'Require email confirmation to un-register?') ), new CheckboxField( 'EmailNotifyChanges', _t('EventManagement.EMAIL_NOTIFY_CHANGES', 'Notify registered users of event changes via email?') ), new CheckboxSetField( 'NotifyChangeFields', _t('EventManagement.NOTIFY_CHANGE_IN', 'Notify of changes in'), singleton('RegistrableDateTime')->fieldLabels(false) ) )); $info->setDescription(_t( 'EventManagement.EMAIL_CONFIRM_INFO_NOTE', 'This message is displayed to users to let them know they need to confirm their registration.' )); $limit->setDescription(_t( 'EventManagement.CONFIRM_TIME_LIMIT_NOTE', 'The time limit to conform registration, in seconds. Set to 0 for no limit.' )); return $fields; } /** * Check if this event can currently be registered for. * @return boolean */ function canRegister(){ if($this->OneRegPerEmail && $registered = $this->hasRegisteredValid()){ return false; } foreach($this->DateTimes() as $time){ $tickets = $time->getAvailableTickets(); if($tickets && $tickets->exists()){ return true; } } return false; } function getRegistrations(){ $registrations = new ArrayList(); foreach($this->DateTimes() as $dt) $registrations->merge($dt->Registrations()->toArray()); return $registrations; } /** * @param null $member * @return types */ function hasRegistered($member = null){ if(!$member || !$member instanceof Member) $member = Member::currentUser(); if(!$member) return false; return ( $this->getRegistrations()->filter(array("MemberID"=>$member->ID))->first() ); } function hasRegisteredValid($member = null){ if(!$member || !$member instanceof Member) $member = Member::currentUser(); if(!$member) return false; return ( $this->getRegistrations()->filter(array("MemberID"=>$member->ID, "Status"=>"Valid"))->first() ); } } class RegistrableEvent_Controller extends CalendarEvent_Controller { public static $allowed_actions = array( 'details', 'registration' ); /** * Shows details for an individual event date time, as well as forms for * registering and un-registering. * * @param SS_HTTPRequest $request * @return array */ public function details($request) { $id = $request->param('ID'); if (!ctype_digit($id)) { $this->httpError(404); } $time = RegistrableDateTime::get()->byID($id); if (!$time || $time->EventID != $this->ID) { $this->httpError(404); } $request->shift(); $request->shiftAllParams(); return new EventTimeDetailsController($this, $time); } /** * Allows a user to view the details of their registration. * * @param SS_HTTPRequest $request * @return EventRegistrationDetailsController */ public function registration($request) { $id = $request->param('ID'); if (!ctype_digit($id)) { $this->httpError(404); } $rego = EventRegistration::get()->byID($id); if (!$rego || $rego->Time()->EventID != $this->ID) { $this->httpError(404); } $request->shift(); $request->shiftAllParams(); return new EventRegistrationDetailsController($this, $rego); } }
bsd-3-clause
psiinon/addons-server
src/olympia/files/tests/test_tasks.py
3866
# -*- coding: utf-8 -*- from unittest import mock import tempfile import zipfile from django.conf import settings from olympia.amo.tests import TestCase from olympia.files.tasks import repack_fileupload from olympia.files.tests.test_models import UploadTest from olympia.files.utils import SafeZip class TestRepackFileUpload(UploadTest, TestCase): @mock.patch('olympia.files.tasks.move_stored_file') @mock.patch('olympia.files.tasks.get_sha256') @mock.patch('olympia.files.tasks.shutil') @mock.patch.object(SafeZip, 'extract_to_dest') def test_not_repacking_non_xpi_files_with_mocks( self, extract_to_dest_mock, shutil_mock, get_sha256_mock, move_stored_file_mock): """Test we're not repacking non-xpi files""" upload = self.get_upload('search.xml') old_hash = upload.hash assert old_hash.startswith('sha256:') fake_results = {'errors': 0} repack_fileupload(fake_results, upload.pk) assert not extract_to_dest_mock.called assert not shutil_mock.make_archive.called assert not get_sha256_mock.called assert not move_stored_file_mock.called upload.reload() assert upload.hash == old_hash # Hasn't changed. @mock.patch('olympia.files.tasks.move_stored_file') @mock.patch('olympia.files.tasks.get_sha256') @mock.patch('olympia.files.tasks.shutil') @mock.patch.object(SafeZip, 'extract_to_dest') def test_repacking_xpi_files_with_mocks( self, extract_to_dest_mock, shutil_mock, get_sha256_mock, move_stored_file_mock): """Opposite of test_not_repacking_non_xpi_files() (using same mocks)""" upload = self.get_upload('webextension.xpi') get_sha256_mock.return_value = 'fakehashfrommock' fake_results = {'errors': 0} repack_fileupload(fake_results, upload.pk) assert extract_to_dest_mock.called tempdir = extract_to_dest_mock.call_args[0][0] assert tempdir.startswith(tempfile.gettempdir()) # On local filesystem assert not tempdir.startswith(settings.TMP_PATH) # Not on EFS assert shutil_mock.make_archive.called assert get_sha256_mock.called assert move_stored_file_mock.called upload.reload() assert upload.hash == 'sha256:fakehashfrommock' def test_repacking_xpi_files(self): """Test that repack_fileupload() does repack xpi files (no mocks)""" # Take an extension with a directory structure, so that we can test # that structure is restored once the file has been moved. upload = self.get_upload('unicode-filenames.xpi') original_hash = upload.hash fake_results = {'errors': 0} repack_fileupload(fake_results, upload.pk) upload.reload() assert upload.hash.startswith('sha256:') assert upload.hash != original_hash # Test zip contents with zipfile.ZipFile(upload.path) as z: contents = sorted(z.namelist()) assert contents == [ u'chrome.manifest', u'chrome/', u'chrome/content/', u'chrome/content/ff-overlay.js', u'chrome/content/ff-overlay.xul', u'chrome/content/overlay.js', u'chrome/locale/', u'chrome/locale/en-US/', u'chrome/locale/en-US/overlay.dtd', u'chrome/locale/en-US/overlay.properties', u'chrome/skin/', u'chrome/skin/overlay.css', u'install.rdf', u'삮' ] # Spot-check an individual file. info = z.getinfo('install.rdf') assert info.file_size == 717 assert info.compress_size < info.file_size assert info.compress_type == zipfile.ZIP_DEFLATED
bsd-3-clause
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/service/alert/com/salesforce/dva/argus/service/alert/testing/TestResults.java
125
package com.salesforce.dva.argus.service.alert.com.salesforce.dva.argus.service.alert.testing; public class TestResults { }
bsd-3-clause
ostashevdv/yii2
tests/unit/extensions/elasticsearch/ElasticSearchTestCase.php
1382
<?php namespace yiiunit\extensions\elasticsearch; use Yii; use yii\elasticsearch\Connection; use yiiunit\TestCase; Yii::setAlias('@yii/elasticsearch', __DIR__ . '/../../../../extensions/elasticsearch'); /** * ElasticSearchTestCase is the base class for all elasticsearch related test cases */ class ElasticSearchTestCase extends TestCase { protected function setUp() { $this->mockApplication(); $databases = $this->getParam('databases'); $params = isset($databases['elasticsearch']) ? $databases['elasticsearch'] : null; if ($params === null || !isset($params['dsn'])) { $this->markTestSkipped('No elasticsearch server connection configured.'); } $dsn = explode('/', $params['dsn']); $host = $dsn[2]; if (strpos($host, ':')===false) { $host .= ':9200'; } if (!@stream_socket_client($host, $errorNumber, $errorDescription, 0.5)) { $this->markTestSkipped('No elasticsearch server running at ' . $params['dsn'] . ' : ' . $errorNumber . ' - ' . $errorDescription); } parent::setUp(); } /** * @param boolean $reset whether to clean up the test database * @return Connection */ public function getConnection($reset = true) { $databases = $this->getParam('databases'); $params = isset($databases['elasticsearch']) ? $databases['elasticsearch'] : []; $db = new Connection(); if ($reset) { $db->open(); } return $db; } }
bsd-3-clause
SalesforceFoundation/Cumulus
force-app/main/default/lwc/geFormWidgetRowAllocation/geFormWidgetRowAllocation.js
5642
import {LightningElement, api, track} from 'lwc'; import GeLabelService from 'c/geLabelService'; import { apiNameFor, isEmpty, isNumeric } from 'c/utilCommon'; import DI_DONATION_AMOUNT_FIELD from '@salesforce/schema/DataImport__c.Donation_Amount__c'; import ALLOCATION_OBJECT from '@salesforce/schema/Allocation__c'; import AMOUNT_FIELD from '@salesforce/schema/Allocation__c.Amount__c'; import PERCENT_FIELD from '@salesforce/schema/Allocation__c.Percent__c'; import GAU_FIELD from '@salesforce/schema/Allocation__c.General_Accounting_Unit__c'; const DATA_FIELD_NAME_SELECTOR = 'data-fieldname'; export default class GeFormWidgetRowAllocation extends LightningElement { @api rowIndex; @api row; @api fieldList; @api disabled; _remainingAmount; @api get remainingAmount() { return this._remainingAmount; } set remainingAmount(value) { if (value === this._remainingAmount || isEmpty(value)) { return; } this._remainingAmount = value; if (this.row.isDefaultGAU) { this.handleFieldValueChange({ detail: { fieldApiName: this.allocationAmountFieldApiName, value: this.remainingAmount } }); } } _totalAmountFromState; _widgetDataFromState; @api get widgetDataFromState(){ return this._widgetDataFromState; } set widgetDataFromState(value) { this._widgetDataFromState = value; this._totalAmountFromState = value[this.donationAmountFieldApiName]; this.reallocateAmountByPercent(); } CUSTOM_LABELS = GeLabelService.CUSTOM_LABELS; reallocateAmountByPercent() { const percentValue = this.row.record[this.allocationPercentageFieldApiName]; if(isNumeric(percentValue) && percentValue >= 0) { this.handleFieldValueChange({ detail: { fieldApiName: this.allocationAmountFieldApiName, value: this.calculateAmountFromPercent(percentValue) } }); } } handleFieldValueChange = (event) => { let changedField = {}; let dependentFieldChanges = {}; // Handle event from a DOM element if (event.target && event.target.hasAttribute(DATA_FIELD_NAME_SELECTOR)) { changedField = { fieldApiName: event.target.getAttribute(DATA_FIELD_NAME_SELECTOR), value: event.target.value } // Handle when the function is called from other functions } else { changedField = event.detail; } if (changedField.fieldApiName === this.allocationPercentageFieldApiName) { dependentFieldChanges = {... {[this.allocationAmountFieldApiName]: this.calculateAmountFromPercent(changedField.value)} }; } this.dispatchEvent(new CustomEvent('rowvaluechange', { detail: { rowIndex: this.rowIndex, changedFieldAndValue: { [changedField.fieldApiName] : changedField.value, ...dependentFieldChanges } } })); } calculateAmountFromPercent(percentValue) { const percentDecimal = parseFloat(percentValue) / 100; // convert to cents instead of dollars, avoids floating point problems const totalInCents = this._totalAmountFromState * 100; return Math.round(totalInCents * percentDecimal) / 100 } remove() { const { rowIndex, row } = this; this.dispatchEvent(new CustomEvent('remove', { detail: { rowIndex, row } })); } get isRemovable() { return this.disabled !== true; } get percentCustomLabel() { return this.CUSTOM_LABELS.commonPercent; } get donationAmountFieldApiName() { return apiNameFor(DI_DONATION_AMOUNT_FIELD); } get allocationObjectApiName() { return apiNameFor(ALLOCATION_OBJECT); } get gauFieldApiName() { return apiNameFor(GAU_FIELD); } get gauValue() { return this.row.record[apiNameFor(GAU_FIELD)]; } get allocationAmountFieldApiName() { return apiNameFor(AMOUNT_FIELD); } get amountValue() { return this.row.record[apiNameFor(AMOUNT_FIELD)]; } get allocationPercentageFieldApiName() { return apiNameFor(PERCENT_FIELD); } get percentValue() { return this.row.record[apiNameFor(PERCENT_FIELD)]; } get shouldDisablePercent() { if (this.row.disabled || (isEmpty(this.row.record[apiNameFor(PERCENT_FIELD)]) && Number.parseFloat(this.row.record[apiNameFor(AMOUNT_FIELD)]) > 0)) { return true; } } get shouldDisableAmount() { if (this.row.disabled || (!isEmpty(this.row.record[apiNameFor(PERCENT_FIELD)]) && Number.parseFloat(this.row.record[apiNameFor(PERCENT_FIELD)]) > 0)) { return true; } } get shouldDisableGAULookup() { return this.row.disabled; } get qaLocatorDeleteRow() { return `button ${this.CUSTOM_LABELS.commonDelete} ${this.rowIndex}`; } get qaLocatorGAU() { return `autocomplete General Accounting Unit ${this.rowIndex}`; } get qaLocatorAllocationAmount() { return `input Amount ${this.rowIndex}`; } get qaLocatorAllocationPercent() { return `input ${this.percentCustomLabel} ${this.rowIndex}`; } }
bsd-3-clause
dmerejkowsky/qibuild
python/qibuild/test/projects/installme/foo.cpp
204
/* * Copyright (c) 2012-2015 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ int foo() { return 42; }
bsd-3-clause
NCIP/annotation-and-image-markup
AimPlugin3.0.4/AIM.Annotation/Configuration/AimSettings.cs
3715
#region License //L // 2007 - 2013 Copyright Northwestern University // // Distributed under the OSI-approved BSD 3-Clause License. // See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details. //L #endregion using System.Configuration; using System.Drawing; using ClearCanvas.Desktop; using ClearCanvas.ImageViewer.Mathematics; using GeneralUtilities.Collections; namespace AIM.Annotation.Configuration { [SettingsGroupDescription("AIM Settings")] [SettingsProvider(typeof(ClearCanvas.Common.Configuration.StandardSettingsProvider))] public sealed partial class AimSettings { private AimSettings() { ApplicationSettingsRegistry.Instance.RegisterInstance(this); if (LoginNameMarkupColors == null) LoginNameMarkupColors = new XmlSerializableStringToColorDictionary(); if (Parameters == null) Parameters = new XmlSerializableStringDictionary(); } public string ActualAnnotationStoreFolder { get { return StoreXmlInMyDocuments ? System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "AIM Annotations") : LocalAnnotationsFolder; } } public string AnnotationQueuesFolder { get { return System.IO.Path.Combine(ActualAnnotationStoreFolder, "queue"); } } public Color GetAimGraphicColorForUser(string username) { Color color; if (LoginNameMarkupColors.ContainsKey(username)) { color = LoginNameMarkupColors[username]; } else { color = GetAimGraphicDefaultColorForUser(username); } return color; } public Color GetAimGraphicDefaultColorForUser(string username) { Color color; if (UseRandomDefaultMarkupColor) color = CreateColorFromStringHash(username); else color = DefaultMarkupColor; return color; } /// <summary> /// Selects a random, non-red color based on the hashcode of a string /// </summary> /// <param name="stringValue">A string to be used as a seed for the random color</param> /// <returns>A random color based on the input string</returns> public static Color CreateColorFromStringHash(string stringValue) { var color = Color.Yellow; if (!string.IsNullOrEmpty(stringValue)) { // Build random vector representing rgb color based on username var randSeed = stringValue.GetHashCode(); var rand = new System.Random(randSeed); var colorVector = new Vector3D((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()); // Keep the color (vector) from being too close to red (x) so it doesn't conflict with the selection color if (colorVector.Y > colorVector.Z) { if (colorVector.X > colorVector.Y) colorVector = new Vector3D(colorVector.Z, colorVector.Y, colorVector.Z); } else if (colorVector.Z > colorVector.Y) { if (colorVector.X > colorVector.Z) colorVector = new Vector3D(colorVector.Y, colorVector.Y, colorVector.Z); } // Make sure color isn't too dark if (colorVector.Magnitude < 1f) colorVector *= (1f / colorVector.Magnitude); // Make sure color components stay within bounds if (colorVector.X > 1) colorVector = new Vector3D(1f, colorVector.Y, colorVector.Z); if (colorVector.Y > 1) colorVector = new Vector3D(colorVector.X, 1f, colorVector.Z); if (colorVector.Z > 1) colorVector = new Vector3D(colorVector.X, colorVector.Y, 1f); color = Color.FromArgb(255, (int)(colorVector.X * 255), (int)(colorVector.Y * 255), (int)(colorVector.Z * 255)); } return color; } } }
bsd-3-clause
zooming-tan/Project-AENEAS
Project-AENEAS/taskapp/celery.py
867
from __future__ import absolute_import import os from celery import Celery from django.apps import AppConfig from django.conf import settings if not settings.configured: # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") # pragma: no cover app = Celery('Project-AENEAS') class CeleryConfig(AppConfig): name = 'Project-AENEAS.taskapp' verbose_name = 'Celery Config' def ready(self): # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) # pragma: no cover
bsd-3-clause
lutece-platform/lutece-core
src/test/java/fr/paris/lutece/portal/web/dashboard/AdminDashboardJspBeanTest.java
11786
/* * Copyright (c) 2002-2022, City of Paris * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice * and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of 'Mairie de Paris' nor 'Lutece' 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 HOLDERS 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. * * License 1.0 */ package fr.paris.lutece.portal.web.dashboard; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; import org.springframework.mock.web.MockHttpServletRequest; import fr.paris.lutece.portal.business.dashboard.AdminDashboardFactory; import fr.paris.lutece.portal.business.dashboard.AdminDashboardHome; import fr.paris.lutece.portal.business.user.AdminUser; import fr.paris.lutece.portal.business.user.AdminUserHome; import fr.paris.lutece.portal.service.admin.AccessDeniedException; import fr.paris.lutece.portal.service.admin.AdminAuthenticationService; import fr.paris.lutece.portal.service.admin.PasswordResetException; import fr.paris.lutece.portal.service.dashboard.admin.IAdminDashboardComponent; import fr.paris.lutece.portal.service.security.SecurityTokenService; import fr.paris.lutece.test.LuteceTestCase; import fr.paris.lutece.test.Utils; /** * AdminDashboardJspBean Test Class * */ public class AdminDashboardJspBeanTest extends LuteceTestCase { private AdminDashboardJspBean instance; private IAdminDashboardComponent _dashboard; @Override protected void setUp( ) throws Exception { super.setUp( ); instance = new AdminDashboardJspBean( ); _dashboard = new TestAdminDashboardCompoent( ); _dashboard.setName( getRandomName( ) ); AdminDashboardFactory.registerDashboardComponent( _dashboard ); AdminDashboardHome.create( _dashboard ); } @Override protected void tearDown( ) throws Exception { AdminDashboardHome.remove( _dashboard.getName( ) ); // TODO : dashboard should be unregistered super.tearDown( ); } private String getRandomName( ) { Random rand = new SecureRandom( ); BigInteger bigInt = new BigInteger( 128, rand ); return "junit" + bigInt.toString( 36 ); } /** * Test of getAdminDashboards method, of class fr.paris.lutece.portal.web.dashboard.AdminDashboardJspBean. * * @throws Exception * e */ public void testGetAdminDashboards( ) throws Exception { MockHttpServletRequest request = new MockHttpServletRequest( ); AdminUser user = AdminUserHome.findUserByLogin( "admin" ); AdminAuthenticationService.getInstance( ).registerUser( request, user ); instance = new AdminDashboardJspBean( ); // should not throw on freemarker templating String adminDashboards = instance.getAdminDashboards( request ); assertNotNull( adminDashboards ); assertFalse( "".equals( adminDashboards ) ); } public void testGetManageDashboards( ) throws PasswordResetException, AccessDeniedException { MockHttpServletRequest request = new MockHttpServletRequest( ); Utils.registerAdminUserWithRigth( request, new AdminUser( ), AdminDashboardJspBean.RIGHT_MANAGE_ADMINDASHBOARD ); instance.init( request, AdminDashboardJspBean.RIGHT_MANAGE_ADMINDASHBOARD ); assertNotNull( instance.getManageDashboards( request ) ); } public void testDoMoveAdminDashboard( ) throws AccessDeniedException { IAdminDashboardComponent stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertNotNull( stored ); assertEquals( 0, stored.getOrder( ) ); assertEquals( 0, stored.getZone( ) ); MockHttpServletRequest request = new MockHttpServletRequest( ); request.setParameter( "dashboard_name", _dashboard.getName( ) ); request.setParameter( "dashboard_order", "-1" ); request.setParameter( "dashboard_column", "-1" ); request.setParameter( SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance( ).getToken( request, "/admin/dashboard/admin/manage_dashboards.html" ) ); instance.doMoveAdminDashboard( request ); stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertNotNull( stored ); assertEquals( 1, stored.getOrder( ) ); assertEquals( -1, stored.getZone( ) ); } public void testDoMoveAdminDashboardInvalidToken( ) throws AccessDeniedException { IAdminDashboardComponent stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertNotNull( stored ); assertEquals( 0, stored.getOrder( ) ); assertEquals( 0, stored.getZone( ) ); MockHttpServletRequest request = new MockHttpServletRequest( ); request.setParameter( "dashboard_name", _dashboard.getName( ) ); request.setParameter( "dashboard_order", "-1" ); request.setParameter( "dashboard_column", "-1" ); request.setParameter( SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance( ).getToken( request, "/admin/dashboard/admin/manage_dashboards.html" ) + "b" ); try { instance.doMoveAdminDashboard( request ); fail( "Should have thrown" ); } catch( AccessDeniedException e ) { stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertNotNull( stored ); assertEquals( 0, stored.getOrder( ) ); assertEquals( 0, stored.getZone( ) ); } } public void testDoMoveAdminDashboardNoToken( ) throws AccessDeniedException { IAdminDashboardComponent stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertNotNull( stored ); assertEquals( 0, stored.getOrder( ) ); assertEquals( 0, stored.getZone( ) ); MockHttpServletRequest request = new MockHttpServletRequest( ); request.setParameter( "dashboard_name", _dashboard.getName( ) ); request.setParameter( "dashboard_order", "-1" ); request.setParameter( "dashboard_column", "-1" ); try { instance.doMoveAdminDashboard( request ); fail( "Should have thrown" ); } catch( AccessDeniedException e ) { stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertNotNull( stored ); assertEquals( 0, stored.getOrder( ) ); assertEquals( 0, stored.getZone( ) ); } } public void testDoReorderColumn( ) throws AccessDeniedException { IAdminDashboardComponent stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertNotNull( stored ); assertEquals( 0, stored.getOrder( ) ); assertEquals( 0, stored.getZone( ) ); int nZone = AdminDashboardHome.findColumns( ).stream( ).max( Integer::compare ).orElse( 1 ); stored.setZone( nZone ); stored.setOrder( -1 ); AdminDashboardHome.update( stored ); stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertEquals( -1, stored.getOrder( ) ); assertEquals( nZone, stored.getZone( ) ); MockHttpServletRequest request = new MockHttpServletRequest( ); request.setParameter( "column", Integer.toString( nZone ) ); request.setParameter( SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance( ).getToken( request, "/admin/dashboard/admin/manage_dashboards.html" ) ); instance.doReorderColumn( request ); stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertEquals( 1, stored.getOrder( ) ); assertEquals( nZone, stored.getZone( ) ); } public void testDoReorderColumnInvalidToken( ) throws AccessDeniedException { IAdminDashboardComponent stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertNotNull( stored ); assertEquals( 0, stored.getOrder( ) ); assertEquals( 0, stored.getZone( ) ); int nZone = AdminDashboardHome.findColumns( ).stream( ).max( Integer::compare ).orElse( 0 ) + 1; stored.setZone( nZone ); stored.setOrder( -1 ); AdminDashboardHome.update( stored ); stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertEquals( -1, stored.getOrder( ) ); assertEquals( nZone, stored.getZone( ) ); MockHttpServletRequest request = new MockHttpServletRequest( ); request.setParameter( "column", Integer.toString( nZone ) ); request.setParameter( SecurityTokenService.PARAMETER_TOKEN, SecurityTokenService.getInstance( ).getToken( request, "/admin/dashboard/admin/manage_dashboards.html" ) + "b" ); try { instance.doReorderColumn( request ); fail( "Should have thrown" ); } catch( AccessDeniedException e ) { stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertEquals( -1, stored.getOrder( ) ); assertEquals( nZone, stored.getZone( ) ); } } public void testDoReorderColumnNoToken( ) throws AccessDeniedException { IAdminDashboardComponent stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertNotNull( stored ); assertEquals( 0, stored.getOrder( ) ); assertEquals( 0, stored.getZone( ) ); int nZone = AdminDashboardHome.findColumns( ).stream( ).max( Integer::compare ).orElse( 0 ) + 1; stored.setZone( nZone ); stored.setOrder( -1 ); AdminDashboardHome.update( stored ); stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertEquals( -1, stored.getOrder( ) ); assertEquals( nZone, stored.getZone( ) ); MockHttpServletRequest request = new MockHttpServletRequest( ); request.setParameter( "column", Integer.toString( nZone ) ); try { instance.doReorderColumn( request ); fail( "Should have thrown" ); } catch( AccessDeniedException e ) { stored = AdminDashboardHome.findByPrimaryKey( _dashboard.getName( ) ); assertEquals( -1, stored.getOrder( ) ); assertEquals( nZone, stored.getZone( ) ); } } }
bsd-3-clause
marks12/Installer
autoload_classmap.php
465
<?php // Generated by ZF2's ./bin/classmap_generator.php return array( 'Installer\Module' => __DIR__ . '/Module.php', 'Installer\Controller\InstallerController' => __DIR__ . '/src/Installer/Controller/InstallerController.php', 'InstallerTest\Framework\TestCase' => __DIR__ . '/tests/Installer/Framework/TestCase.php', 'InstallerTest\SampleTest' => __DIR__ . '/tests/Installer/SampleTest.php', );
bsd-3-clause
m-ober/byceps
tests/blueprints/user_message/test_address_formatting.py
1202
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from unittest.mock import patch import pytest from byceps.services.user_message import service as user_message_service from tests.conftest import database_recreated from tests.helpers import ( app_context, create_email_config, create_site, create_user, ) def test_recipient_formatting(site, params): screen_name, email_address, expected = params user = create_user(screen_name, email_address=email_address) message = user_message_service.create_message( user.id, user.id, '', '', site.id ) assert message.recipients == [expected] @pytest.fixture(params=[ ('Alice', 'alice@example.com', 'Alice <alice@example.com>'), ('<AngleInvestor>', 'angleinvestor@example.com', '"<AngleInvestor>" <angleinvestor@example.com>'), ('-=]YOLO[=-', 'yolo@example.com', '"-=]YOLO[=-" <yolo@example.com>'), ]) def params(request): yield request.param @pytest.fixture(scope='module') def site(db): with app_context(): with database_recreated(db): create_email_config() site = create_site() yield site
bsd-3-clause
myGrid/t2-server-jar
src/main/java/uk/org/taverna/server/client/ServerException.java
2074
/* * Copyright (c) 2010, 2011 The University of Manchester, UK. * * 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 names of The University of Manchester 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. */ package uk.org.taverna.server.client; /** * This is the abstract superclass of all the exceptions generated by code in * this package. * * @author Robert Haines */ public abstract class ServerException extends RuntimeException { private static final long serialVersionUID = 1L; /** * Constructs a new server exception with the specified detail message. * * @param message */ public ServerException(String message) { super(message); } }
bsd-3-clause
theghostbel/pimcore
website_demo/views/scripts/advanced/search.php
3239
<?php if(!$this->getParam("q")) { ?> <?php $this->template("/content/default.php"); ?> <?php } else { ?> <?php $this->template("/includes/content-headline.php"); ?> <?php } ?> <div> <form class="form-search" method="get"> <input name="q" type="text" class="input-medium search-query" value="<?= $this->getParam("q") ?>"> <button type="submit" name="submit" class="btn"><?php echo $this->translate("Search"); ?></button> </form> <?php if ($this->paginator) { ?> <?php $facets = $this->result->getFacets(); ?> <?php if(!empty($facets)) { ?> <div> Facets: <?php foreach ($facets as $label => $anchor) { ?> <a href="<?= $this->url(array('facet' => $label, "page" => null)); ?>"><?= $anchor ?></a> <?php } ?> </div> <?php } ?> <?php foreach ($this->paginator as $item) { ?> <!-- see class Pimcore_Google_Cse_Item for all possible properties --> <div class="media <?php echo $item->getType(); ?>"> <?php if($item->getImage()) { ?> <!-- if an image is present this can be simply a string or an internal asset object --> <?php if($item->getImage() instanceof Asset) { ?> <a class="pull-left" href="<?php echo $item->getLink() ?>"> <img class="media-object" src="<?php echo $item->getImage()->getThumbnail("newsList"); ?>"> </a> <?php } else { ?> <a class="pull-left" href="<?php echo $item->getLink() ?>"> <img width="64" src="<?php echo $item->getImage() ?>" /> </a> <?php } ?> <?php } ?> <div class="media-body"> <h4 class="media-heading"> <a href="<?= $item->getLink() ?>"> <!-- if there's a document set for this result use the original title without suffixes ... --> <!-- the same can be done with the description and every other element relating to the document --> <?php if($item->getDocument() && $item->getDocument()->getTitle()) { ?> <?= $item->getDocument()->getTitle() ?> <?php } else { ?> <?= $item->getTitle() ?> <?php } ?> </a> </h4> <?= $item->getHtmlSnippet() ?> <br /> <small><?= $item->getHtmlFormattedUrl(); ?></small> </div> </div> <?php } ?> <?= $this->paginationControl($this->paginator, "Sliding", "includes/paging.php"); ?> <?php } else if ($this->getParam("q")) { ?> <div> Sorry, something seems to went wrong ... </div> <?php } else { ?> <div> Type your keyword and press search </div> <?php } ?> </div>
bsd-3-clause
alexcomput/ZF2Project
module/SONUser/Module.php
1296
<?php namespace SONUser; use Zend\Mvc\MvcEvent; use Zend\Mail\Transport\Smtp as SmtpTransport; use Zend\Mail\Transport\SmtpOptions; class Module { public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } public function getServiceConfig() { return array( 'factories' => array( 'SONUser\Mail\Transport' => function ($sm) { $config = $sm->get('Config'); $transport = new SmtpTransport; $options = new SmtpOptions($config['mail']); $transport->setOptions($options); return $transport; }, 'SONUser\Service\User' => function ($sm) { return new Service\User($sm->get('Doctrine\ORM\EntityManager'), $sm->get('SONUser\Mail\Transport'), $sm->get('View')); } ) ); } }
bsd-3-clause
tivv/pgjdbc
org/postgresql/ssl/jdbc3/AbstractJdbc3MakeSSL.java
2174
/*------------------------------------------------------------------------- * * Copyright (c) 2004-2011, PostgreSQL Global Development Group * * *------------------------------------------------------------------------- */ package org.postgresql.ssl.jdbc3; import java.util.Properties; import java.io.IOException; import java.net.Socket; import java.lang.reflect.Constructor; import javax.net.ssl.SSLSocketFactory; import org.postgresql.core.PGStream; import org.postgresql.core.Logger; import org.postgresql.util.GT; import org.postgresql.util.PSQLState; import org.postgresql.util.PSQLException; public class AbstractJdbc3MakeSSL { public static void convert(PGStream stream, Properties info, Logger logger) throws IOException, PSQLException { logger.debug("converting regular socket connection to ssl"); SSLSocketFactory factory; // Use the default factory if no specific factory is requested // String classname = info.getProperty("sslfactory"); if (classname == null) { factory = (SSLSocketFactory)SSLSocketFactory.getDefault(); } else { Object[] args = {info.getProperty("sslfactoryarg")}; Constructor ctor; Class factoryClass; try { factoryClass = Class.forName(classname); try { ctor = factoryClass.getConstructor(new Class[]{String.class}); } catch (NoSuchMethodException nsme) { ctor = factoryClass.getConstructor((Class[])null); args = null; } factory = (SSLSocketFactory)ctor.newInstance(args); } catch (Exception e) { throw new PSQLException(GT.tr("The SSLSocketFactory class provided {0} could not be instantiated.", classname), PSQLState.CONNECTION_FAILURE, e); } } Socket newConnection = factory.createSocket(stream.getSocket(), stream.getHost(), stream.getPort(), true); stream.changeSocket(newConnection); } }
bsd-3-clause
rriggio/joule
joule/template.py
5892
#!/usr/bin/env python # # Copyright (c) 2013, Roberto Riggio # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the CREATE-NET 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 CREATE-NET ''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 CREATE-NET 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. """ The Joule Template generator. It generates a Joule descriptor to be used with the Joule Daemon(s) and with the Joule Profiler. The generated descriptor defines two probes and a list of rates and packet sizes. Stints are defined as all the possible permutations between the rates list and the packets sizes list. It is possible to define also the duration of each stint. By default the descriptor is ~/joule.json. Command Line Arguments: --joule, -j: output joule descriptor, e.g. ~/joule.json --probea, -a: probe A's IP Address, e.g. 192.168.1.1 --probeb, -b: probe B's IP Address, e.g. 192.168.1.2 --rates, -r: list of transmission rates, e.g. "0.1 0.5 1" --sizes, -s: list probe sizes in bytes (UDP payload), e.g. "64 128 256" --duration, -d: probe duration in seconds, e.g. 30 The default behavior is the following: template -j ./joule.json -a 127.0.0.1 \ -b 127.0.0.1 \ -r "0.1 0.5 1 2 5 10 15 20 25 30 35 40" \ -s "32 64 128 256 384 512 640 768 1024 1280 1460 1534 1788 2048" \ -d 30 """ import os import json import optparse import logging DEFAULT_PROBE_A = "127.0.0.1" DEFAULT_PROBE_B = "127.0.0.1" DEFAULT_RATES = "0.1 0.5 1 2 5 10 15 20 25 30 35 40" DEFAULT_SIZES = "64 128 256 384 512 640 768 1024 1280 1460 1534 1788 2048" DEFAULT_DURATION = 30 DEFAULT_JOULE = './joule.json' LOG_FORMAT = '%(asctime)-15s %(message)s' def main(): """ Launcher method. """ parser = optparse.OptionParser() parser.add_option('--joule', '-j', dest="joule", default=DEFAULT_JOULE) parser.add_option('--probea', '-a', dest="probea", default=DEFAULT_PROBE_A) parser.add_option('--probeb', '-b', dest="probeb", default=DEFAULT_PROBE_B) parser.add_option('--rates', '-r', dest="rates", default=DEFAULT_RATES) parser.add_option('--sizes', '-s', dest="sizes", default=DEFAULT_SIZES) parser.add_option('--duration', '-d', dest="duration", type="int", default=DEFAULT_DURATION) parser.add_option('--verbose', '-v', action="store_true", dest="verbose", default=False) parser.add_option('--log', '-l', dest="log") options, _ = parser.parse_args() if options.verbose: logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT, filename=options.log, filemode='w') else: logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, filename=options.log, filemode='w') joule = {'probes' : {}, 'models' : {}, 'stints' : []} for rate in options.rates.split(" "): for size in options.sizes.split(" "): stint = { "bitrate_mbps": float(rate), "dst": "A", "duration_s": options.duration, "packetsize_bytes": int(size), "src": "B" } joule['stints'].append(stint) stint = { "bitrate_mbps": float(rate), "dst": "B", "duration_s": options.duration, "packetsize_bytes": int(size), "src": "A" } joule['stints'].append(stint) joule['idle'] = {"duration_s": options.duration} joule['probes'] = { "A": { "ip": options.probea, "receiver": options.probeb, "sender_port": 9997, "receiver_port": 9998, "receiver_control": 6666, "sender_control": 6667 }, "B": { "ip": options.probeb, "receiver": options.probea, "sender_port": 9998, "receiver_port": 9997, "receiver_control": 7777, "sender_control": 7778 } } joule['models'] = { "TX": { "src": "A", "dst": "B" }, "RX": { "src": "B", "dst": "A" } } with open(os.path.expanduser(options.joule), 'w') as data_file: json.dump(joule, data_file, sort_keys=True, indent=4, separators=(',', ': ')) if __name__ == "__main__": main()
bsd-3-clause
sgraham/nope
chrome/browser/extensions/api/developer_private/developer_private_api.cc
47150
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/developer_private/developer_private_api.h" #include "apps/app_load_service.h" #include "apps/saved_files_service.h" #include "base/base64.h" #include "base/bind.h" #include "base/files/file_util.h" #include "base/lazy_instance.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/extensions/api/developer_private/developer_private_mangle.h" #include "chrome/browser/extensions/api/developer_private/entry_picker.h" #include "chrome/browser/extensions/api/developer_private/extension_info_generator.h" #include "chrome/browser/extensions/api/file_handlers/app_file_handler_util.h" #include "chrome/browser/extensions/devtools_util.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_ui_util.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/shared_module_service.h" #include "chrome/browser/extensions/unpacked_installer.h" #include "chrome/browser/extensions/updater/extension_updater.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/extensions/api/developer_private.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/api/device_permissions_manager.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/extension_error.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/file_highlighter.h" #include "extensions/browser/management_policy.h" #include "extensions/browser/notification_types.h" #include "extensions/browser/warning_service.h" #include "extensions/common/constants.h" #include "extensions/common/extension_resource.h" #include "extensions/common/extension_set.h" #include "extensions/common/feature_switch.h" #include "extensions/common/install_warning.h" #include "extensions/common/manifest.h" #include "extensions/common/manifest_handlers/icons_handler.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/grit/extensions_browser_resources.h" #include "storage/browser/fileapi/external_mount_points.h" #include "storage/browser/fileapi/file_system_context.h" #include "storage/browser/fileapi/file_system_operation.h" #include "storage/browser/fileapi/file_system_operation_runner.h" #include "storage/browser/fileapi/isolated_context.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" namespace extensions { namespace developer_private = api::developer_private; namespace { const char kNoSuchExtensionError[] = "No such extension."; const char kSupervisedUserError[] = "Supervised users cannot modify extension settings."; const char kCannotModifyPolicyExtensionError[] = "Cannot modify the extension by policy."; const char kRequiresUserGestureError[] = "This action requires a user gesture."; const char kCouldNotShowSelectFileDialogError[] = "Could not show a file chooser."; const char kFileSelectionCanceled[] = "File selection was canceled."; const char kNoSuchRendererError[] = "No such renderer."; const char kInvalidPathError[] = "Invalid path."; const char kManifestKeyIsRequiredError[] = "The 'manifestKey' argument is required for manifest files."; const char kUnpackedAppsFolder[] = "apps_target"; const char kManifestFile[] = "manifest.json"; ExtensionService* GetExtensionService(content::BrowserContext* context) { return ExtensionSystem::Get(context)->extension_service(); } ExtensionUpdater* GetExtensionUpdater(Profile* profile) { return GetExtensionService(profile)->updater(); } GURL GetImageURLFromData(const std::string& contents) { std::string contents_base64; base::Base64Encode(contents, &contents_base64); // TODO(dvh): make use of content::kDataScheme. Filed as crbug/297301. const char kDataURLPrefix[] = "data:;base64,"; return GURL(kDataURLPrefix + contents_base64); } GURL GetDefaultImageURL(developer_private::ItemType type) { int icon_resource_id; switch (type) { case developer::ITEM_TYPE_LEGACY_PACKAGED_APP: case developer::ITEM_TYPE_HOSTED_APP: case developer::ITEM_TYPE_PACKAGED_APP: icon_resource_id = IDR_APP_DEFAULT_ICON; break; default: icon_resource_id = IDR_EXTENSION_DEFAULT_ICON; break; } return GetImageURLFromData( ResourceBundle::GetSharedInstance().GetRawDataResourceForScale( icon_resource_id, ui::SCALE_FACTOR_100P).as_string()); } // TODO(dvh): This code should be refactored and moved to // extensions::ImageLoader. Also a resize should be performed to avoid // potential huge URLs: crbug/297298. GURL ToDataURL(const base::FilePath& path, developer_private::ItemType type) { std::string contents; if (path.empty() || !base::ReadFileToString(path, &contents)) return GetDefaultImageURL(type); return GetImageURLFromData(contents); } std::string GetExtensionID(const content::RenderViewHost* render_view_host) { if (!render_view_host->GetSiteInstance()) return std::string(); return render_view_host->GetSiteInstance()->GetSiteURL().host(); } void BroadcastItemStateChanged(content::BrowserContext* browser_context, developer::EventType event_type, const std::string& item_id) { developer::EventData event_data; event_data.event_type = event_type; event_data.item_id = item_id; scoped_ptr<base::ListValue> args(new base::ListValue()); args->Append(event_data.ToValue().release()); scoped_ptr<Event> event(new Event( developer_private::OnItemStateChanged::kEventName, args.Pass())); EventRouter::Get(browser_context)->BroadcastEvent(event.Pass()); } std::string ReadFileToString(const base::FilePath& path) { std::string data; ignore_result(base::ReadFileToString(path, &data)); return data; } } // namespace namespace AllowFileAccess = api::developer_private::AllowFileAccess; namespace AllowIncognito = api::developer_private::AllowIncognito; namespace ChoosePath = api::developer_private::ChoosePath; namespace GetItemsInfo = api::developer_private::GetItemsInfo; namespace Inspect = api::developer_private::Inspect; namespace PackDirectory = api::developer_private::PackDirectory; namespace Reload = api::developer_private::Reload; static base::LazyInstance<BrowserContextKeyedAPIFactory<DeveloperPrivateAPI> > g_factory = LAZY_INSTANCE_INITIALIZER; // static BrowserContextKeyedAPIFactory<DeveloperPrivateAPI>* DeveloperPrivateAPI::GetFactoryInstance() { return g_factory.Pointer(); } // static DeveloperPrivateAPI* DeveloperPrivateAPI::Get( content::BrowserContext* context) { return GetFactoryInstance()->Get(context); } DeveloperPrivateAPI::DeveloperPrivateAPI(content::BrowserContext* context) : profile_(Profile::FromBrowserContext(context)) { RegisterNotifications(); } DeveloperPrivateEventRouter::DeveloperPrivateEventRouter(Profile* profile) : extension_registry_observer_(this), profile_(profile) { registrar_.Add(this, extensions::NOTIFICATION_EXTENSION_VIEW_REGISTERED, content::Source<Profile>(profile_)); registrar_.Add(this, extensions::NOTIFICATION_EXTENSION_VIEW_UNREGISTERED, content::Source<Profile>(profile_)); // TODO(limasdf): Use scoped_observer instead. ErrorConsole::Get(profile)->AddObserver(this); extension_registry_observer_.Add(ExtensionRegistry::Get(profile_)); } DeveloperPrivateEventRouter::~DeveloperPrivateEventRouter() { ErrorConsole::Get(profile_)->RemoveObserver(this); } void DeveloperPrivateEventRouter::AddExtensionId( const std::string& extension_id) { extension_ids_.insert(extension_id); } void DeveloperPrivateEventRouter::RemoveExtensionId( const std::string& extension_id) { extension_ids_.erase(extension_id); } void DeveloperPrivateEventRouter::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { Profile* profile = content::Source<Profile>(source).ptr(); CHECK(profile); CHECK(profile_->IsSameProfile(profile)); developer::EventData event_data; switch (type) { case extensions::NOTIFICATION_EXTENSION_VIEW_UNREGISTERED: { event_data.event_type = developer::EVENT_TYPE_VIEW_UNREGISTERED; event_data.item_id = GetExtensionID( content::Details<const content::RenderViewHost>(details).ptr()); break; } case extensions::NOTIFICATION_EXTENSION_VIEW_REGISTERED: { event_data.event_type = developer::EVENT_TYPE_VIEW_REGISTERED; event_data.item_id = GetExtensionID( content::Details<const content::RenderViewHost>(details).ptr()); break; } default: NOTREACHED(); return; } BroadcastItemStateChanged(profile, event_data.event_type, event_data.item_id); } void DeveloperPrivateEventRouter::OnExtensionLoaded( content::BrowserContext* browser_context, const Extension* extension) { DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context))); BroadcastItemStateChanged( browser_context, developer::EVENT_TYPE_LOADED, extension->id()); } void DeveloperPrivateEventRouter::OnExtensionUnloaded( content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionInfo::Reason reason) { DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context))); BroadcastItemStateChanged( browser_context, developer::EVENT_TYPE_UNLOADED, extension->id()); } void DeveloperPrivateEventRouter::OnExtensionWillBeInstalled( content::BrowserContext* browser_context, const Extension* extension, bool is_update, bool from_ephemeral, const std::string& old_name) { DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context))); BroadcastItemStateChanged( browser_context, developer::EVENT_TYPE_INSTALLED, extension->id()); } void DeveloperPrivateEventRouter::OnExtensionUninstalled( content::BrowserContext* browser_context, const Extension* extension, extensions::UninstallReason reason) { DCHECK(profile_->IsSameProfile(Profile::FromBrowserContext(browser_context))); BroadcastItemStateChanged( browser_context, developer::EVENT_TYPE_UNINSTALLED, extension->id()); } void DeveloperPrivateEventRouter::OnErrorAdded(const ExtensionError* error) { // We don't want to handle errors thrown by extensions subscribed to these // events (currently only the Apps Developer Tool), because doing so risks // entering a loop. if (extension_ids_.find(error->extension_id()) != extension_ids_.end()) return; BroadcastItemStateChanged( profile_, developer::EVENT_TYPE_ERROR_ADDED, error->extension_id()); } void DeveloperPrivateAPI::SetLastUnpackedDirectory(const base::FilePath& path) { last_unpacked_directory_ = path; } void DeveloperPrivateAPI::RegisterNotifications() { EventRouter::Get(profile_)->RegisterObserver( this, developer_private::OnItemStateChanged::kEventName); } DeveloperPrivateAPI::~DeveloperPrivateAPI() {} void DeveloperPrivateAPI::Shutdown() {} void DeveloperPrivateAPI::OnListenerAdded( const EventListenerInfo& details) { if (!developer_private_event_router_) { developer_private_event_router_.reset( new DeveloperPrivateEventRouter(profile_)); } developer_private_event_router_->AddExtensionId(details.extension_id); } void DeveloperPrivateAPI::OnListenerRemoved( const EventListenerInfo& details) { if (!EventRouter::Get(profile_)->HasEventListener( developer_private::OnItemStateChanged::kEventName)) { developer_private_event_router_.reset(NULL); } else { developer_private_event_router_->RemoveExtensionId(details.extension_id); } } namespace api { DeveloperPrivateAPIFunction::~DeveloperPrivateAPIFunction() { } const Extension* DeveloperPrivateAPIFunction::GetExtensionById( const std::string& id) { return ExtensionRegistry::Get(browser_context())->GetExtensionById( id, ExtensionRegistry::EVERYTHING); } bool DeveloperPrivateAutoUpdateFunction::RunSync() { ExtensionUpdater* updater = GetExtensionUpdater(GetProfile()); if (updater) updater->CheckNow(ExtensionUpdater::CheckParams()); SetResult(new base::FundamentalValue(true)); return true; } DeveloperPrivateAutoUpdateFunction::~DeveloperPrivateAutoUpdateFunction() {} DeveloperPrivateGetExtensionsInfoFunction:: ~DeveloperPrivateGetExtensionsInfoFunction() { } ExtensionFunction::ResponseAction DeveloperPrivateGetExtensionsInfoFunction::Run() { scoped_ptr<developer::GetExtensionsInfo::Params> params( developer::GetExtensionsInfo::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); bool include_disabled = true; bool include_terminated = true; if (params->options) { if (params->options->include_disabled) include_disabled = *params->options->include_disabled; if (params->options->include_terminated) include_terminated = *params->options->include_terminated; } std::vector<linked_ptr<developer::ExtensionInfo>> list = ExtensionInfoGenerator(browser_context()). CreateExtensionsInfo(include_disabled, include_terminated); return RespondNow(ArgumentList( developer::GetExtensionsInfo::Results::Create(list))); } DeveloperPrivateGetExtensionInfoFunction:: ~DeveloperPrivateGetExtensionInfoFunction() { } ExtensionFunction::ResponseAction DeveloperPrivateGetExtensionInfoFunction::Run() { scoped_ptr<developer::GetExtensionInfo::Params> params( developer::GetExtensionInfo::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); developer::ExtensionState state = developer::EXTENSION_STATE_ENABLED; const Extension* extension = registry->enabled_extensions().GetByID(params->id); if (!extension && (extension = registry->disabled_extensions().GetByID(params->id)) != nullptr) { state = developer::EXTENSION_STATE_DISABLED; } else if (!extension && (extension = registry->terminated_extensions().GetByID(params->id)) != nullptr) { state = developer::EXTENSION_STATE_TERMINATED; } else { return RespondNow(Error(kNoSuchExtensionError)); } return RespondNow(OneArgument(ExtensionInfoGenerator(browser_context()). CreateExtensionInfo(*extension, state)->ToValue().release())); } DeveloperPrivateGetItemsInfoFunction::DeveloperPrivateGetItemsInfoFunction() {} DeveloperPrivateGetItemsInfoFunction::~DeveloperPrivateGetItemsInfoFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateGetItemsInfoFunction::Run() { scoped_ptr<developer::GetItemsInfo::Params> params( developer::GetItemsInfo::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); ExtensionSet items; ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context()); items.InsertAll(registry->enabled_extensions()); if (params->include_disabled) items.InsertAll(registry->disabled_extensions()); if (params->include_terminated) items.InsertAll(registry->terminated_extensions()); std::map<std::string, ExtensionResource> resource_map; for (const scoped_refptr<const Extension>& item : items) { // Don't show component extensions and invisible apps. if (ui_util::ShouldDisplayInExtensionSettings(item.get(), browser_context())) { resource_map[item->id()] = IconsInfo::GetIconResource(item.get(), extension_misc::EXTENSION_ICON_MEDIUM, ExtensionIconSet::MATCH_BIGGER); } } std::vector<linked_ptr<developer::ExtensionInfo>> list = ExtensionInfoGenerator(browser_context()). CreateExtensionsInfo(params->include_disabled, params->include_terminated); for (const linked_ptr<developer::ExtensionInfo>& info : list) item_list_.push_back(developer_private_mangle::MangleExtensionInfo(*info)); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&DeveloperPrivateGetItemsInfoFunction::GetIconsOnFileThread, this, resource_map)); return RespondLater(); } void DeveloperPrivateGetItemsInfoFunction::GetIconsOnFileThread( const std::map<std::string, ExtensionResource> resource_map) { for (const linked_ptr<developer::ItemInfo>& item : item_list_) { auto resource = resource_map.find(item->id); if (resource != resource_map.end()) { item->icon_url = ToDataURL(resource->second.GetFilePath(), item->type).spec(); } } content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&DeveloperPrivateGetItemsInfoFunction::Finish, this)); } void DeveloperPrivateGetItemsInfoFunction::Finish() { Respond(ArgumentList(developer::GetItemsInfo::Results::Create(item_list_))); } ExtensionFunction::ResponseAction DeveloperPrivateAllowFileAccessFunction::Run() { scoped_ptr<AllowFileAccess::Params> params( AllowFileAccess::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = GetExtensionById(params->extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); if (!user_gesture()) return RespondNow(Error(kRequiresUserGestureError)); if (util::IsExtensionSupervised( extension, Profile::FromBrowserContext(browser_context()))) { return RespondNow(Error(kSupervisedUserError)); } ManagementPolicy* management_policy = ExtensionSystem::Get(browser_context())->management_policy(); if (!management_policy->UserMayModifySettings(extension, nullptr)) { LOG(ERROR) << "Attempt to change allow file access of an extension that " << "non-usermanagable was made. Extension id : " << extension->id(); return RespondNow(Error(kCannotModifyPolicyExtensionError)); } util::SetAllowFileAccess(extension->id(), browser_context(), params->allow); return RespondNow(NoArguments()); } DeveloperPrivateAllowFileAccessFunction:: ~DeveloperPrivateAllowFileAccessFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateAllowIncognitoFunction::Run() { scoped_ptr<AllowIncognito::Params> params( AllowIncognito::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = GetExtensionById(params->extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); if (!user_gesture()) return RespondNow(Error(kRequiresUserGestureError)); // Should this take into account policy settings? util::SetIsIncognitoEnabled( extension->id(), browser_context(), params->allow); return RespondNow(NoArguments()); } DeveloperPrivateAllowIncognitoFunction:: ~DeveloperPrivateAllowIncognitoFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateReloadFunction::Run() { scoped_ptr<Reload::Params> params(Reload::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = GetExtensionById(params->extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); bool fail_quietly = params->options && params->options->fail_quietly && *params->options->fail_quietly; ExtensionService* service = GetExtensionService(browser_context()); if (fail_quietly) service->ReloadExtensionWithQuietFailure(params->extension_id); else service->ReloadExtension(params->extension_id); // TODO(devlin): We shouldn't return until the extension has finished trying // to reload (and then we could also return the error). return RespondNow(NoArguments()); } bool DeveloperPrivateShowPermissionsDialogFunction::RunSync() { EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &extension_id_)); CHECK(!extension_id_.empty()); AppWindowRegistry* registry = AppWindowRegistry::Get(GetProfile()); DCHECK(registry); AppWindow* app_window = registry->GetAppWindowForRenderViewHost(render_view_host()); prompt_.reset(new ExtensionInstallPrompt(app_window->web_contents())); const Extension* extension = ExtensionRegistry::Get(GetProfile()) ->GetExtensionById(extension_id_, ExtensionRegistry::EVERYTHING); if (!extension) return false; // Released by InstallUIAbort or InstallUIProceed. AddRef(); std::vector<base::FilePath> retained_file_paths; if (extension->permissions_data()->HasAPIPermission( APIPermission::kFileSystem)) { std::vector<apps::SavedFileEntry> retained_file_entries = apps::SavedFilesService::Get(GetProfile()) ->GetAllFileEntries(extension_id_); for (size_t i = 0; i < retained_file_entries.size(); i++) { retained_file_paths.push_back(retained_file_entries[i].path); } } std::vector<base::string16> retained_device_messages; if (extension->permissions_data()->HasAPIPermission(APIPermission::kUsb)) { retained_device_messages = extensions::DevicePermissionsManager::Get(GetProfile()) ->GetPermissionMessageStrings(extension_id_); } prompt_->ReviewPermissions( this, extension, retained_file_paths, retained_device_messages); return true; } DeveloperPrivateReloadFunction::~DeveloperPrivateReloadFunction() {} // This is called when the user clicks "Revoke File Access." void DeveloperPrivateShowPermissionsDialogFunction::InstallUIProceed() { Profile* profile = GetProfile(); extensions::DevicePermissionsManager::Get(profile)->Clear(extension_id_); const Extension* extension = ExtensionRegistry::Get( profile)->GetExtensionById(extension_id_, ExtensionRegistry::EVERYTHING); apps::SavedFilesService::Get(profile)->ClearQueue(extension); apps::AppLoadService::Get(profile) ->RestartApplicationIfRunning(extension_id_); SendResponse(true); Release(); } void DeveloperPrivateShowPermissionsDialogFunction::InstallUIAbort( bool user_initiated) { SendResponse(true); Release(); } DeveloperPrivateShowPermissionsDialogFunction:: DeveloperPrivateShowPermissionsDialogFunction() {} DeveloperPrivateShowPermissionsDialogFunction:: ~DeveloperPrivateShowPermissionsDialogFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateInspectFunction::Run() { scoped_ptr<developer::Inspect::Params> params( developer::Inspect::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const developer::InspectOptions& options = params->options; int render_process_id = 0; if (options.render_process_id.as_string && !base::StringToInt(*options.render_process_id.as_string, &render_process_id)) { return RespondNow(Error(kNoSuchRendererError)); } else if (options.render_process_id.as_integer) { render_process_id = *options.render_process_id.as_integer; } int render_view_id = 0; if (options.render_view_id.as_string && !base::StringToInt(*options.render_view_id.as_string, &render_view_id)) { return RespondNow(Error(kNoSuchRendererError)); } else if (options.render_view_id.as_integer) { render_view_id = *options.render_view_id.as_integer; } if (render_process_id == -1) { // This is a lazy background page. const Extension* extension = ExtensionRegistry::Get( browser_context())->enabled_extensions().GetByID(options.extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); Profile* profile = Profile::FromBrowserContext(browser_context()); if (options.incognito) profile = profile->GetOffTheRecordProfile(); // Wakes up the background page and opens the inspect window. devtools_util::InspectBackgroundPage(extension, profile); return RespondNow(NoArguments()); } content::RenderViewHost* host = content::RenderViewHost::FromID( render_process_id, render_view_id); if (!host || !content::WebContents::FromRenderViewHost(host)) return RespondNow(Error(kNoSuchRendererError)); DevToolsWindow::OpenDevToolsWindow( content::WebContents::FromRenderViewHost(host)); return RespondNow(NoArguments()); } DeveloperPrivateInspectFunction::~DeveloperPrivateInspectFunction() {} DeveloperPrivateLoadUnpackedFunction::DeveloperPrivateLoadUnpackedFunction() : fail_quietly_(false) { } ExtensionFunction::ResponseAction DeveloperPrivateLoadUnpackedFunction::Run() { scoped_ptr<developer_private::LoadUnpacked::Params> params( developer_private::LoadUnpacked::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); if (!ShowPicker( ui::SelectFileDialog::SELECT_FOLDER, l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY), ui::SelectFileDialog::FileTypeInfo(), 0 /* file_type_index */)) { return RespondNow(Error(kCouldNotShowSelectFileDialogError)); } fail_quietly_ = params->options && params->options->fail_quietly && *params->options->fail_quietly; AddRef(); // Balanced in FileSelected / FileSelectionCanceled. return RespondLater(); } void DeveloperPrivateLoadUnpackedFunction::FileSelected( const base::FilePath& path) { scoped_refptr<UnpackedInstaller> installer( UnpackedInstaller::Create(GetExtensionService(browser_context()))); installer->set_be_noisy_on_failure(!fail_quietly_); installer->set_completion_callback( base::Bind(&DeveloperPrivateLoadUnpackedFunction::OnLoadComplete, this)); installer->Load(path); DeveloperPrivateAPI::Get(browser_context())->SetLastUnpackedDirectory(path); Release(); // Balanced in Run(). } void DeveloperPrivateLoadUnpackedFunction::FileSelectionCanceled() { // This isn't really an error, but we should keep it like this for // backward compatability. Respond(Error(kFileSelectionCanceled)); Release(); // Balanced in Run(). } void DeveloperPrivateLoadUnpackedFunction::OnLoadComplete( const Extension* extension, const base::FilePath& file_path, const std::string& error) { Respond(extension ? NoArguments() : Error(error)); } bool DeveloperPrivateChooseEntryFunction::ShowPicker( ui::SelectFileDialog::Type picker_type, const base::string16& select_title, const ui::SelectFileDialog::FileTypeInfo& info, int file_type_index) { content::WebContents* web_contents = GetSenderWebContents(); if (!web_contents) return false; // The entry picker will hold a reference to this function instance, // and subsequent sending of the function response) until the user has // selected a file or cancelled the picker. At that point, the picker will // delete itself. new EntryPicker(this, web_contents, picker_type, DeveloperPrivateAPI::Get(browser_context())-> GetLastUnpackedDirectory(), select_title, info, file_type_index); return true; } DeveloperPrivateChooseEntryFunction::~DeveloperPrivateChooseEntryFunction() {} void DeveloperPrivatePackDirectoryFunction::OnPackSuccess( const base::FilePath& crx_file, const base::FilePath& pem_file) { developer::PackDirectoryResponse response; response.message = base::UTF16ToUTF8( PackExtensionJob::StandardSuccessMessage(crx_file, pem_file)); response.status = developer::PACK_STATUS_SUCCESS; Respond(OneArgument(response.ToValue().release())); Release(); // Balanced in Run(). } void DeveloperPrivatePackDirectoryFunction::OnPackFailure( const std::string& error, ExtensionCreator::ErrorType error_type) { developer::PackDirectoryResponse response; response.message = error; if (error_type == ExtensionCreator::kCRXExists) { response.item_path = item_path_str_; response.pem_path = key_path_str_; response.override_flags = ExtensionCreator::kOverwriteCRX; response.status = developer::PACK_STATUS_WARNING; } else { response.status = developer::PACK_STATUS_ERROR; } Respond(OneArgument(response.ToValue().release())); Release(); // Balanced in Run(). } ExtensionFunction::ResponseAction DeveloperPrivatePackDirectoryFunction::Run() { scoped_ptr<PackDirectory::Params> params( PackDirectory::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); int flags = params->flags ? *params->flags : 0; item_path_str_ = params->path; if (params->private_key_path) key_path_str_ = *params->private_key_path; base::FilePath root_directory = base::FilePath::FromUTF8Unsafe(item_path_str_); base::FilePath key_file = base::FilePath::FromUTF8Unsafe(key_path_str_); developer::PackDirectoryResponse response; if (root_directory.empty()) { if (item_path_str_.empty()) response.message = l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_ROOT_REQUIRED); else response.message = l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_ROOT_INVALID); response.status = developer::PACK_STATUS_ERROR; return RespondNow(OneArgument(response.ToValue().release())); } if (!key_path_str_.empty() && key_file.empty()) { response.message = l10n_util::GetStringUTF8( IDS_EXTENSION_PACK_DIALOG_ERROR_KEY_INVALID); response.status = developer::PACK_STATUS_ERROR; return RespondNow(OneArgument(response.ToValue().release())); } AddRef(); // Balanced in OnPackSuccess / OnPackFailure. // TODO(devlin): Why is PackExtensionJob ref-counted? pack_job_ = new PackExtensionJob(this, root_directory, key_file, flags); pack_job_->Start(); return RespondLater(); } DeveloperPrivatePackDirectoryFunction::DeveloperPrivatePackDirectoryFunction() { } DeveloperPrivatePackDirectoryFunction:: ~DeveloperPrivatePackDirectoryFunction() {} DeveloperPrivateLoadUnpackedFunction::~DeveloperPrivateLoadUnpackedFunction() {} bool DeveloperPrivateLoadDirectoryFunction::RunAsync() { // TODO(grv) : add unittests. std::string directory_url_str; std::string filesystem_name; std::string filesystem_path; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &filesystem_name)); EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filesystem_path)); EXTENSION_FUNCTION_VALIDATE(args_->GetString(2, &directory_url_str)); context_ = content::BrowserContext::GetStoragePartition( GetProfile(), render_view_host()->GetSiteInstance()) ->GetFileSystemContext(); // Directory url is non empty only for syncfilesystem. if (!directory_url_str.empty()) { storage::FileSystemURL directory_url = context_->CrackURL(GURL(directory_url_str)); if (!directory_url.is_valid() || directory_url.type() != storage::kFileSystemTypeSyncable) { SetError("DirectoryEntry of unsupported filesystem."); return false; } return LoadByFileSystemAPI(directory_url); } else { // Check if the DirecotryEntry is the instance of chrome filesystem. if (!app_file_handler_util::ValidateFileEntryAndGetPath(filesystem_name, filesystem_path, render_view_host_, &project_base_path_, &error_)) { SetError("DirectoryEntry of unsupported filesystem."); return false; } // Try to load using the FileSystem API backend, in case the filesystem // points to a non-native local directory. std::string filesystem_id; bool cracked = storage::CrackIsolatedFileSystemName(filesystem_name, &filesystem_id); CHECK(cracked); base::FilePath virtual_path = storage::IsolatedContext::GetInstance() ->CreateVirtualRootPath(filesystem_id) .Append(base::FilePath::FromUTF8Unsafe(filesystem_path)); storage::FileSystemURL directory_url = context_->CreateCrackedFileSystemURL( extensions::Extension::GetBaseURLFromExtensionId(extension_id()), storage::kFileSystemTypeIsolated, virtual_path); if (directory_url.is_valid() && directory_url.type() != storage::kFileSystemTypeNativeLocal && directory_url.type() != storage::kFileSystemTypeRestrictedNativeLocal && directory_url.type() != storage::kFileSystemTypeDragged) { return LoadByFileSystemAPI(directory_url); } Load(); } return true; } bool DeveloperPrivateLoadDirectoryFunction::LoadByFileSystemAPI( const storage::FileSystemURL& directory_url) { std::string directory_url_str = directory_url.ToGURL().spec(); size_t pos = 0; // Parse the project directory name from the project url. The project url is // expected to have project name as the suffix. if ((pos = directory_url_str.rfind("/")) == std::string::npos) { SetError("Invalid Directory entry."); return false; } std::string project_name; project_name = directory_url_str.substr(pos + 1); project_base_url_ = directory_url_str.substr(0, pos + 1); base::FilePath project_path(GetProfile()->GetPath()); project_path = project_path.AppendASCII(kUnpackedAppsFolder); project_path = project_path.Append( base::FilePath::FromUTF8Unsafe(project_name)); project_base_path_ = project_path; content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE, base::Bind(&DeveloperPrivateLoadDirectoryFunction:: ClearExistingDirectoryContent, this, project_base_path_)); return true; } void DeveloperPrivateLoadDirectoryFunction::Load() { ExtensionService* service = GetExtensionService(GetProfile()); UnpackedInstaller::Create(service)->Load(project_base_path_); // TODO(grv) : The unpacked installer should fire an event when complete // and return the extension_id. SetResult(new base::StringValue("-1")); SendResponse(true); } void DeveloperPrivateLoadDirectoryFunction::ClearExistingDirectoryContent( const base::FilePath& project_path) { // Clear the project directory before copying new files. base::DeleteFile(project_path, true /*recursive*/); pending_copy_operations_count_ = 1; content::BrowserThread::PostTask(content::BrowserThread::IO, FROM_HERE, base::Bind(&DeveloperPrivateLoadDirectoryFunction:: ReadDirectoryByFileSystemAPI, this, project_path, project_path.BaseName())); } void DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPI( const base::FilePath& project_path, const base::FilePath& destination_path) { GURL project_url = GURL(project_base_url_ + destination_path.AsUTF8Unsafe()); storage::FileSystemURL url = context_->CrackURL(project_url); context_->operation_runner()->ReadDirectory( url, base::Bind(&DeveloperPrivateLoadDirectoryFunction:: ReadDirectoryByFileSystemAPICb, this, project_path, destination_path)); } void DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPICb( const base::FilePath& project_path, const base::FilePath& destination_path, base::File::Error status, const storage::FileSystemOperation::FileEntryList& file_list, bool has_more) { if (status != base::File::FILE_OK) { DLOG(ERROR) << "Error in copying files from sync filesystem."; return; } // We add 1 to the pending copy operations for both files and directories. We // release the directory copy operation once all the files under the directory // are added for copying. We do that to ensure that pendingCopyOperationsCount // does not become zero before all copy operations are finished. // In case the directory happens to be executing the last copy operation it // will call SendResponse to send the response to the API. The pending copy // operations of files are released by the CopyFile function. pending_copy_operations_count_ += file_list.size(); for (size_t i = 0; i < file_list.size(); ++i) { if (file_list[i].is_directory) { ReadDirectoryByFileSystemAPI(project_path.Append(file_list[i].name), destination_path.Append(file_list[i].name)); continue; } GURL project_url = GURL(project_base_url_ + destination_path.Append(file_list[i].name).AsUTF8Unsafe()); storage::FileSystemURL url = context_->CrackURL(project_url); base::FilePath target_path = project_path; target_path = target_path.Append(file_list[i].name); context_->operation_runner()->CreateSnapshotFile( url, base::Bind(&DeveloperPrivateLoadDirectoryFunction::SnapshotFileCallback, this, target_path)); } if (!has_more) { // Directory copy operation released here. pending_copy_operations_count_--; if (!pending_copy_operations_count_) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&DeveloperPrivateLoadDirectoryFunction::SendResponse, this, success_)); } } } void DeveloperPrivateLoadDirectoryFunction::SnapshotFileCallback( const base::FilePath& target_path, base::File::Error result, const base::File::Info& file_info, const base::FilePath& src_path, const scoped_refptr<storage::ShareableFileReference>& file_ref) { if (result != base::File::FILE_OK) { SetError("Error in copying files from sync filesystem."); success_ = false; return; } content::BrowserThread::PostTask(content::BrowserThread::FILE, FROM_HERE, base::Bind(&DeveloperPrivateLoadDirectoryFunction::CopyFile, this, src_path, target_path)); } void DeveloperPrivateLoadDirectoryFunction::CopyFile( const base::FilePath& src_path, const base::FilePath& target_path) { if (!base::CreateDirectory(target_path.DirName())) { SetError("Error in copying files from sync filesystem."); success_ = false; } if (success_) base::CopyFile(src_path, target_path); CHECK(pending_copy_operations_count_ > 0); pending_copy_operations_count_--; if (!pending_copy_operations_count_) { content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::Bind(&DeveloperPrivateLoadDirectoryFunction::Load, this)); } } DeveloperPrivateLoadDirectoryFunction::DeveloperPrivateLoadDirectoryFunction() : pending_copy_operations_count_(0), success_(true) {} DeveloperPrivateLoadDirectoryFunction::~DeveloperPrivateLoadDirectoryFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateChoosePathFunction::Run() { scoped_ptr<developer::ChoosePath::Params> params( developer::ChoosePath::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); ui::SelectFileDialog::Type type = ui::SelectFileDialog::SELECT_FOLDER; ui::SelectFileDialog::FileTypeInfo info; if (params->select_type == developer::SELECT_TYPE_FILE) type = ui::SelectFileDialog::SELECT_OPEN_FILE; base::string16 select_title; int file_type_index = 0; if (params->file_type == developer::FILE_TYPE_LOAD) { select_title = l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY); } else if (params->file_type == developer::FILE_TYPE_PEM) { select_title = l10n_util::GetStringUTF16( IDS_EXTENSION_PACK_DIALOG_SELECT_KEY); info.extensions.push_back(std::vector<base::FilePath::StringType>( 1, FILE_PATH_LITERAL("pem"))); info.extension_description_overrides.push_back( l10n_util::GetStringUTF16( IDS_EXTENSION_PACK_DIALOG_KEY_FILE_TYPE_DESCRIPTION)); info.include_all_files = true; file_type_index = 1; } else { NOTREACHED(); } if (!ShowPicker( type, select_title, info, file_type_index)) { return RespondNow(Error(kCouldNotShowSelectFileDialogError)); } AddRef(); // Balanced by FileSelected / FileSelectionCanceled. return RespondLater(); } void DeveloperPrivateChoosePathFunction::FileSelected( const base::FilePath& path) { Respond(OneArgument(new base::StringValue(path.LossyDisplayName()))); Release(); } void DeveloperPrivateChoosePathFunction::FileSelectionCanceled() { // This isn't really an error, but we should keep it like this for // backward compatability. Respond(Error(kFileSelectionCanceled)); Release(); } DeveloperPrivateChoosePathFunction::~DeveloperPrivateChoosePathFunction() {} bool DeveloperPrivateIsProfileManagedFunction::RunSync() { SetResult(new base::FundamentalValue(GetProfile()->IsSupervised())); return true; } DeveloperPrivateIsProfileManagedFunction:: ~DeveloperPrivateIsProfileManagedFunction() { } DeveloperPrivateRequestFileSourceFunction:: DeveloperPrivateRequestFileSourceFunction() {} DeveloperPrivateRequestFileSourceFunction:: ~DeveloperPrivateRequestFileSourceFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateRequestFileSourceFunction::Run() { params_ = developer::RequestFileSource::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(params_); const developer::RequestFileSourceProperties& properties = params_->properties; const Extension* extension = GetExtensionById(properties.extension_id); if (!extension) return RespondNow(Error(kNoSuchExtensionError)); // Under no circumstances should we ever need to reference a file outside of // the extension's directory. If it tries to, abort. base::FilePath path_suffix = base::FilePath::FromUTF8Unsafe(properties.path_suffix); if (path_suffix.empty() || path_suffix.ReferencesParent()) return RespondNow(Error(kInvalidPathError)); if (properties.path_suffix == kManifestFile && !properties.manifest_key) return RespondNow(Error(kManifestKeyIsRequiredError)); base::PostTaskAndReplyWithResult( content::BrowserThread::GetBlockingPool(), FROM_HERE, base::Bind(&ReadFileToString, extension->path().Append(path_suffix)), base::Bind(&DeveloperPrivateRequestFileSourceFunction::Finish, this)); return RespondLater(); } void DeveloperPrivateRequestFileSourceFunction::Finish( const std::string& file_contents) { const developer::RequestFileSourceProperties& properties = params_->properties; const Extension* extension = GetExtensionById(properties.extension_id); if (!extension) { Respond(Error(kNoSuchExtensionError)); return; } developer::RequestFileSourceResponse response; base::FilePath path_suffix = base::FilePath::FromUTF8Unsafe(properties.path_suffix); base::FilePath path = extension->path().Append(path_suffix); response.title = base::StringPrintf("%s: %s", extension->name().c_str(), path.BaseName().AsUTF8Unsafe().c_str()); response.message = properties.message; scoped_ptr<FileHighlighter> highlighter; if (properties.path_suffix == kManifestFile) { highlighter.reset(new ManifestHighlighter( file_contents, *properties.manifest_key, properties.manifest_specific ? *properties.manifest_specific : std::string())); } else { highlighter.reset(new SourceHighlighter( file_contents, properties.line_number ? *properties.line_number : 0)); } response.before_highlight = highlighter->GetBeforeFeature(); response.highlight = highlighter->GetFeature(); response.after_highlight = highlighter->GetAfterFeature(); Respond(OneArgument(response.ToValue().release())); } DeveloperPrivateOpenDevToolsFunction::DeveloperPrivateOpenDevToolsFunction() {} DeveloperPrivateOpenDevToolsFunction::~DeveloperPrivateOpenDevToolsFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateOpenDevToolsFunction::Run() { scoped_ptr<developer::OpenDevTools::Params> params( developer::OpenDevTools::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); const developer::OpenDevToolsProperties& properties = params->properties; content::RenderViewHost* rvh = content::RenderViewHost::FromID(properties.render_process_id, properties.render_view_id); content::WebContents* web_contents = rvh ? content::WebContents::FromRenderViewHost(rvh) : nullptr; // It's possible that the render view was closed since we last updated the // links. Handle this gracefully. if (!web_contents) return RespondNow(Error(kNoSuchRendererError)); // If we include a url, we should inspect it specifically (and not just the // render view). if (properties.url) { // Line/column numbers are reported in display-friendly 1-based numbers, // but are inspected in zero-based numbers. // Default to the first line/column. DevToolsWindow::OpenDevToolsWindow( web_contents, DevToolsToggleAction::Reveal( base::UTF8ToUTF16(*properties.url), properties.line_number ? *properties.line_number - 1 : 0, properties.column_number ? *properties.column_number - 1 : 0)); } else { DevToolsWindow::OpenDevToolsWindow(web_contents); } // Once we open the inspector, we focus on the appropriate tab... Browser* browser = chrome::FindBrowserWithWebContents(web_contents); // ... but some pages (popups and apps) don't have tabs, and some (background // pages) don't have an associated browser. For these, the inspector opens in // a new window, and our work is done. if (!browser || !browser->is_type_tabbed()) return RespondNow(NoArguments()); TabStripModel* tab_strip = browser->tab_strip_model(); tab_strip->ActivateTabAt(tab_strip->GetIndexOfWebContents(web_contents), false); // Not through direct user gesture. return RespondNow(NoArguments()); } } // namespace api } // namespace extensions
bsd-3-clause
joshbohde/scikit-learn
examples/grid_search_text_feature_extraction.py
4106
""" ========================================================== Sample pipeline for text feature extraction and evaluation ========================================================== The dataset used in this example is the 20 newsgroups dataset which will be automatically downloaded and then cached and reused for the document classification example. You can adjust the number of categories by giving there name to the dataset loader or setting them to None to get the 20 of them. Here is a sample output of a run on a quad-core machine:: Loading 20 newsgroups dataset for categories: ['alt.atheism', 'talk.religion.misc'] 1427 documents 2 categories Performing grid search... pipeline: ['vect', 'tfidf', 'clf'] parameters: {'clf__alpha': (1.0000000000000001e-05, 9.9999999999999995e-07), 'clf__n_iter': (10, 50, 80), 'clf__penalty': ('l2', 'elasticnet'), 'tfidf__use_idf': (True, False), 'vect__analyzer__max_n': (1, 2), 'vect__max_df': (0.5, 0.75, 1.0), 'vect__max_features': (None, 5000, 10000, 50000)} done in 1737.030s Best score: 0.940 Best parameters set: clf__alpha: 9.9999999999999995e-07 clf__n_iter: 50 clf__penalty: 'elasticnet' tfidf__use_idf: True vect__analyzer__max_n: 2 vect__max_df: 0.75 vect__max_features: 50000 """ print __doc__ # Author: Olivier Grisel <olivier.grisel@ensta.org> # Peter Prettenhofer <peter.prettenhofer@gmail.com> # Mathieu Blondel <mathieu@mblondel.org> # License: Simplified BSD from pprint import pprint from time import time import os import logging from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model.sparse import SGDClassifier from sklearn.grid_search import GridSearchCV from sklearn.pipeline import Pipeline # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') ################################################################################ # Load some categories from the training set categories = [ 'alt.atheism', 'talk.religion.misc', ] # Uncomment the following to do the analysis on all the categories #categories = None print "Loading 20 newsgroups dataset for categories:" print categories data = fetch_20newsgroups(subset='train', categories=categories) print "%d documents" % len(data.filenames) print "%d categories" % len(data.target_names) print ################################################################################ # define a pipeline combining a text feature extractor with a simple # classifier pipeline = Pipeline([ ('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', SGDClassifier()), ]) parameters = { # uncommenting more parameters will give better exploring power but will # increase processing time in a combinatorial way 'vect__max_df': (0.5, 0.75, 1.0), # 'vect__max_features': (None, 5000, 10000, 50000), 'vect__analyzer__max_n': (1, 2), # words or bigrams # 'tfidf__use_idf': (True, False), # 'tfidf__norm': ('l1', 'l2'), 'clf__alpha': (0.00001, 0.000001), 'clf__penalty': ('l2', 'elasticnet'), # 'clf__n_iter': (10, 50, 80), } # find the best parameters for both the feature extraction and the # classifier grid_search = GridSearchCV(pipeline, parameters, n_jobs=1) # cross-validation doesn't work if the length of the data is not known, # hence use lists instead of iterators text_docs = [file(f).read() for f in data.filenames] print "Performing grid search..." print "pipeline:", [name for name, _ in pipeline.steps] print "parameters:" pprint(parameters) t0 = time() grid_search.fit(text_docs, data.target) print "done in %0.3fs" % (time() - t0) print print "Best score: %0.3f" % grid_search.best_score print "Best parameters set:" best_parameters = grid_search.best_estimator._get_params() for param_name in sorted(parameters.keys()): print "\t%s: %r" % (param_name, best_parameters[param_name])
bsd-3-clause
youtube/cobalt
starboard/shared/starboard/microphone/microphone_create.cc
1163
// Copyright 2017 The Cobalt Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "starboard/microphone.h" #include "starboard/shared/starboard/microphone/microphone_internal.h" #if SB_API_VERSION < 12 && !SB_HAS(MICROPHONE) #error "SB_HAS_MICROPHONE must be set to build this file before Starboard API \ version 12." #endif SbMicrophone SbMicrophoneCreate(SbMicrophoneId id, int sample_rate_in_hz, int buffer_size) { return SbMicrophonePrivate::CreateMicrophone(id, sample_rate_in_hz, buffer_size); }
bsd-3-clause
dariomangoni/chrono
src/demos/vehicle/demo_M113_Band/demo_VEH_M113_Band.cpp
19076
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Michael Taylor // ============================================================================= // // Demonstration program for M113 vehicle with continuous band tracks. // // ============================================================================= #include "chrono/ChConfig.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/terrain/RigidTerrain.h" #include "chrono_vehicle/tracked_vehicle/track_shoe/ChTrackShoeBand.h" #include "chrono_models/vehicle/m113/M113_SimplePowertrain.h" #include "chrono_models/vehicle/m113/M113_Vehicle.h" #ifdef CHRONO_IRRLICHT #include "chrono_vehicle/driver/ChIrrGuiDriver.h" #include "chrono_vehicle/tracked_vehicle/utils/ChTrackedVehicleIrrApp.h" #define USE_IRRLICHT #endif #ifdef CHRONO_MUMPS #include "chrono_mumps/ChSolverMumps.h" #endif #ifdef CHRONO_PARDISO_MKL #include "chrono_pardisomkl/ChSolverPardisoMKL.h" #endif #include "chrono_thirdparty/filesystem/path.h" using namespace chrono; using namespace chrono::vehicle; using namespace chrono::vehicle::m113; using std::cout; using std::endl; // ============================================================================= // USER SETTINGS // ============================================================================= // Initial vehicle position ChVector<> initLoc(0, 0, 1.1); // Initial vehicle orientation ChQuaternion<> initRot(1, 0, 0, 0); // Rigid terrain dimensions double terrainLength = 100.0; // size in X direction double terrainWidth = 100.0; // size in Y direction // Simulation length double t_end = 1.0; // Simulation step size double step_size = 1e-4; // Linear solver (MUMPS or PARDISO_MKL) ChSolver::Type solver_type = ChSolver::Type::MUMPS; // Time interval between two render frames double render_step_size = 1.0 / 50; // FPS = 50 // Output directories const std::string out_dir = GetChronoOutputPath() + "M113_BAND"; const std::string pov_dir = out_dir + "/POVRAY"; const std::string img_dir = out_dir + "/IMG"; // Verbose level bool verbose_solver = false; bool verbose_integrator = false; // Output bool output = true; bool dbg_output = false; bool povray_output = false; bool img_output = false; // ============================================================================= // Dummy driver class (always returns 1 for throttle, 0 for all other inputs) class MyDriver { public: MyDriver() {} double GetThrottle() const { return 1; } double GetSteering() const { return 0; } double GetBraking() const { return 0; } void Synchronize(double time) {} void Advance(double step) {} }; // ============================================================================= // Forward declarations void AddFixedObstacles(ChSystem* system); // ============================================================================= int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // -------------------------- // Construct the M113 vehicle // -------------------------- CollisionType chassis_collision_type = CollisionType::PRIMITIVES; M113_Vehicle vehicle(false, TrackShoeType::BAND_BUSHING, BrakeType::SIMPLE, ChContactMethod::SMC, chassis_collision_type); // Disable gravity in this simulation ////vehicle.GetSystem()->Set_G_acc(ChVector<>(0, 0, 0)); // Control steering type (enable crossdrive capability) ////vehicle.GetDriveline()->SetGyrationMode(true); // ------------------------------------------------ // Initialize the vehicle at the specified position // ------------------------------------------------ vehicle.Initialize(ChCoordsys<>(initLoc, initRot)); // Set visualization type for vehicle components. vehicle.SetChassisVisualizationType(VisualizationType::PRIMITIVES); vehicle.SetSprocketVisualizationType(VisualizationType::PRIMITIVES); vehicle.SetIdlerVisualizationType(VisualizationType::PRIMITIVES); vehicle.SetRoadWheelAssemblyVisualizationType(VisualizationType::PRIMITIVES); vehicle.SetRoadWheelVisualizationType(VisualizationType::PRIMITIVES); vehicle.SetTrackShoeVisualizationType(VisualizationType::PRIMITIVES); // -------------------------------------------------- // Control internal collisions and contact monitoring // -------------------------------------------------- // Enable contact on all tracked vehicle parts, except the left sprocket ////vehicle.SetCollide(TrackedCollisionFlag::ALL & (~TrackedCollisionFlag::SPROCKET_LEFT)); // Disable contact for all tracked vehicle parts ////vehicle.SetCollide(TrackedCollisionFlag::NONE); // Disable all contacts for vehicle chassis (if chassis collision was defined) ////vehicle.SetChassisCollide(false); // Disable only contact between chassis and track shoes (if chassis collision was defined) ////vehicle.SetChassisVehicleCollide(false); // Monitor internal contacts for the chassis, left sprocket, left idler, and first shoe on the left track. ////vehicle.MonitorContacts(TrackedCollisionFlag::CHASSIS | TrackedCollisionFlag::SPROCKET_LEFT | //// TrackedCollisionFlag::SHOES_LEFT | TrackedCollisionFlag::IDLER_LEFT); // Monitor only contacts involving the chassis. vehicle.MonitorContacts(TrackedCollisionFlag::CHASSIS); // Collect contact information. // If enabled, number of contacts and local contact point locations are collected for all // monitored parts. Data can be written to a file by invoking ChTrackedVehicle::WriteContacts(). ////vehicle.SetContactCollection(true); // ------------------ // Create the terrain // ------------------ RigidTerrain terrain(vehicle.GetSystem()); auto patch_mat = chrono_types::make_shared<ChMaterialSurfaceSMC>(); patch_mat->SetFriction(0.9f); patch_mat->SetRestitution(0.01f); patch_mat->SetYoungModulus(2e7f); patch_mat->SetPoissonRatio(0.3f); auto patch = terrain.AddPatch(patch_mat, ChVector<>(0, 0, 0), ChVector<>(0, 0, 1), terrainLength, terrainWidth); patch->SetColor(ChColor(0.5f, 0.8f, 0.5f)); patch->SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 200, 200); terrain.Initialize(); // ------------------- // Add fixed obstacles // ------------------- AddFixedObstacles(vehicle.GetSystem()); // ---------------------------- // Create the powertrain system // ---------------------------- auto powertrain = chrono_types::make_shared<M113_SimplePowertrain>("powertrain"); vehicle.InitializePowertrain(powertrain); #ifdef USE_IRRLICHT // --------------------------------------- // Create the vehicle Irrlicht application // --------------------------------------- ChTrackedVehicleIrrApp app(&vehicle, L"M113 Band-track Vehicle Demo"); app.SetSkyBox(); irrlicht::ChIrrWizard::add_typical_Logo(app.GetDevice()); app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130); app.SetChaseCamera(ChVector<>(0, 0, 0), 6.0, 0.5); ////app.SetChaseCameraPosition(vehicle.GetVehiclePos() + ChVector<>(0, 2, 0)); app.SetChaseCameraMultipliers(1e-4, 10); app.SetTimestep(step_size); app.AssetBindAll(); app.AssetUpdateAll(); // ------------------------ // Create the driver system // ------------------------ ChIrrGuiDriver driver(app); // Set the time response for keyboard inputs. double steering_time = 0.5; // time to go from 0 to +1 (or from 0 to -1) double throttle_time = 1.0; // time to go from 0 to +1 double braking_time = 0.3; // time to go from 0 to +1 driver.SetSteeringDelta(render_step_size / steering_time); driver.SetThrottleDelta(render_step_size / throttle_time); driver.SetBrakingDelta(render_step_size / braking_time); driver.Initialize(); #else // Create a default driver (always returns 1 for throttle, 0 for all other inputs) MyDriver driver; #endif // ----------------- // Initialize output // ----------------- if (!filesystem::create_directory(filesystem::path(out_dir))) { cout << "Error creating directory " << out_dir << endl; return 1; } if (povray_output) { if (!filesystem::create_directory(filesystem::path(pov_dir))) { cout << "Error creating directory " << pov_dir << endl; return 1; } terrain.ExportMeshPovray(out_dir); } if (img_output) { if (!filesystem::create_directory(filesystem::path(img_dir))) { cout << "Error creating directory " << img_dir << endl; return 1; } } //Setup chassis position output with column headers utils::CSV_writer csv("\t"); csv.stream().setf(std::ios::scientific | std::ios::showpos); csv.stream().precision(6); csv << "Time (s)" << "Chassis X Pos (m)" << "Chassis Y Pos (m)" << "Chassis Z Pos (m)" << endl; // Set up vehicle output ////vehicle.SetChassisOutput(true); ////vehicle.SetTrackAssemblyOutput(VehicleSide::LEFT, true); vehicle.SetOutput(ChVehicleOutput::ASCII, out_dir, "vehicle_output", 0.1); // Generate JSON information with available output channels ////vehicle.ExportComponentList(out_dir + "/component_list.json"); // Export visualization mesh for shoe tread body auto shoe0 = std::static_pointer_cast<ChTrackShoeBand>(vehicle.GetTrackShoe(LEFT, 0)); shoe0->WriteTreadVisualizationMesh(out_dir); shoe0->ExportTreadVisualizationMeshPovray(out_dir); // ------------------------------ // Solver and integrator settings // ------------------------------ #ifndef CHRONO_PARDISO_MKL if (solver_type == ChSolver::Type::PARDISO_MKL) solver_type = ChSolver::Type::MUMPS; #endif #ifndef CHRONO_MUMPS if (solver_type == ChSolver::Type::MUMPS) solver_type = ChSolver::Type::PARDISO_MKL; #endif switch (solver_type) { #ifdef CHRONO_MUMPS case ChSolver::Type::MUMPS : { auto mumps_solver = chrono_types::make_shared<ChSolverMumps>(); mumps_solver->LockSparsityPattern(true); mumps_solver->SetVerbose(verbose_solver); vehicle.GetSystem()->SetSolver(mumps_solver); break; } #endif #ifdef CHRONO_PARDISO_MKL case ChSolver::Type::PARDISO_MKL : { auto mkl_solver = chrono_types::make_shared<ChSolverPardisoMKL>(); mkl_solver->LockSparsityPattern(true); mkl_solver->SetVerbose(verbose_solver); vehicle.GetSystem()->SetSolver(mkl_solver); break; } #endif } vehicle.GetSystem()->SetTimestepperType(ChTimestepper::Type::HHT); auto integrator = std::static_pointer_cast<ChTimestepperHHT>(vehicle.GetSystem()->GetTimestepper()); integrator->SetAlpha(-0.2); integrator->SetMaxiters(50); integrator->SetAbsTolerances(1e-2, 1e2); integrator->SetMode(ChTimestepperHHT::ACCELERATION); integrator->SetStepControl(false); integrator->SetModifiedNewton(true); integrator->SetScaling(true); integrator->SetVerbose(verbose_integrator); // --------------- // Simulation loop // --------------- // Inter-module communication data BodyStates shoe_states_left(vehicle.GetNumTrackShoes(LEFT)); BodyStates shoe_states_right(vehicle.GetNumTrackShoes(RIGHT)); TerrainForces shoe_forces_left(vehicle.GetNumTrackShoes(LEFT)); TerrainForces shoe_forces_right(vehicle.GetNumTrackShoes(RIGHT)); // Number of steps to run for the simulation int sim_steps = (int)std::ceil(t_end / step_size); // Number of simulation steps between two 3D view render frames int render_steps = (int)std::ceil(render_step_size / step_size); // Total execution time (for integration) double total_timing = 0; // Initialize simulation frame counter int step_number = 0; int render_frame = 0; while (step_number < sim_steps) { const ChVector<>& c_pos = vehicle.GetVehiclePos(); // File output if (output) { csv << vehicle.GetSystem()->GetChTime() << c_pos.x() << c_pos.y() << c_pos.z() << endl; } // Debugging (console) output if (dbg_output) { cout << "Time: " << vehicle.GetSystem()->GetChTime() << endl; const ChFrameMoving<>& c_ref = vehicle.GetChassisBody()->GetFrame_REF_to_abs(); cout << " chassis: " << c_pos.x() << " " << c_pos.y() << " " << c_pos.z() << endl; { const ChVector<>& i_pos_abs = vehicle.GetTrackAssembly(LEFT)->GetIdler()->GetWheelBody()->GetPos(); const ChVector<>& s_pos_abs = vehicle.GetTrackAssembly(LEFT)->GetSprocket()->GetGearBody()->GetPos(); ChVector<> i_pos_rel = c_ref.TransformPointParentToLocal(i_pos_abs); ChVector<> s_pos_rel = c_ref.TransformPointParentToLocal(s_pos_abs); cout << " L idler: " << i_pos_rel.x() << " " << i_pos_rel.y() << " " << i_pos_rel.z() << endl; cout << " L sprocket: " << s_pos_rel.x() << " " << s_pos_rel.y() << " " << s_pos_rel.z() << endl; } { const ChVector<>& i_pos_abs = vehicle.GetTrackAssembly(RIGHT)->GetIdler()->GetWheelBody()->GetPos(); const ChVector<>& s_pos_abs = vehicle.GetTrackAssembly(RIGHT)->GetSprocket()->GetGearBody()->GetPos(); ChVector<> i_pos_rel = c_ref.TransformPointParentToLocal(i_pos_abs); ChVector<> s_pos_rel = c_ref.TransformPointParentToLocal(s_pos_abs); cout << " R idler: " << i_pos_rel.x() << " " << i_pos_rel.y() << " " << i_pos_rel.z() << endl; cout << " R sprocket: " << s_pos_rel.x() << " " << s_pos_rel.y() << " " << s_pos_rel.z() << endl; } cout << " L suspensions (arm angles):" << endl; for (size_t i = 0; i < vehicle.GetTrackAssembly(LEFT)->GetNumRoadWheelAssemblies(); i++) { cout << " " << vehicle.GetTrackAssembly(VehicleSide::LEFT)->GetRoadWheelAssembly(i)->GetCarrierAngle(); } cout << endl; cout << " R suspensions (arm angles):" << endl; for (size_t i = 0; i < vehicle.GetTrackAssembly(RIGHT)->GetNumRoadWheelAssemblies(); i++) { cout << " " << vehicle.GetTrackAssembly(VehicleSide::RIGHT)->GetRoadWheelAssembly(i)->GetCarrierAngle(); } cout << endl; } #ifdef USE_IRRLICHT if (!app.GetDevice()->run()) break; // Render scene app.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192)); app.DrawAll(); #endif if (step_number % render_steps == 0) { if (povray_output) { char filename[100]; sprintf(filename, "%s/data_%03d.dat", pov_dir.c_str(), render_frame + 1); utils::WriteShapesPovray(vehicle.GetSystem(), filename); } #ifdef USE_IRRLICHT if (img_output && step_number > 200) { char filename[100]; sprintf(filename, "%s/img_%03d.jpg", img_dir.c_str(), render_frame + 1); app.WriteImageToFile(filename); } #endif render_frame++; } // Collect data from modules ChDriver::Inputs driver_inputs = driver.GetInputs(); vehicle.GetTrackShoeStates(LEFT, shoe_states_left); vehicle.GetTrackShoeStates(RIGHT, shoe_states_right); // Update modules (process data from other modules) double time = vehicle.GetChTime(); driver.Synchronize(time); terrain.Synchronize(time); vehicle.Synchronize(time, driver_inputs, shoe_forces_left, shoe_forces_right); #ifdef USE_IRRLICHT app.Synchronize("", driver_inputs); #endif // Advance simulation for one timestep for all modules driver.Advance(step_size); terrain.Advance(step_size); vehicle.Advance(step_size); #ifdef USE_IRRLICHT app.Advance(step_size); #endif // Report if the chassis experienced a collision if (vehicle.IsPartInContact(TrackedCollisionFlag::CHASSIS)) { cout << time << " chassis contact" << endl; } // Increment frame number step_number++; double step_timing = vehicle.GetSystem()->GetTimerStep(); total_timing += step_timing; cout << "Step: " << step_number; cout << " Time: " << time; cout << " Number of Iterations: " << integrator->GetNumIterations(); cout << " Step Time: " << step_timing; cout << " Total Time: " << total_timing; cout << endl; #ifdef USE_IRRLICHT app.EndScene(); #endif } if (output) { csv.write_to_file(out_dir + "/chassis_position.txt"); } vehicle.WriteContacts(out_dir + "/contacts.txt"); return 0; } // ============================================================================= void AddFixedObstacles(ChSystem* system) { double radius = 2.2; double length = 6; auto obstacle = std::shared_ptr<ChBody>(system->NewBody()); obstacle->SetPos(ChVector<>(10, 0, -1.8)); obstacle->SetBodyFixed(true); obstacle->SetCollide(true); // Visualization auto shape = chrono_types::make_shared<ChCylinderShape>(); shape->GetCylinderGeometry().p1 = ChVector<>(0, -length * 0.5, 0); shape->GetCylinderGeometry().p2 = ChVector<>(0, length * 0.5, 0); shape->GetCylinderGeometry().rad = radius; obstacle->AddAsset(shape); auto color = chrono_types::make_shared<ChColorAsset>(); color->SetColor(ChColor(1, 1, 1)); obstacle->AddAsset(color); #ifdef USE_IRRLICHT auto texture = chrono_types::make_shared<ChTexture>(); texture->SetTextureFilename(vehicle::GetDataFile("terrain/textures/tile4.jpg")); texture->SetTextureScale(10, 10); obstacle->AddAsset(texture); #endif // Contact auto obst_mat = chrono_types::make_shared<ChMaterialSurfaceSMC>(); obst_mat->SetFriction(0.9f); obst_mat->SetRestitution(0.01f); obst_mat->SetYoungModulus(2e7f); obst_mat->SetPoissonRatio(0.3f); obstacle->GetCollisionModel()->ClearModel(); obstacle->GetCollisionModel()->AddCylinder(obst_mat, radius, radius, length * 0.5); obstacle->GetCollisionModel()->BuildModel(); system->AddBody(obstacle); }
bsd-3-clause
matthewgjoseph/basic-computer-science-coding
CS1635/IndividualAssignment3-Spring2013/cocosproject/proj.android/gen/com/cs1635/mgj7/cocosproject/R.java
539
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.cs1635.mgj7.cocosproject; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; public static final int icon=0x7f020001; } public static final class string { public static final int app_name=0x7f030000; } }
bsd-3-clause
jdub/rust-bindgen
libbindgen/src/uses.rs
3529
//! Take in our IR and output a C/C++ file with dummy uses of each IR type. //! //! Say that we had this C++ header, `header.hpp`: //! //! ```c++ //! class Point { //! int x; //! int y; //! } //! //! enum Bar { //! THIS, //! THAT, //! OTHER //! } //! ``` //! //! If we generated dummy uses for this header, we would get a `.cpp` file like //! this: //! //! ```c++ //! #include "header.hpp" //! //! void dummy(Point*) {} //! void dummy(Bar*) {} //! ``` //! //! This is useful because we can compile this `.cpp` file into an object file, //! and then compare its debugging information to the debugging information //! generated for our Rust bindings. These two sets of debugging information had //! better agree on the C/C++ types' physical layout, or else our bindings are //! incorrect! //! //! "But you still haven't explained why we have to generate the dummy uses" you //! complain. Well if the types are never used, then they are elided when the //! C/C++ compiler generates debugging information. use ir::context::BindgenContext; use ir::item::{Item, ItemAncestors, ItemCanonicalName}; use std::io; // Like `canonical_path`, except we always take namespaces into account, ignore // the generated names of anonymous items, and return a `String`. // // TODO: Would it be easier to try and demangle the USR? fn namespaced_name(ctx: &BindgenContext, item: &Item) -> String { let mut names: Vec<_> = item.ancestors(ctx) .map(|id| ctx.resolve_item(id).canonical_name(ctx)) .filter(|name| !name.starts_with("_bindgen_")) .collect(); names.reverse(); names.join("::") } /// Generate the dummy uses for all the items in the given context, and write /// the dummy uses to `dest`. pub fn generate_dummy_uses<W>(ctx: &mut BindgenContext, mut dest: W) -> io::Result<()> where W: io::Write, { ctx.gen(|ctx| { let input_header = ctx.options() .input_header .as_ref() .expect("Should not generate dummy uses without an input header"); try!(writeln!(dest, "/* automatically generated by rust-bindgen */")); try!(writeln!(dest, "")); try!(writeln!(dest, "#include \"{}\"", input_header)); try!(writeln!(dest, "")); let type_items = ctx.whitelisted_items() .map(|id| ctx.resolve_item(id)) .filter(|item| { // We only want type items. if let Some(ty) = item.kind().as_type() { // However, we don't want anonymous types, as we can't // generate dummy uses for them. ty.name().is_some() && // Nor do we want builtin types or named template type // arguments. Again, we can't generate dummy uses for // these. !ty.is_builtin_or_named() && // And finally, we won't be creating any dummy // specializations, so ignore template declarations and // partial specializations. item.applicable_template_args(ctx).is_empty() } else { false } }) .map(|item| namespaced_name(ctx, item)) .enumerate(); for (idx, name) in type_items { try!(writeln!(dest, "void dummy{}({}*) {{ }}", idx, name)); } Ok(()) }) }
bsd-3-clause
DimaHuts/zf-pro
module/Application/src/Service/ConfigFormServiceInterface.php
380
<?php namespace Application\Service; use Zend\Form\Form; interface ConfigFormServiceInterface { /** * This method will pass to a form some configurations * * @param Form $form * @param [] $configurations It is an array that consists of settings for the $form * @return mixed */ public function configForm(Form $form, $configurations); }
bsd-3-clause
wgsyd/wgtf
src/core/lib/core_reflection/base_property_with_metadata.hpp
1760
#ifndef BASE_PROPERTY_WITH_METADATA_HPP #define BASE_PROPERTY_WITH_METADATA_HPP #include "interfaces/i_base_property.hpp" #include "metadata/meta_base.hpp" #include "reflection_dll.hpp" #include <memory> namespace wgt { class REFLECTION_DLL BasePropertyWithMetaData : public IBaseProperty { public: BasePropertyWithMetaData(const IBasePropertyPtr& property, MetaData metaData); virtual ~BasePropertyWithMetaData(); std::shared_ptr< IPropertyPath> generatePropertyName( const std::shared_ptr< const IPropertyPath > & parent) const override; virtual const TypeId& getType() const override; virtual const char* getName() const override; virtual uint64_t getNameHash() const override; virtual const MetaData & getMetaData() const override; virtual bool readOnly(const ObjectHandle& handle) const override; // TODO: remove isMethod and add separate accessors to the class definition for properties and methods. virtual bool isMethod() const override; virtual bool isValue() const override; virtual bool isCollection() const override; virtual bool isByReference() const override; virtual bool set(const ObjectHandle& handle, const Variant& value, const IDefinitionManager& definitionManager) const override; virtual Variant get(const ObjectHandle& handle, const IDefinitionManager& definitionManager) const override; virtual Variant invoke(const ObjectHandle& object, const IDefinitionManager& definitionManager, const ReflectedMethodParameters& parameters) override; virtual size_t parameterCount() const override; IBasePropertyPtr baseProperty() const; private: IBasePropertyPtr property_; MetaData metaData_; }; } // end namespace wgt #endif // BASE_REFLECTED_PROPERTY_HPP
bsd-3-clause
rodijolak/calico
Client/core/src/calico/input/CInputDevice.java
2213
/******************************************************************************* * Copyright (c) 2013, Regents of the University of California * 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. * * None of the name of the Regents of the University of California, or 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. ******************************************************************************/ package calico.input; import calico.*; import it.unimi.dsi.fastutil.ints.*; public class CInputDevice { public static final int TYPE_MOUSE = 1; public static final int TYPE_PEN = 2; public int deviceID = 0; public int type = CInputDevice.TYPE_PEN; public int xpos = 0; public int ypos = 0; public boolean button_left = false; public boolean button_right = false; public boolean button_center = false; public CInputDevice() { } }//
bsd-3-clause
bietiekay/sonos-podcast-service
sonos-podcast-service/ConsoleOutputLogger.cs
3934
using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Globalization; using System.Threading; namespace sonospodcastservice { /// <summary> /// This Class stores a number of Console Output Lines into a ring buffer /// </summary> public class ConsoleOutputLogger { private int Max_Number_Of_Entries = 500; private LinkedList<String> LoggerList = new LinkedList<String>(); public bool verbose = false; public bool writeLogfile = false; private DateTime LastWrite = DateTime.MinValue; private StreamWriter Logfile = null; public void SetNumberOfMaxEntries(int Number) { // TODO: It would be nice to keep at least the Number of Lines we're setting lock (LoggerList) { LoggerList.Clear(); } Max_Number_Of_Entries = Number; } public int GetMaxNumberOfEntries() { return Max_Number_Of_Entries; } private bool lastEntryYesterday() { if (DateTime.Now.Day != LastWrite.Day) return true; else return false; } private String GenerateLogFilename() { CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; // Change culture to en-US. Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE"); String LogFilename = DateTime.Now.ToShortDateString() + ".log"; // Restore original culture. Thread.CurrentThread.CurrentCulture = originalCulture; return LogFilename; } public void LogToFile(String text) { lock(LoggerList) { if (Logfile == null) { WriteLineToScreenOnly("Opening Logfile: " + GenerateLogFilename()); Logfile = new StreamWriter(GenerateLogFilename(), true); Logfile.AutoFlush = true; } if (LastWrite == DateTime.MinValue) LastWrite = DateTime.Now; // check if the day changed, if it did, we start a new log-file if (lastEntryYesterday()) { // when the logfile is open already, we close it if (Logfile != null) Logfile.Close(); // now we reopen/create the new logfile for this day... Logfile = new StreamWriter(GenerateLogFilename(), true); Logfile.AutoFlush = true; } lock (Logfile) { Logfile.WriteLine(text); } } } public void WriteLine(String text) { DateTime TimeDate = DateTime.Now; text = TimeDate.ToShortDateString() + " - " + TimeDate.ToShortTimeString() + " " + text; // write it to the console if (verbose) Console.WriteLine(text); if (writeLogfile) LogToFile(text); LastWrite = TimeDate; lock (LoggerList) { if (LoggerList.Count == Max_Number_Of_Entries) { LoggerList.RemoveFirst(); } LoggerList.AddLast(text); } } public void WriteLineToScreenOnly(String text) { DateTime TimeDate = DateTime.Now; text = TimeDate.ToShortDateString() + " - " + TimeDate.ToShortTimeString() + " " + text; // write it to the console if (verbose) Console.WriteLine(text); } public String[] GetLoggedLines() { String[] Output = new String[Max_Number_Of_Entries]; int Current_Position = 0; lock (LoggerList) { foreach (String line in LoggerList) { Output[Current_Position] = line; Current_Position++; } } return Output; } } }
bsd-3-clause
GeoscienceAustralia/geodesy-sitelog-domain
src/main/java/au/gov/ga/geodesy/sitelog/domain/model/FrequencyStandard.java
1636
package au.gov.ga.geodesy.sitelog.domain.model; import javax.validation.Valid; import javax.validation.constraints.Size; /** * http://sopac.ucsd.edu/ns/geodesy/doc/igsSiteLog/equipment/2004/frequencyStandard.xsd:frequenceStandardType */ public class FrequencyStandard { private Integer id; @Size(max = 200) protected String standardType; @Size(max = 200) protected String inputFrequency; @Valid protected EffectiveDates effectiveDates; @Size(max = 4000) protected String notes; @SuppressWarnings("unused") private Integer getId() { return id; } @SuppressWarnings("unused") private void setId(Integer id) { this.id = id; } /** * Return standard type. */ public String getStandardType() { return standardType; } /** * Set standard type. */ public void setStandardType(String value) { this.standardType = value; } /** * Return input frequency. */ public String getInputFrequency() { return inputFrequency; } /** * Set input frequency. */ public void setInputFrequency(String value) { this.inputFrequency = value; } /** * Return effective dates. */ public EffectiveDates getEffectiveDates() { return effectiveDates; } /** * Set effective dates. */ public void setEffectiveDates(EffectiveDates value) { this.effectiveDates = value; } /** * Return notes. */ public String getNotes() { return notes; } /** * Set notes. */ public void setNotes(String value) { this.notes = value; } }
bsd-3-clause
gudezi/yiiBaseAdvanced
frontend/views/site/nopermitido.php
317
<?php use yii\helpers\Html; /* @var $this yii\web\View */ $this->title = 'About'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-about"> <h1><?= Html::encode($this->title) ?></h1> <div class="alert alert-danger"> <p>No tiene permiso para acceder a esta página.</p> </div> </div>
bsd-3-clause
NCIP/cadsr-cgmdr-nci-uk
src/org/exist/storage/btree/BTreeException.java
2927
/*L * Copyright Oracle Inc * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details. */ package org.exist.storage.btree; /* * dbXML License, Version 1.0 * * * Copyright (c) 1999-2001 The dbXML Group, L.L.C. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by * The dbXML Group (http://www.dbxml.com/)." * Alternately, this acknowledgment may appear in the software * itself, if and wherever such third-party acknowledgments normally * appear. * * 4. The names "dbXML" and "The dbXML Group" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * info@dbxml.com. * * 5. Products derived from this software may not be called "dbXML", * nor may "dbXML" appear in their name, without prior written * permission of The dbXML Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 DBXML GROUP OR ITS 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. * * $Id$ */ /** * A BTreeException is thrown by the BTree if an exception occurs * in the managing of the BTree. */ public class BTreeException extends DBException { public BTreeException() { } public BTreeException(String message) { super(message); } public BTreeException(int faultCode) { super(faultCode); } public BTreeException(int faultCode, String message) { super(faultCode, message); } }
bsd-3-clause
1nv4d3r5/onxshop
controllers/bo/component/file.php
1854
<?php /** * Copyright (c) 2010-2011 Laposa Ltd (http://laposa.co.uk) * Licensed under the New BSD License. See the file LICENSE.txt for details. */ class Onxshop_Controller_Bo_Component_File extends Onxshop_Controller { /** * main action */ public function mainAction() { $file_id = $this->GET['file_id']; $type = $this->GET['type']; $relation = $this->GET['relation']; $File = $this->initializeFile($relation); $this->tpl->assign('IMAGE_CONF', $File->conf); return true; } /** * initialize file */ public function initializeFile($relation) { switch ($relation) { case 'product': require_once('models/ecommerce/ecommerce_product_image.php'); $File = new ecommerce_product_image(); break; case 'product_variety': require_once('models/ecommerce/ecommerce_product_variety_image.php'); $File = new ecommerce_product_variety_image(); break; case 'recipe': require_once('models/ecommerce/ecommerce_recipe_image.php'); $File = new ecommerce_recipe_image(); break; case 'store': require_once('models/ecommerce/ecommerce_store_image.php'); $File = new ecommerce_store_image(); break; case 'survey': require_once('models/education/education_survey_image.php'); $File = new education_survey_image(); break; case 'taxonomy': require_once('models/common/common_taxonomy_label_image.php'); $File = new common_taxonomy_label_image(); break; case 'node': require_once('models/common/common_image.php'); $File = new common_image(); break; case 'print_article': require_once('models/common/common_print_article.php'); $File = new common_print_article(); break; case 'file': default: require_once('models/common/common_file.php'); $File = new common_file(); break; } return $File; } }
bsd-3-clause
clbn/Cachet
resources/lang/no/forms.php
7175
<?php /* * This file is part of Cachet. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return [ // Setup form fields 'setup' => [ 'email' => 'Epost', 'username' => 'Brukernavn', 'password' => 'Passord', 'site_name' => 'Nettstedsnavn', 'site_domain' => 'Nettstedet domene', 'site_timezone' => 'Velg tidssone', 'site_locale' => 'Velg språk', 'enable_google2fa' => 'Aktiver Google Two Factor Authentication', 'cache_driver' => 'Cache-Driver', 'session_driver' => 'Økt Driver', ], // Login form fields 'login' => [ 'login' => 'Username or Email', 'email' => 'Epost', 'password' => 'Passord', '2fauth' => 'Godkjenningskode', 'invalid' => 'Invalid username or password', 'invalid-token' => 'Ugyldig token', 'cookies' => 'Du må aktivere informasjonskapsler for å logge inn.', ], // Incidents form fields 'incidents' => [ 'name' => 'Navn', 'status' => 'Status', 'component' => 'Komponent', 'message' => 'Melding', 'message-help' => 'Du kan også bruke Markdown.', 'scheduled_at' => 'Når ønsker du å planlegge vedlikeholdet?', 'incident_time' => 'When did this incident occur?', 'notify_subscribers' => 'Notify Subscribers?', 'visibility' => 'Incident Visibility', 'public' => 'Viewable by public', 'logged_in_only' => 'Only visible to logged in users', 'templates' => [ 'name' => 'Navn', 'template' => 'Template', 'twig' => 'Incident Templates can make use of the <a href="http://twig.sensiolabs.org/" target="_blank">Twig</a> templating language.', ], ], // Components form fields 'components' => [ 'name' => 'Navn', 'status' => 'Status', 'group' => 'Group', 'description' => 'Description', 'link' => 'Link', 'tags' => 'Tags', 'tags-help' => 'Comma separated.', 'enabled' => 'Component enabled?', 'groups' => [ 'name' => 'Navn', 'collapsed' => 'Collapse the group by default?', ], ], // Metric form fields 'metrics' => [ 'name' => 'Navn', 'suffix' => 'Suffix', 'description' => 'Description', 'description-help' => 'Du kan også bruke Markdown.', 'display-chart' => 'Display chart on status page?', 'default-value' => 'Default Value', 'calc_type' => 'Calculation of Metrics', 'type_sum' => 'Sum', 'type_avg' => 'Average', 'places' => 'Decimal Places', 'default_view' => 'Default View', 'points' => [ 'value' => 'Value', ], ], // Settings 'settings' => [ /// Application setup 'app-setup' => [ 'site-name' => 'Sidenavn', 'site-url' => 'Nettsteds-URL', 'display-graphs' => 'Vis grafer på statussiden?', 'about-this-page' => 'Om denne siden', 'days-of-incidents' => 'How many days of incidents to show?', 'banner' => 'Banner Image', 'banner-help' => 'Det anbefales at du ikke laster opp bilder bredere enn 930 piksler.', 'subscribers' => 'Tillatt brukere å melde seg inn for epostvarslinger?', ], 'analytics' => [ 'analytics_google' => 'Google Analytics code', 'analytics_gosquared' => 'GoSquared Analytics code', 'analytics_piwik_url' => 'URL of your Piwik instance (without http(s)://)', 'analytics_piwik_siteid' => 'Piwik\'s site id', ], 'localization' => [ 'site-timezone' => 'Site Timezone', 'site-locale' => 'Site Language', 'date-format' => 'Date Format', 'incident-date-format' => 'Incident Timestamp Format', ], 'security' => [ 'allowed-domains' => 'Allowed Domains', 'allowed-domains-help' => 'Comma separated. The domain set above is automatically allowed by default.', ], 'stylesheet' => [ 'custom-css' => 'Custom Stylesheet', ], 'theme' => [ 'background-color' => 'Background Color', 'background-fills' => 'Background Fills (Components, Incidents, Footer)', 'banner-background-color' => 'Banner Background Color', 'banner-padding' => 'Banner Padding', 'fullwidth-banner' => 'Enable fullwidth banner?', 'text-color' => 'Text Color', 'dashboard-login' => 'Show dashboard button in the footer?', 'reds' => 'Red (Used for errors)', 'blues' => 'Blue (Used for information)', 'greens' => 'Green (Used for success)', 'yellows' => 'Yellow (Used for alerts)', 'oranges' => 'Orange (Used for notices)', 'metrics' => 'Metrics Fill', 'links' => 'Links', ], ], 'user' => [ 'username' => 'Username', 'email' => 'Epost', 'password' => 'Passord', 'api-token' => 'API Token', 'api-token-help' => 'Regenerating your API token will prevent existing applications from accessing Cachet.', 'gravatar' => 'Change your profile picture at Gravatar.', 'user_level' => 'User Level', 'levels' => [ 'admin' => 'Admin', 'user' => 'User', ], '2fa' => [ 'help' => 'Enabling two factor authentication increases security of your account. You will need to download <a href="https://support.google.com/accounts/answer/1066447?hl=en">Google Authenticator</a> or a similar app on to your mobile device. When you login you will be asked to provide a token generated by the app.', ], 'team' => [ 'description' => 'Invite your team members by entering their email addresses here.', 'email' => 'Email #:id', ], ], // Buttons 'add' => 'Add', 'save' => 'Lagre', 'update' => 'Update', 'create' => 'Opprett', 'edit' => 'Rediger', 'delete' => 'Slett', 'submit' => 'Submit', 'cancel' => 'Cancel', 'remove' => 'Fjern', 'invite' => 'Invite', 'signup' => 'Sign Up', // Other 'optional' => '* Optional', ];
bsd-3-clause
winterbe/nake
test/shell/nakefile.js
3709
task("basic", "test exec/pipe/print", function() { shell(".") .exec("ls") .print() .dir("folder1") .exec("ls") .print() .exec("echo Hi there!") .pipe("cat") .print(); }); task("exec-fn", "test exec with function", function () { shell() .exec("ls -al") .exec(function (result) { print("executing function with result:"); print(result.trim()); }) .print("DONE"); }); task("exec-interpolate", "cmd interpolation", function () { shell() .set("text", "Hi there!") .exec("echo {{text}}") .print(); }); task("dir", "test change dir", function () { shell() .exec("pwd") .print() .dir("folder1") .exec("pwd") .print() .dir("subfolder1") .exec("pwd") .dir("/usr/local") .exec("pwd") .print(); }); task("dir2", "test change .. dir", function() { shell("folder1/subfolder1") .exec("pwd") .print() .dir("..") .exec("pwd") .print() .dir("../folder1/subfolder1") .exec("pwd") .print() .dir("../..") .exec("pwd") .print() .dir("folder1/../folder1/subfolder1") .exec("pwd") .print(); }); task("prompt", "test prompt", function() { shell() .prompt("Who's there?") .print(); }); task("interpolate", "test prompt/print interpolation", function() { shell() .set("foo", "who") .prompt("Who's {{foo}}?") .stash("res") .print("Hi {{res}}!"); }); task("interpolate-default", "test interpolate default value", function () { shell() .set("wat") .print("wait {{}}"); }); task("interpolate-multiple", "test interpolate multiple values", function () { shell() .set("bang") .set("bang", "boom") .print("{{}} - {{bang}} - {{}}"); }); task("eachLine", "test eachLine", function() { shell() .exec("ls -al") .eachLine(function(line, i) { print("${i}: ${line}"); }) .print("DONE"); }); task("stash", "test stash/pipe", function() { shell() .exec("ls -al") .stash("mykey") .exec("ls") .pipe("cat", "mykey") .print(); }); task("unstash", "test stash/unstash", function() { shell() .exec("ls -al") .stash("mykey") .exec("ls") .unstash("mykey") .pipe("cat") .print(); }); task("result", "test return of result", function () { var result = shell() .exec("ls -al") .get(); print(result); }); task("result-stashed", "test return of stashed result", function () { var result = shell() .exec("ls -al") .stash("mylist") .exec("ls") .get("mylist"); print(result); }); task("apply", "test apply", function () { shell() .exec("ls -al") .apply(function (val) { return val.toUpperCase(); }) .print(); }); task("apply-stashed", "test apply stashed", function () { shell() .exec("ls") .stash("mylist") .exec("ls -al") .apply(function (val) { return java.lang.String.join(" ", val.split("\n")); }, "mylist") .unstash("mylist") .print(); }); task("set", "test set", function () { shell() .exec("ls -al") .set("abc") .print(); }); task("set-key", "test set with key", function () { shell() .set("mykey", "BAM") .exec("ls -al") .unstash("mykey") .print(); }); task("showErr", "test show stderr", function () { shell() .showErr() .exec("java -version"); }); task("stashErr1", "test stash stderr as default value", function () { shell() .exec("java -version") .stashErr() .print(); }); task("stashErr2", "test stash stderr with key", function () { shell() .exec("java -version") .stashErr("javaVersion") .print("Result of key=javaVersion:\n{{javaVersion}}"); });
bsd-3-clause
killerwilmer/empopasto_proveedores
core/libs/filter/base_filter/htmlentities_filter.php
1183
<?php /** * KumbiaPHP web & app Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://wiki.kumbiaphp.com/Licencia * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@kumbiaphp.com so we can send you a copy immediately. * * Filtra una cadena Htmlentities * * @category Kumbia * @package Filter * @subpackage BaseFilter * @copyright Copyright (c) 2005-2012 Kumbia Team (http://www.kumbiaphp.com) * @license http://wiki.kumbiaphp.com/Licencia New BSD License */ class HtmlentitiesFilter implements FilterInterface { /** * Ejecuta el filtro * * @param string $s * @param array $options * @return string */ public static function execute ($s, $options) { $charset = (isset($options['charset']) && $options['charset']) ? $options['charset'] : APP_CHARSET; return htmlentities((string) $s, ENT_QUOTES, $charset); } }
bsd-3-clause
Garethp/php-ews
src/API/Message/GetSharingFolder.php
148
<?php namespace garethp\ews\API\Message; /** * Class representing GetSharingFolder */ class GetSharingFolder extends GetSharingFolderType { }
bsd-3-clause
TomAugspurger/pandas
pandas/tests/indexes/categorical/test_reindex.py
2400
import numpy as np from pandas import Categorical, CategoricalIndex, Index import pandas._testing as tm class TestReindex: def test_reindex_dtype(self): c = CategoricalIndex(["a", "b", "c", "a"]) res, indexer = c.reindex(["a", "c"]) tm.assert_index_equal(res, Index(["a", "a", "c"]), exact=True) tm.assert_numpy_array_equal(indexer, np.array([0, 3, 2], dtype=np.intp)) c = CategoricalIndex(["a", "b", "c", "a"]) res, indexer = c.reindex(Categorical(["a", "c"])) exp = CategoricalIndex(["a", "a", "c"], categories=["a", "c"]) tm.assert_index_equal(res, exp, exact=True) tm.assert_numpy_array_equal(indexer, np.array([0, 3, 2], dtype=np.intp)) c = CategoricalIndex(["a", "b", "c", "a"], categories=["a", "b", "c", "d"]) res, indexer = c.reindex(["a", "c"]) exp = Index(["a", "a", "c"], dtype="object") tm.assert_index_equal(res, exp, exact=True) tm.assert_numpy_array_equal(indexer, np.array([0, 3, 2], dtype=np.intp)) c = CategoricalIndex(["a", "b", "c", "a"], categories=["a", "b", "c", "d"]) res, indexer = c.reindex(Categorical(["a", "c"])) exp = CategoricalIndex(["a", "a", "c"], categories=["a", "c"]) tm.assert_index_equal(res, exp, exact=True) tm.assert_numpy_array_equal(indexer, np.array([0, 3, 2], dtype=np.intp)) def test_reindex_duplicate_target(self): # See GH25459 cat = CategoricalIndex(["a", "b", "c"], categories=["a", "b", "c", "d"]) res, indexer = cat.reindex(["a", "c", "c"]) exp = Index(["a", "c", "c"], dtype="object") tm.assert_index_equal(res, exp, exact=True) tm.assert_numpy_array_equal(indexer, np.array([0, 2, 2], dtype=np.intp)) res, indexer = cat.reindex( CategoricalIndex(["a", "c", "c"], categories=["a", "b", "c", "d"]) ) exp = CategoricalIndex(["a", "c", "c"], categories=["a", "b", "c", "d"]) tm.assert_index_equal(res, exp, exact=True) tm.assert_numpy_array_equal(indexer, np.array([0, 2, 2], dtype=np.intp)) def test_reindex_empty_index(self): # See GH16770 c = CategoricalIndex([]) res, indexer = c.reindex(["a", "b"]) tm.assert_index_equal(res, Index(["a", "b"]), exact=True) tm.assert_numpy_array_equal(indexer, np.array([-1, -1], dtype=np.intp))
bsd-3-clause
pranavpandey/pranavpandey.github.io
src/pages/pp-contact.js
4998
/** * @license * Copyright (c) 2019 Pranav Pandey. * Copyright (c) 2018 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ import { PolymerElement, html } from '@polymer/polymer/polymer-element.js'; import '@polymer/iron-form/iron-form.js'; import '@polymer/paper-input/paper-input-container.js'; import '@polymer/paper-input/paper-input.js'; import '@polymer/paper-input/paper-input-error.js'; import '@polymer/paper-input/paper-textarea.js'; import '@google-web-components/google-map/google-map.js'; import '../elements/pp-content.js'; class PPContact extends PolymerElement { static get template() { return html` <style include="pp-styles"></style> <pp-content url="../../data/contact.json" theme="[[theme]]" loading="{{loading}}"> </pp-content> <div class="weight-half"> <h2 class="padding-horizontal">Form</h2> <!-- Add your email id for the contact form --> <paper-card> <div class="card-content"> <iron-form id="contactform"> <form action="https://formspree.io/YOUR_EMAIL_ID" method="post"> <h3 class="card-subtitle">If you have any queries or anything good for me, you can contact me via this form.</h3> <input type="text" name="_gotcha" style="display:none"> <paper-input class="margin-top" type="text" name="name" label="Name" floatinglabel required auto-validate error-message="Name cannot be empty!"> <iron-icon slot="prefix" class="small" icon="pp-icons:person"></iron-icon> </paper-input> <paper-input class="margin-top" name="_replyto" type="email" label="Email" floatinglabel required auto-validate error-message="Please enter your email id."> <iron-icon slot="prefix" class="small" icon="pp-icons:mail"></iron-icon> </paper-input> <paper-input class="margin-top" type="text" name="_subject" label="Subject" floatinglabel required auto-validate error-message="Please enter subject."> <iron-icon slot="prefix" class="small" icon="pp-icons:create"></iron-icon> </paper-input> <paper-textarea class="margin-top" id="message" type="text" label="Message" name="message" floatinglabel multiline rows="3" required placeholder="Something about your subject..." error-message="Message cannot be empty!"> </paper-textarea> </form> </iron-form> </div> <div class="card-actions contact-footer"> <paper-button id="btn_submit" class="secondary" raised on-tap="submitForm"> <iron-icon class="small" icon="pp-icons:submit"></iron-icon> Submit </paper-button> <paper-button class="secondary" on-tap="resetForm"> <iron-icon class="small" icon="pp-icons:reset"></iron-icon> Reset </paper-button> </div> </paper-card> </div> <div class="weight-half"> <h2 class="padding-horizontal">Map</h2> <!-- Modify Google Maps according to your need --> <paper-card> <google-map latitude="LATITUDE" longitude="LONGITUDE" api-key="YOUR_API_KEY" zoom="13"> <google-map-marker latitude="LATITUDE" longitude="LONGITUDE" title="TITLE" draggable="true"> </google-map-marker> </google-map> <div class="card-content"> <h3 class="card-subtitle no-vertical-margin"> YOUR_LOCATION_TEXT </h3> </div> </paper-card> </div> `; } static get properties() { return { theme: { type: String, notify: true }, loading: { type: Boolean, value: false, notify: true } }; } ready() { super.ready(); this.$.contactform.addEventListener( 'iron-form-submit', function(event) { event.target.fire('show-toast', { 'text': 'Thanks for contacting me. I will get back to you soon!', }); }); this.$.contactform.addEventListener( 'iron-form-presubmit', function(event) { event.target.reset(); }); } submitForm() { this.shadowRoot.querySelector('iron-form').submit(); } resetForm() { this.shadowRoot.querySelector('iron-form').reset();s } } window.customElements.define('pp-contact', PPContact);
bsd-3-clause
morozovigor/carbax
console/migrations/m150914_091518_create_phone_table.php
981
<?php use yii\db\Schema; use yii\db\Migration; class m150914_091518_create_phone_table extends Migration { public function up() { $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'; } $this->createTable('phone', [ 'id' => Schema::TYPE_PK, 'service_id' => Schema::TYPE_INTEGER . '(10) NOT NULL', 'number' => Schema::TYPE_STRING . '(255) ', ], $tableOptions); $this->addForeignKey('phone_service_id_fk', 'phone', 'service_id', 'services', 'id', 'RESTRICT', 'CASCADE'); } public function down() { $this->dropForeignKey('phone_service_id_fk', 'phone'); $this->dropTable('phone'); } /* // Use safeUp/safeDown to run migration code within a transaction public function safeUp() { } public function safeDown() { } */ }
bsd-3-clause
mozilla/relman-auto-nag
auto_nag/scripts/good_first_bug_unassign_inactive.py
1727
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. from auto_nag import utils from auto_nag.bzcleaner import BzCleaner class GoodFirstBugUnassignInactive(BzCleaner): def __init__(self): super(GoodFirstBugUnassignInactive, self).__init__() self.nmonths = utils.get_config(self.name(), "months_lookup") self.autofix_assignee = {} def description(self): return "Bugs with good-first-bug keyword and no activity for the last {} months".format( self.nmonths ) def get_autofix_change(self): return self.autofix_assignee def handle_bug(self, bug, data): bugid = str(bug["id"]) doc = self.get_documentation() self.autofix_assignee[bugid] = { "comment": { "body": "This good-first-bug hasn't had any activity for {} months, it is automatically unassigned.\n{}".format( self.nmonths, doc ) }, "reset_assigned_to": True, "status": "NEW", } return bug def get_bz_params(self, date): fields = ["assigned_to"] params = { "include_fields": fields, "resolution": "---", "f1": "keywords", "o1": "casesubstring", "v1": "good-first-bug", "f2": "days_elapsed", "o2": "greaterthan", "v2": self.nmonths * 30, } utils.get_empty_assignees(params, True) return params if __name__ == "__main__": GoodFirstBugUnassignInactive().run()
bsd-3-clause
sunnysideup/addons.silverstripe.org
ssu/code/cms/ExtensionTagGroup_Admin.php
986
<?php class ExtensionTagGroup_Admin extends ModelAdmin { public static $managed_models = array( 'MetaExtensionTagGroup', 'ExtensionTagGroup', 'TopicChange', 'TopicChangeIPAddress', 'AddonKeyword', 'FavouritesToComposerRecord', ); public static $url_segment = 'taggroup'; public static $menu_title = 'Tag Groups'; public $showImportForm = false; public function getEditForm($id = null, $fields = null) { $form = parent::getEditForm(); //This check is simply to ensure you are on the managed model you want adjust accordingly if ($this->modelClass === 'MetaExtensionTagGroup' || $this->modelClass === 'ExtensionTagGroup') { if ($gridField = $form->Fields()->dataFieldByName($this->sanitiseClassName($this->modelClass))) { $gridField->getConfig()->addComponent(new GridFieldSortableRows('SortOrder')); } } return $form; } }
bsd-3-clause
pjreiniger/TempAllWpi
wpilibjIntegrationTests/src/main/java/edu/wpi/first/wpilibj/fixtures/MotorEncoderFixture.java
7211
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2008-2017 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.fixtures; import java.lang.reflect.ParameterizedType; import java.util.logging.Logger; import edu.wpi.first.wpilibj.Counter; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.PWM; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.test.TestBench; /** * Represents a physically connected Motor and Encoder to allow for unit tests on these different * pairs<br> Designed to allow the user to easily setup and tear down the fixture to allow for * reuse. This class should be explicitly instantiated in the TestBed class to allow any test to * access this fixture. This allows tests to be mailable so that you can easily reconfigure the * physical testbed without breaking the tests. */ public abstract class MotorEncoderFixture<T extends SpeedController> implements ITestFixture { private static final Logger logger = Logger.getLogger(MotorEncoderFixture.class.getName()); private boolean m_initialized = false; private boolean m_tornDown = false; protected T m_motor; private Encoder m_encoder; private final Counter[] m_counters = new Counter[2]; protected DigitalInput m_alphaSource; // Stored so it can be freed at tear down protected DigitalInput m_betaSource; /** * Default constructor for a MotorEncoderFixture. */ public MotorEncoderFixture() { } public abstract int getPDPChannel(); /** * Where the implementer of this class should pass the speed controller Constructor should only be * called from outside this class if the Speed controller is not also an implementation of PWM * interface. * * @return SpeedController */ protected abstract T giveSpeedController(); /** * Where the implementer of this class should pass one of the digital inputs. * * <p>CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS! * * @return DigitalInput */ protected abstract DigitalInput giveDigitalInputA(); /** * Where the implementer fo this class should pass the other digital input. * * <p>CONSTRUCTOR SHOULD NOT BE CALLED FROM OUTSIDE THIS CLASS! * * @return Input B to be used when this class is instantiated */ protected abstract DigitalInput giveDigitalInputB(); private final void initialize() { synchronized (this) { if (!m_initialized) { m_initialized = true; // This ensures it is only initialized once m_alphaSource = giveDigitalInputA(); m_betaSource = giveDigitalInputB(); m_encoder = new Encoder(m_alphaSource, m_betaSource); m_counters[0] = new Counter(m_alphaSource); m_counters[1] = new Counter(m_betaSource); logger.fine("Creating the speed controller!"); m_motor = giveSpeedController(); } } } @Override public boolean setup() { initialize(); return true; } /** * Gets the motor for this Object. * * @return the motor this object refers too */ public T getMotor() { initialize(); return m_motor; } /** * Gets the encoder for this object. * * @return the encoder that this object refers too */ public Encoder getEncoder() { initialize(); return m_encoder; } public Counter[] getCounters() { initialize(); return m_counters; } /** * Retrieves the name of the motor that this object refers to. * * @return The simple name of the motor {@link Class#getSimpleName()} */ public String getType() { initialize(); return m_motor.getClass().getSimpleName(); } /** * Checks to see if the speed of the motor is within some range of a given value. This is used * instead of equals() because doubles can have inaccuracies. * * @param value The value to compare against * @param accuracy The accuracy range to check against to see if the * @return true if the range of values between motors speed accuracy contains the 'value'. */ public boolean isMotorSpeedWithinRange(double value, double accuracy) { initialize(); return Math.abs(Math.abs(m_motor.get()) - Math.abs(value)) < Math.abs(accuracy); } @Override public boolean reset() { initialize(); m_motor.setInverted(false); m_motor.set(0); Timer.delay(TestBench.MOTOR_STOP_TIME); // DEFINED IN THE TestBench m_encoder.reset(); for (Counter c : m_counters) { c.reset(); } boolean wasReset = true; wasReset = wasReset && m_motor.get() == 0; wasReset = wasReset && m_encoder.get() == 0; for (Counter c : m_counters) { wasReset = wasReset && c.get() == 0; } return wasReset; } /** * Safely tears down the MotorEncoder Fixture in a way that makes sure that even if an object * fails to initialize the rest of the fixture can still be torn down and the resources * deallocated. */ @Override @SuppressWarnings("Regexp") public boolean teardown() { String type; if (m_motor != null) { type = getType(); } else { type = "null"; } if (!m_tornDown) { boolean wasNull = false; if (m_motor instanceof PWM && m_motor != null) { ((PWM) m_motor).free(); m_motor = null; } else if (m_motor == null) { wasNull = true; } if (m_encoder != null) { m_encoder.free(); m_encoder = null; } else { wasNull = true; } if (m_counters[0] != null) { m_counters[0].free(); m_counters[0] = null; } else { wasNull = true; } if (m_counters[1] != null) { m_counters[1].free(); m_counters[1] = null; } else { wasNull = true; } if (m_alphaSource != null) { m_alphaSource.free(); m_alphaSource = null; } else { wasNull = true; } if (m_betaSource != null) { m_betaSource.free(); m_betaSource = null; } else { wasNull = true; } m_tornDown = true; if (wasNull) { throw new NullPointerException("MotorEncoderFixture had null params at teardown"); } } else { throw new RuntimeException(type + " Motor Encoder torn down multiple times"); } return true; } @Override public String toString() { StringBuilder string = new StringBuilder("MotorEncoderFixture<"); // Get the generic type as a class @SuppressWarnings("unchecked") Class<T> class1 = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]; string.append(class1.getSimpleName()); string.append(">"); return string.toString(); } }
bsd-3-clause
ros/catkin
test/unit_tests/test_catkin_find.py
1195
import imp import os import unittest imp.load_source('catkin_find', os.path.join(os.path.dirname(__file__), '..', '..', 'bin', 'catkin_find')) from catkin_find import parse_args # noqa: E402 class CatkinFindTest(unittest.TestCase): def test_parse_args_empty(self): args = parse_args([]) self.assertEqual(False, args.first_only) self.assertIsNone(args.path) self.assertIsNone(args.project) self.assertIsNone(args.install_folders) def test_parse_args_folders(self): args = parse_args(['--etc', '--lib', '--bin']) self.assertEqual(False, args.first_only) self.assertIsNone(args.path) self.assertIsNone(args.project) self.assertEqual(['etc', 'lib', 'bin'], args.install_folders) args = parse_args(['--etc', '--bin', '--lib']) self.assertEqual(['etc', 'bin', 'lib'], args.install_folders) def test_parse_args_first(self): args = parse_args(['--first-only']) self.assertEqual(True, args.first_only) self.assertIsNone(args.path) self.assertIsNone(args.project) self.assertIsNone(args.install_folders)
bsd-3-clause
fluffynuts/PeanutButter
source/Utils/PeanutButter.DuckTyping/Shimming/IsADuckAttribute.cs
275
using System; namespace PeanutButter.DuckTyping.Shimming { /// <summary> /// Attribute added to all types created by the TypeMaker, usually consumed /// during efforts to duck-type /// </summary> public class IsADuckAttribute : Attribute { } }
bsd-3-clause
Newlooc/task_manager
module/Task/src/Controller/RegisterController.php
2474
<?php namespace Task\Controller; use Zend\View\Model\ViewModel; use Zend\Mvc\Controller\AbstractActionController; use Task\Model\RegisterInterFace; use Task\Model\User; use Task\Model\AuthInterface; use Zend\Form\Form; use Zend\Authentication\Storage\StorageInterface; class RegisterController extends AbstractActionController { protected $userCommand; protected $registerForm; protected $session; protected $auth; public function __construct( RegisterInterface $userCommand, Form $registerForm, StorageInterface $session, AuthInterface $auth ) { $this->userCommand = $userCommand; $this->registerForm = $registerForm; $this->session = $session; $this->auth = $auth; } public function registerAction() { if($this->session->read()) { return $this->redirect()->toRoute('task'); } $errorFlags = [ 'userExist' => [ 'userNameExist' =>false, 'emailExist' =>false, ], 'passwdNotEqual' => false, ]; /* $captcha = new Figlet([ 'name' => 'foo', 'wordLen' => '4', 'timeout' => '300', ]); $id = $captcha->generate(); $char = $captcha->getFiglet()->render($captcha->getWord()); pc($char); $image = new Image(); $image->setFont('/var/www/task_manager/public/fonts/Arial.ttf'); $image->setWordLen(4); $id = $image->generate(); pc($id); pc($image->getId()); pc($image->isValid('122')); */ $view = new ViewModel([ 'registerForm' => $this->registerForm, 'errorFlags' => $errorFlags, ]); $request = $this->getRequest(); if(!$request->isPost()){ return $view; } $this->registerForm->setData($request->getPost()); if(!$this->registerForm->isValid()) { return $view; } if( $request->getPost()['registerFieldset']['passwd'] != $request->getPost()['registerFieldset']['passwdConfrim'] ) { $errorFlags['passwdNotEqual'] = true; } $this->userCommand->setUser($this->registerForm->getData()); $check = $this->userCommand->checkUserExist(); $errorFlags['userExist'] = $check; if( $errorFlags['userExist']['userNameExist'] || $errorFlags['userExist']['emailExist'] || $errorFlags['passwdNotEqual'] ) { return new ViewModel([ 'registerForm' => $this->registerForm, 'errorFlags' => $errorFlags, ]); } $this->userCommand->register(); if($this->auth->registerAuth($this->registerForm->getData())) { return $this->redirect()->toRoute('task'); } return $view; } }
bsd-3-clause
minktom/spree_ghetto_faq
app/helpers/spree/admin/questions_helper.rb
41
module Spree::Admin::QuestionsHelper end
bsd-3-clause
CartoDB/cartodb
spec/support/shared_entities_spec_helper.rb
2858
module SharedEntitiesSpecHelper extend ActiveSupport::Concern def share_table(table, user) permission = table.table_visualization.permission permission.update!( acl: [ { type: Carto::Permission::TYPE_USER, entity: { id: user.id }, access: Carto::Permission::ACCESS_READONLY } ] ) end def http_share_table(table, owner, user) bypass_named_maps headers = { 'CONTENT_TYPE' => 'application/json' } perm_id = table.table_visualization.permission.id request_payload = { acl: [ { type: Carto::Permission::TYPE_USER, entity: { id: user.id }, access: Carto::Permission::ACCESS_READONLY } ] }.to_json put( api_v1_permissions_update_url(user_domain: owner.username, api_key: owner.api_key, id: perm_id), request_payload, headers ) response.status.should == 200 end def share_table_with_user(table, user, access: Carto::Permission::ACCESS_READONLY) vis = CartoDB::Visualization::Member.new(id: table.table_visualization.id).fetch per = vis.permission per.set_user_permission(user, access) per.save per.reload end def share_visualization_with_user(visualization, user, access: Carto::Permission::ACCESS_READONLY) vis = CartoDB::Visualization::Member.new(id: visualization.id).fetch per = vis.permission per.set_user_permission(user, access) per.save per.reload end def share_table_with_organization(table, owner, organization) bypass_named_maps headers = { 'CONTENT_TYPE' => 'application/json' } perm_id = table.table_visualization.permission.id params = { acl: [ { type: Carto::Permission::TYPE_ORGANIZATION, entity: { id: organization.id }, access: Carto::Permission::ACCESS_READONLY } ] } url = api_v1_permissions_update_url(user_domain: owner.username, api_key: owner.api_key, id: perm_id) put url, params.to_json, headers last_response.status.should == 200 end def share_visualization(visualization, user, access = Carto::Permission::ACCESS_READONLY) Carto::SharedEntity.create( recipient_id: user.id, recipient_type: Carto::SharedEntity::RECIPIENT_TYPE_USER, entity_id: visualization.id, entity_type: Carto::SharedEntity::ENTITY_TYPE_VISUALIZATION ) owner = visualization.user perm_id = visualization.permission.id params = { acl: [ { type: Carto::Permission::TYPE_USER, entity: { id: user.id }, access: access } ] } url = api_v1_permissions_update_url(user_domain: owner.username, api_key: owner.api_key, id: perm_id) put_json url, params do |response| response.status.should == 200 end end end
bsd-3-clause
multmeio/django-hstore-flattenfields
example/app/forms.py
212
''' Created on 24/05/2013 @author: luan ''' from hstore_flattenfields.forms import HStoreModelForm from models import Something class SomethingForm(HStoreModelForm): class Meta: model = Something
bsd-3-clause
loopCM/chromium
content/browser/renderer_host/pepper/pepper_message_filter.cc
19957
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/pepper/pepper_message_filter.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/process_util.h" #include "base/threading/sequenced_worker_pool.h" #include "base/threading/worker_pool.h" #include "build/build_config.h" #include "content/browser/renderer_host/pepper/pepper_socket_utils.h" #include "content/browser/renderer_host/pepper/pepper_tcp_server_socket.h" #include "content/browser/renderer_host/pepper/pepper_tcp_socket.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/common/pepper_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/resource_context.h" #include "content/public/common/content_client.h" #include "net/base/address_family.h" #include "net/base/address_list.h" #include "net/base/host_port_pair.h" #include "net/base/sys_addrinfo.h" #include "net/cert/cert_verifier.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/private/ppb_net_address_private.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/shared_impl/api_id.h" #include "ppapi/shared_impl/private/net_address_private_impl.h" using ppapi::NetAddressPrivateImpl; namespace content { namespace { const size_t kMaxSocketsAllowed = 1024; const uint32 kInvalidSocketID = 0; } // namespace PepperMessageFilter::PepperMessageFilter(int process_id, BrowserContext* browser_context) : plugin_type_(PLUGIN_TYPE_IN_PROCESS), permissions_(), process_id_(process_id), external_plugin_render_view_id_(0), resource_context_(browser_context->GetResourceContext()), host_resolver_(NULL), next_socket_id_(1) { DCHECK(browser_context); // Keep BrowserContext data in FILE-thread friendly storage. browser_path_ = browser_context->GetPath(); incognito_ = browser_context->IsOffTheRecord(); DCHECK(resource_context_); } PepperMessageFilter::PepperMessageFilter( const ppapi::PpapiPermissions& permissions, net::HostResolver* host_resolver) : plugin_type_(PLUGIN_TYPE_OUT_OF_PROCESS), permissions_(permissions), process_id_(0), external_plugin_render_view_id_(0), resource_context_(NULL), host_resolver_(host_resolver), next_socket_id_(1), incognito_(false) { DCHECK(host_resolver); } PepperMessageFilter::PepperMessageFilter( const ppapi::PpapiPermissions& permissions, net::HostResolver* host_resolver, int process_id, int render_view_id) : plugin_type_(PLUGIN_TYPE_EXTERNAL_PLUGIN), permissions_(permissions), process_id_(process_id), external_plugin_render_view_id_(render_view_id), resource_context_(NULL), host_resolver_(host_resolver), next_socket_id_(1) { DCHECK(host_resolver); } void PepperMessageFilter::OverrideThreadForMessage( const IPC::Message& message, BrowserThread::ID* thread) { if (message.type() == PpapiHostMsg_PPBTCPServerSocket_Listen::ID || message.type() == PpapiHostMsg_PPBTCPSocket_Connect::ID || message.type() == PpapiHostMsg_PPBTCPSocket_ConnectWithNetAddress::ID) { *thread = BrowserThread::UI; } } bool PepperMessageFilter::OnMessageReceived(const IPC::Message& msg, bool* message_was_ok) { bool handled = true; IPC_BEGIN_MESSAGE_MAP_EX(PepperMessageFilter, msg, *message_was_ok) // TCP messages. IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPSocket_Create, OnTCPCreate) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPSocket_Connect, OnTCPConnect) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPSocket_ConnectWithNetAddress, OnTCPConnectWithNetAddress) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPSocket_SSLHandshake, OnTCPSSLHandshake) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPSocket_Read, OnTCPRead) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPSocket_Write, OnTCPWrite) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPSocket_Disconnect, OnTCPDisconnect) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPSocket_SetBoolOption, OnTCPSetBoolOption) // TCP Server messages. IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPServerSocket_Listen, OnTCPServerListen) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPServerSocket_Accept, OnTCPServerAccept) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBTCPServerSocket_Destroy, RemoveTCPServerSocket) // NetworkMonitor messages. IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBNetworkMonitor_Start, OnNetworkMonitorStart) IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBNetworkMonitor_Stop, OnNetworkMonitorStop) // X509 certificate messages. IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBX509Certificate_ParseDER, OnX509CertificateParseDER); IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP_EX() return handled; } void PepperMessageFilter::OnIPAddressChanged() { GetAndSendNetworkList(); } net::HostResolver* PepperMessageFilter::GetHostResolver() { return resource_context_ ? resource_context_->GetHostResolver() : host_resolver_; } net::CertVerifier* PepperMessageFilter::GetCertVerifier() { if (!cert_verifier_) cert_verifier_.reset(net::CertVerifier::CreateDefault()); return cert_verifier_.get(); } uint32 PepperMessageFilter::AddAcceptedTCPSocket( int32 routing_id, uint32 plugin_dispatcher_id, net::StreamSocket* socket) { scoped_ptr<net::StreamSocket> s(socket); uint32 tcp_socket_id = GenerateSocketID(); if (tcp_socket_id != kInvalidSocketID) { tcp_sockets_[tcp_socket_id] = linked_ptr<PepperTCPSocket>( new PepperTCPSocket(this, routing_id, plugin_dispatcher_id, tcp_socket_id, s.release())); } return tcp_socket_id; } void PepperMessageFilter::RemoveTCPServerSocket(uint32 socket_id) { TCPServerSocketMap::iterator iter = tcp_server_sockets_.find(socket_id); if (iter == tcp_server_sockets_.end()) { NOTREACHED(); return; } // Destroy the TCPServerSocket instance will cancel any pending completion // callback. From this point on, there won't be any messages associated with // this socket sent to the plugin side. tcp_server_sockets_.erase(iter); } PepperMessageFilter::~PepperMessageFilter() { if (!network_monitor_ids_.empty()) net::NetworkChangeNotifier::RemoveIPAddressObserver(this); } void PepperMessageFilter::OnTCPCreate(int32 routing_id, uint32 plugin_dispatcher_id, uint32* socket_id) { *socket_id = GenerateSocketID(); if (*socket_id == kInvalidSocketID) return; tcp_sockets_[*socket_id] = linked_ptr<PepperTCPSocket>( new PepperTCPSocket(this, routing_id, plugin_dispatcher_id, *socket_id)); } void PepperMessageFilter::OnTCPConnect(int32 routing_id, uint32 socket_id, const std::string& host, uint16_t port) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); content::SocketPermissionRequest params( content::SocketPermissionRequest::TCP_CONNECT, host, port); bool allowed = CanUseSocketAPIs(routing_id, params); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&PepperMessageFilter::DoTCPConnect, this, allowed, routing_id, socket_id, host, port)); } void PepperMessageFilter::DoTCPConnect(bool allowed, int32 routing_id, uint32 socket_id, const std::string& host, uint16_t port) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); TCPSocketMap::iterator iter = tcp_sockets_.find(socket_id); if (iter == tcp_sockets_.end()) { // Due to current permission check process (IO -> UI -> IO) some // calls to TCPSocketPrivate interface can be intermixed (like // Connect and Close). So, NOTREACHED() is not needed there. return; } if (routing_id == iter->second->routing_id() && allowed) iter->second->Connect(host, port); else iter->second->SendConnectACKError(); } void PepperMessageFilter::OnTCPConnectWithNetAddress( int32 routing_id, uint32 socket_id, const PP_NetAddress_Private& net_addr) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); bool allowed = CanUseSocketAPIs( routing_id, pepper_socket_utils::CreateSocketPermissionRequest( content::SocketPermissionRequest::TCP_CONNECT, net_addr)); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&PepperMessageFilter::DoTCPConnectWithNetAddress, this, allowed, routing_id, socket_id, net_addr)); } void PepperMessageFilter::DoTCPConnectWithNetAddress( bool allowed, int32 routing_id, uint32 socket_id, const PP_NetAddress_Private& net_addr) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); TCPSocketMap::iterator iter = tcp_sockets_.find(socket_id); if (iter == tcp_sockets_.end()) { // Due to current permission check process (IO -> UI -> IO) some // calls to TCPSocketPrivate interface can be intermixed (like // ConnectWithNetAddress and Close). So, NOTREACHED() is not // needed there. return; } if (routing_id == iter->second->routing_id() && allowed) iter->second->ConnectWithNetAddress(net_addr); else iter->second->SendConnectACKError(); } void PepperMessageFilter::OnTCPSSLHandshake( uint32 socket_id, const std::string& server_name, uint16_t server_port, const std::vector<std::vector<char> >& trusted_certs, const std::vector<std::vector<char> >& untrusted_certs) { TCPSocketMap::iterator iter = tcp_sockets_.find(socket_id); if (iter == tcp_sockets_.end()) { NOTREACHED(); return; } iter->second->SSLHandshake(server_name, server_port, trusted_certs, untrusted_certs); } void PepperMessageFilter::OnTCPRead(uint32 socket_id, int32_t bytes_to_read) { TCPSocketMap::iterator iter = tcp_sockets_.find(socket_id); if (iter == tcp_sockets_.end()) { NOTREACHED(); return; } iter->second->Read(bytes_to_read); } void PepperMessageFilter::OnTCPWrite(uint32 socket_id, const std::string& data) { TCPSocketMap::iterator iter = tcp_sockets_.find(socket_id); if (iter == tcp_sockets_.end()) { NOTREACHED(); return; } iter->second->Write(data); } void PepperMessageFilter::OnTCPDisconnect(uint32 socket_id) { TCPSocketMap::iterator iter = tcp_sockets_.find(socket_id); if (iter == tcp_sockets_.end()) { NOTREACHED(); return; } // Destroying the TCPSocket instance will cancel any pending completion // callback. From this point on, there won't be any messages associated with // this socket sent to the plugin side. tcp_sockets_.erase(iter); } void PepperMessageFilter::OnTCPSetBoolOption(uint32 socket_id, uint32_t name, bool value) { TCPSocketMap::iterator iter = tcp_sockets_.find(socket_id); if (iter == tcp_sockets_.end()) { NOTREACHED(); return; } iter->second->SetBoolOption(name, value); } void PepperMessageFilter::OnTCPServerListen(int32 routing_id, uint32 plugin_dispatcher_id, PP_Resource socket_resource, const PP_NetAddress_Private& addr, int32_t backlog) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); bool allowed = CanUseSocketAPIs( routing_id, pepper_socket_utils::CreateSocketPermissionRequest( content::SocketPermissionRequest::TCP_LISTEN, addr)); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&PepperMessageFilter::DoTCPServerListen, this, allowed, routing_id, plugin_dispatcher_id, socket_resource, addr, backlog)); } void PepperMessageFilter::DoTCPServerListen(bool allowed, int32 routing_id, uint32 plugin_dispatcher_id, PP_Resource socket_resource, const PP_NetAddress_Private& addr, int32_t backlog) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (!allowed) { Send(new PpapiMsg_PPBTCPServerSocket_ListenACK(routing_id, plugin_dispatcher_id, socket_resource, 0, PP_ERROR_FAILED)); return; } uint32 socket_id = GenerateSocketID(); if (socket_id == kInvalidSocketID) { Send(new PpapiMsg_PPBTCPServerSocket_ListenACK(routing_id, plugin_dispatcher_id, socket_resource, 0, PP_ERROR_NOSPACE)); return; } PepperTCPServerSocket* socket = new PepperTCPServerSocket( this, routing_id, plugin_dispatcher_id, socket_resource, socket_id); tcp_server_sockets_[socket_id] = linked_ptr<PepperTCPServerSocket>(socket); socket->Listen(addr, backlog); } void PepperMessageFilter::OnTCPServerAccept(int32 tcp_client_socket_routing_id, uint32 server_socket_id) { TCPServerSocketMap::iterator iter = tcp_server_sockets_.find(server_socket_id); if (iter == tcp_server_sockets_.end()) { NOTREACHED(); return; } iter->second->Accept(tcp_client_socket_routing_id); } void PepperMessageFilter::OnNetworkMonitorStart(uint32 plugin_dispatcher_id) { // Support all in-process plugins, and ones with "private" permissions. if (plugin_type_ != PLUGIN_TYPE_IN_PROCESS && !permissions_.HasPermission(ppapi::PERMISSION_PRIVATE)) { return; } if (network_monitor_ids_.empty()) net::NetworkChangeNotifier::AddIPAddressObserver(this); network_monitor_ids_.insert(plugin_dispatcher_id); GetAndSendNetworkList(); } void PepperMessageFilter::OnNetworkMonitorStop(uint32 plugin_dispatcher_id) { // Support all in-process plugins, and ones with "private" permissions. if (plugin_type_ != PLUGIN_TYPE_IN_PROCESS && !permissions_.HasPermission(ppapi::PERMISSION_PRIVATE)) { return; } network_monitor_ids_.erase(plugin_dispatcher_id); if (network_monitor_ids_.empty()) net::NetworkChangeNotifier::RemoveIPAddressObserver(this); } void PepperMessageFilter::OnX509CertificateParseDER( const std::vector<char>& der, bool* succeeded, ppapi::PPB_X509Certificate_Fields* result) { if (der.size() == 0) *succeeded = false; *succeeded = PepperTCPSocket::GetCertificateFields(&der[0], der.size(), result); } uint32 PepperMessageFilter::GenerateSocketID() { // TODO(yzshen): Change to use Pepper resource ID as socket ID. // // Generate a socket ID. For each process which sends us socket requests, IDs // of living sockets must be unique, to each socket type. // // However, it is safe to generate IDs based on the internal state of a single // PepperSocketMessageHandler object, because for each plugin or renderer // process, there is at most one PepperMessageFilter (in other words, at most // one PepperSocketMessageHandler) talking to it. if (tcp_sockets_.size() + tcp_server_sockets_.size() >= kMaxSocketsAllowed) return kInvalidSocketID; uint32 socket_id = kInvalidSocketID; do { // Although it is unlikely, make sure that we won't cause any trouble when // the counter overflows. socket_id = next_socket_id_++; } while (socket_id == kInvalidSocketID || tcp_sockets_.find(socket_id) != tcp_sockets_.end() || tcp_server_sockets_.find(socket_id) != tcp_server_sockets_.end()); return socket_id; } bool PepperMessageFilter::CanUseSocketAPIs(int32 render_id, const content::SocketPermissionRequest& params) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // External plugins always get their own PepperMessageFilter, initialized with // a render view id. Use this instead of the one that came with the message, // which is actually an API ID. bool external_plugin = false; if (plugin_type_ == PLUGIN_TYPE_EXTERNAL_PLUGIN) { external_plugin = true; render_id = external_plugin_render_view_id_; } RenderViewHostImpl* render_view_host = RenderViewHostImpl::FromID(process_id_, render_id); return pepper_socket_utils::CanUseSocketAPIs(external_plugin, params, render_view_host); } void PepperMessageFilter::GetAndSendNetworkList() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostBlockingPoolTask( FROM_HERE, base::Bind(&PepperMessageFilter::DoGetNetworkList, this)); } void PepperMessageFilter::DoGetNetworkList() { scoped_ptr<net::NetworkInterfaceList> list(new net::NetworkInterfaceList()); net::GetNetworkList(list.get()); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&PepperMessageFilter::SendNetworkList, this, base::Passed(&list))); } void PepperMessageFilter::SendNetworkList( scoped_ptr<net::NetworkInterfaceList> list) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); scoped_ptr< ::ppapi::NetworkList> list_copy( new ::ppapi::NetworkList(list->size())); for (size_t i = 0; i < list->size(); ++i) { const net::NetworkInterface& network = list->at(i); ::ppapi::NetworkInfo& network_copy = list_copy->at(i); network_copy.name = network.name; network_copy.addresses.resize(1, NetAddressPrivateImpl::kInvalidNetAddress); bool result = NetAddressPrivateImpl::IPEndPointToNetAddress( network.address, 0, &(network_copy.addresses[0])); DCHECK(result); // TODO(sergeyu): Currently net::NetworkInterfaceList provides // only name and one IP address. Add all other fields and copy // them here. network_copy.type = PP_NETWORKLIST_UNKNOWN; network_copy.state = PP_NETWORKLIST_UP; network_copy.display_name = network.name; network_copy.mtu = 0; } for (NetworkMonitorIdSet::iterator it = network_monitor_ids_.begin(); it != network_monitor_ids_.end(); ++it) { Send(new PpapiMsg_PPBNetworkMonitor_NetworkList( ppapi::API_ID_PPB_NETWORKMANAGER_PRIVATE, *it, *list_copy)); } } } // namespace content
bsd-3-clause
zackgalbreath/CDash
models/buildconfigureerror.php
2439
<?php /*========================================================================= Program: CDash - Cross-Platform Dashboard System Module: $Id: buildconfigureerror.php 2567 2010-07-27 15:07:22Z zach.mullen $ Language: PHP Date: $Date: 2010-07-27 15:07:22 +0000 (Tue, 27 Jul 2010) $ Version: $Revision: 2567 $ Copyright (c) 2002 Kitware, Inc. All rights reserved. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ /** BuildConfigureError class */ class BuildConfigureError { var $Type; var $Text; var $BuildId; /** Return if exists */ function Exists() { if(!$this->BuildId || !is_numeric($this->BuildId)) { echo "BuildConfigureError::Save(): BuildId not set"; return false; } if(!$this->Type || !is_numeric($this->Type) ) { echo "BuildConfigureError::Save(): Type not set"; return false; } $query = pdo_query("SELECT count(*) AS c FROM configureerror WHERE buildid='".$this->BuildId."' AND type='".$this->Type."' AND text='".$this->Text."'"); add_last_sql_error("BuildConfigureError:Exists",0,$this->BuildId); $query_array = pdo_fetch_array($query); if($query_array['c']>0) { return true; } return false; } /** Save in the database */ function Save() { if(!$this->BuildId || !is_numeric($this->BuildId)) { echo "BuildConfigureError::Save(): BuildId not set"; return false; } if(!$this->Type || !is_numeric($this->Type)) { echo "BuildConfigureError::Save(): Type not set"; return false; } if(!$this->Exists()) { $text = pdo_real_escape_string($this->Text); $query = "INSERT INTO configureerror (buildid,type,text) VALUES (".qnum($this->BuildId).",".qnum($this->Type).",'$text')"; if(!pdo_query($query)) { add_last_sql_error("BuildConfigureError:Save",0,$this->BuildId); return false; } } return true; } } ?>
bsd-3-clause
mbuckley/pixel-perfect
lib/sdk/core/system.js
2801
/* See license.txt for terms of usage */ "use strict"; const { Cu, Ci } = require("chrome"); const { getMostRecentBrowserWindow } = require("sdk/window/utils"); const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {}); const { Services } = Cu.import("resource://gre/modules/Services.jsm", {}); const currentBrowserVersion = Services.appinfo.platformVersion; let System = {}; /** * Compare the current browser version with the provided version argument. * * @param version string to compare with. * @returns {Integer} Possible result values: * is smaller than 0, the current version < version * equals 0 then the current version == version * is bigger than 0, then the current version > version */ System.compare = function(version) { return Services.vc.compare(currentBrowserVersion, version); } /** * Returns true if the current browser version is equal or bigger than * the giver version. The version can be specified as a string or number. * * @param version {String|Number} string that must correspond * to the version format. Read the following pages: * https://developer.mozilla.org/en/docs/Toolkit_version_format * https://addons.mozilla.org/en-US/firefox/pages/appversions/ * The version can be also specified as a simple number that is converted * to the version string. * * @returns {Boolean} True if the current browser version is equal or bigger. */ System.versionIsAtLeast = function(version) { if (typeof version == "number") { version = version + ".0a1"; } return System.compare(version) >= 0; } /** * Returns true if the current browser comes from Developer Edition channel * (formerly Aurora). */ System.isDeveloperBrowser = function() { try { let value = Services.prefs.getCharPref("app.update.channel"); // xxxHonza: "nightly-gum" can be removed at some point. return (value == "aurora") || (value == "nightly-gum"); } catch (err) { // Exception is thrown when the preference doesn't exist } return false; } /** * Returns true if the current browser supports multiprocess feature * (known also as Electrolysis & e10s) */ System.isMultiprocessEnabled = function(browserDoc) { if (Services.appinfo.browserTabsRemoteAutostart) { return true; } if (browserDoc) { let browser = browserDoc.getElementById("content"); if (browser && browser.mCurrentBrowser.isRemoteBrowser) { return true; } } let browser = getMostRecentBrowserWindow(); if (browser && browser.gBrowser.isRemoteBrowser) { return true; } return false; } /** * Safe require for devtools modules. */ System.devtoolsRequire = function(uri) { try { return devtools["require"](uri); } catch (err) { return {}; } } // Exports from this module exports.System = System;
bsd-3-clause
fernando3287/friendly
views/usuarios/aceptar.php
715
<?php /* @var $this yii\web\View */ /* @var $model app\models\Usuario */ ?> <div class="usuario-view"> <div class="enlaces"> <h3>Algunas sugerencias...</h3> <br> <a href="https://www.google.com/intl/es/gmail/about/" class="boton_enlace"><img src="/img/gmail.png" alt="" class="enlace"></a> <a href="https://www.microsoft.com/es-es/outlook-com" class="boton_enlace"><img src="/img/outlook.jpg" alt="" class="enlace"></a> <a href="https://www.gmx.es" class="boton_enlace"><img src="/img/gmx.png" alt="" class="enlace"></a> <a href="https://es.yahoo.com" class="boton_enlace"><img src="/img/yahoo.jpg" alt="" class="enlace"></a> </div> </div>
bsd-3-clause
threerings/depot
src/main/java/com/samskivert/depot/DataSourceConnectionProvider.java
4021
// // samskivert library - useful routines for java programs // Copyright (C) 2001-2012 Michael Bayne, et al. // http://github.com/samskivert/samskivert/blob/master/COPYING package com.samskivert.depot; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import static com.samskivert.depot.Log.log; /** * Provides connections using a pair of {@link DataSource} instances (one for read-only operations * and one for read-write operations). Note: if transactions are going to be used, the data sources * must be pooled data sources, otherwise bad things will happen. */ public class DataSourceConnectionProvider implements ConnectionProvider { /** * Creates a connection provider that will obtain connections from the supplied read-only and * read-write sources. The <code>ident</code> mechanism is not used by this provider. * Responsibility for the lifecycle of the supplied datasources is left to the caller and is * not managed by the connection provider ({@link #shutdown} does nothing). * * @param url a URL prefix that can be used to identify the type of database being accessed by * the supplied data sources, this should be one of "jdbc:mysql" or "jdbc:postgresql" as those * are the only two types of database currently supported. */ public DataSourceConnectionProvider (String url, DataSource readSource, DataSource writeSource) { _url = url; _readSource = readSource; _writeSource = writeSource; } // from ConnectionProvider public Connection getConnection (String ident, boolean readOnly) { return getConnection(ident, readOnly, null); } // from ConnectionProvider public void releaseConnection (String ident, boolean readOnly, Connection conn) { try { conn.close(); } catch (Exception e) { log.warning("Failure closing connection", "ident", ident, "ro", readOnly, "conn", conn, e); } } // from ConnectionProvider public void connectionFailed (String ident, boolean readOnly, Connection conn, SQLException error) { try { conn.close(); } catch (Exception e) { log.warning("Failure closing failed connection", "ident", ident, "ro", readOnly, "conn", conn, e); } } // from ConnectionProvider public Connection getTxConnection (String ident) { // our connections are pooled, so we can just get them normally return getConnection(ident, false, false); } // from ConnectionProvider public void releaseTxConnection (String ident, Connection conn) { // our connections are pooled, so we can just release them normally releaseConnection(ident, false, conn); } // from ConnectionProvider public void txConnectionFailed (String ident, Connection conn, SQLException error) { // our connections are pooled, so we can just fail them normally connectionFailed(ident, false, conn, error); } // from ConnectionProvider public String getURL (String ident) { return _url; } // from ConnectionProvider public void shutdown () { // nothing doing, the caller has to shutdown the datasources } protected Connection getConnection (String ident, boolean readOnly, Boolean autoCommit) { try { Connection conn; if (readOnly) { conn = _readSource.getConnection(); conn.setReadOnly(true); } else { conn = _writeSource.getConnection(); } if (autoCommit != null) conn.setAutoCommit(autoCommit); return conn; } catch (SQLException sqe) { throw new DatabaseException(sqe); } } protected String _url; protected DataSource _readSource, _writeSource; }
bsd-3-clause
rcarmo/crab
scikits/crab/metrics/pairwise.py
18499
#-*- coding:utf-8 -*- """Utilities to evaluate pairwise distances or metrics between 2 sets of points. """ # Authors: Marcel Caraciolo <marcel@muricoca.com> # Bruno Melo <bruno@muricoca.com> # License: BSD Style. import numpy as np import scipy.spatial.distance as ssd def euclidean_distances(X, Y, squared=False, inverse=True): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. An implementation of a "similarity" based on the Euclidean "distance" between two vectors X and Y. Thinking of items as dimensions and preferences as points along those dimensions, a distance is computed using all items (dimensions) where both users have expressed a preference for that item. This is simply the square root of the sum of the squares of differences in position (preference) along each dimension. Parameters ---------- X: array of shape (n_samples_1, n_features) Y: array of shape (n_samples_2, n_features) squared: boolean, optional This routine will return squared Euclidean distances instead. inverse: boolean, optional This routine will return the inverse Euclidean distances instead. Returns ------- distances: array of shape (n_samples_1, n_samples_2) Examples -------- >>> from scikits.crab.metrics.pairwise import euclidean_distances >>> X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0],[3.0, 3.5, 1.5, 5.0, 3.5,3.0]] >>> # distrance between rows of X >>> euclidean_distances(X, X) array([[ 1. , 0.29429806], [ 0.29429806, 1. ]]) >>> # get distance to origin >>> X = [[1.0, 0.0],[1.0,1.0]] >>> euclidean_distances(X, [[0.0, 0.0]]) #doctest: +NORMALIZE_WHITESPACE array([[ 0.5 ], [ 0.41421356]]) """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. if X is Y: X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) if X.shape[1] != Y.shape[1]: raise ValueError("Incompatible dimension for X and Y matrices") if squared: return ssd.cdist(X, Y, 'sqeuclidean') #workaround for Numpy bug that destroys array structure: # np.double(np.asarray([[5,5]])) == array([[ 5., 5.]]) # but np.double(np.asarray([[5]])) == 5.0 !!! if X.shape[1] == 1: XY = np.asarray([[np.sqrt(((X[0][0]-Y[0][0])**2))]]) else: XY = ssd.cdist(X, Y) return np.divide(1.0, (1.0 + XY)) if inverse else XY euclidian_distances = euclidean_distances # both spelling for backward compat def pearson_correlation(X, Y): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. This correlation implementation is equivalent to the cosine similarity since the data it receives is assumed to be centered -- mean is 0. The correlation may be interpreted as the cosine of the angle between the two vectors defined by the users' preference values. Parameters ---------- X: array of shape (n_samples_1, n_features) Y: array of shape (n_samples_2, n_features) Returns ------- distances: array of shape (n_samples_1, n_samples_2) Examples -------- >>> from scikits.crab.metrics.pairwise import pearson_correlation >>> X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0],[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]] >>> # distance between rows of X >>> pearson_correlation(X, X) #doctest: +NORMALIZE_WHITESPACE array([[ 1., 1.], [ 1., 1.]]) >>> pearson_correlation(X, [[3.0, 3.5, 1.5, 5.0, 3.5,3.0]]) #doctest: +NORMALIZE_WHITESPACE array([[ 0.39605902], [ 0.39605902]]) """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. if X is Y: X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) if X.shape[1] != Y.shape[1]: raise ValueError("Incompatible dimension for X and Y matrices") XY = ssd.cdist(X, Y, 'correlation', 2) return 1 - XY def jaccard_coefficient(X, Y): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. This correlation implementation is a statistic used for comparing the similarity and diversity of sample sets. The Jaccard coefficient measures similarity between sample sets, and is defined as the size of the intersection divided by the size of the union of the sample sets. Parameters ---------- X: array of shape (n_samples_1, n_features) Y: array of shape (n_samples_2, n_features) Returns ------- distances: array of shape (n_samples_1, n_samples_2) Examples -------- >>> from scikits.crab.metrics.pairwise import jaccard_coefficient >>> X = [['a', 'b', 'c', 'd'],['e', 'f','g']] >>> # distance between rows of X >>> jaccard_coefficient(X, X) array([[ 1., 0.], [ 0., 1.]]) >>> jaccard_coefficient(X, [['a', 'b', 'c', 'k']]) array([[ 0.6], [ 0. ]]) """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. if X is Y: X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) #TODO: Check if it is possible to optimize this function result = [] i = 0 for arrayX in X: result.append([]) for arrayY in Y: n_XY = np.intersect1d(arrayY, arrayX).size result[i].append(n_XY / (float(len(arrayX)) + len(arrayY) - n_XY)) result[i] = np.array(result[i]) i += 1 #XY = np.array([ [np.intersect1d(y,x).size / (float(len(x)) + len(y) - np.intersect1d(y,x).size)] for y in Y for x in X]) return np.array(result) def manhattan_distances(X, Y): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. This distance implementation is the distance between two points in a grid based on a strictly horizontal and/or vertical path (that is, along the grid lines as opposed to the diagonal or "as the crow flies" distance. The Manhattan distance is the simple sum of the horizontal and vertical components, whereas the diagonal distance might be computed by applying the Pythagorean theorem. Parameters ---------- X: array of shape (n_samples_1, n_features) Y: array of shape (n_samples_2, n_features) Returns ------- distances: array of shape (n_samples_1, n_samples_2) Examples -------- >>> from scikits.crab.metrics.pairwise import manhattan_distances >>> X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0],[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]] >>> # distance between rows of X >>> manhattan_distances(X, X) array([[ 1., 1.], [ 1., 1.]]) >>> manhattan_distances(X, [[3.0, 3.5, 1.5, 5.0, 3.5,3.0]]) #doctest: +NORMALIZE_WHITESPACE array([[ 0.25], [ 0.25]]) """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. if X is Y: X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) if X.shape[1] != Y.shape[1]: raise ValueError("Incompatible dimension for X and Y matrices") XY = ssd.cdist(X, Y, 'cityblock') return 1.0 - (XY / float(X.shape[1])) def sorensen_coefficient(X, Y): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. The Sørensen index, also known as Sørensen’s similarity coefficient, is a statistic used for comparing the similarity of two samples. It was developed by the botanist Thorvald Sørensen and published in 1948. [1] See the link:http://en.wikipedia.org/wiki/S%C3%B8rensen_similarity_index This is intended for "binary" data sets where a user either expresses a generic "yes" preference for an item or has no preference. The actual preference values do not matter here, only their presence or absence. Parameters ---------- X: array of shape (n_samples_1, n_features) Y: array of shape (n_samples_2, n_features) Returns ------- distances: array of shape (n_samples_1, n_samples_2) Examples -------- >>> from scikits.crab.metrics.pairwise import sorensen_coefficient >>> X = [['a', 'b', 'c', 'd'],['e', 'f','g']] >>> # distance between rows of X >>> sorensen_coefficient(X, X) #doctest: +NORMALIZE_WHITESPACE array([[ 1., 0.], [ 0., 1.]]) >>> sorensen_coefficient(X, [['a', 'b', 'c', 'k']]) #doctest: +NORMALIZE_WHITESPACE array([[ 0.75], [ 0. ]]) """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. if X is Y: X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) #TODO: Check if it is possible to optimize this function #XY = np.array([np.intersect1d(x,y).size for y in Y for x in X]) XY = [] i = 0 for arrayX in X: XY.append([]) for arrayY in Y: XY[i].append(2 * np.intersect1d(arrayX, arrayY).size / float(len(arrayX) + len(arrayY))) XY[i] = np.array(XY[i]) i += 1 XY = np.array(XY) return XY def tanimoto_coefficient(X, Y): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. An implementation of a "similarity" based on the Tanimoto coefficient, or extended Jaccard coefficient. This is intended for "binary" data sets where a user either expresses a generic "yes" preference for an item or has no preference. The actual preference values do not matter here, only their presence or absence. Parameters ---------- X: array of shape n_samples_1 Y: array of shape n_samples_2 Returns ------- distances: array of shape (n_samples_1, n_samples_2) Examples -------- >>> from scikits.crab.metrics.pairwise import tanimoto_coefficient >>> X = [['a', 'b', 'c', 'd'],['e', 'f','g']] >>> # distance between rows of X >>> tanimoto_coefficient(X, X) array([[ 1., 0.], [ 0., 1.]]) >>> tanimoto_coefficient(X, [['a', 'b', 'c', 'k']]) array([[ 0.6], [ 0. ]]) """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. if X is Y: X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) #TODO: Check if it is possible to optimize this function result = [] i = 0 for arrayX in X: result.append([]) for arrayY in Y: n_XY = np.intersect1d(arrayY, arrayX).size result[i].append(n_XY / (float(len(arrayX)) + len(arrayY) - n_XY)) result[i] = np.array(result[i]) i += 1 #XY = np.array([ [np.intersect1d(y,x).size / (float(len(x)) + len(y) - np.intersect1d(y,x).size)] for y in Y for x in X]) return np.array(result) def cosine_distances(X, Y): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. An implementation of the cosine similarity. The result is the cosine of the angle formed between the two preference vectors. Note that this similarity does not "center" its data, shifts the user's preference values so that each of their means is 0. For this behavior, use Pearson Coefficient, which actually is mathematically equivalent for centered data. Parameters ---------- X: array of shape (n_samples_1, n_features) Y: array of shape (n_samples_2, n_features) Returns ------- distances: array of shape (n_samples_1, n_samples_2) Examples -------- >>> from scikits.crab.metrics.pairwise import cosine_distances >>> X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0],[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]] >>> # distance between rows of X >>> cosine_distances(X, X) #doctest: +NORMALIZE_WHITESPACE array([[ 1., 1.], [ 1., 1.]]) >>> cosine_distances(X, [[3.0, 3.5, 1.5, 5.0, 3.5,3.0]]) array([[ 0.9606463], [ 0.9606463]]) """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. if X is Y: X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) if X.shape[1] != Y.shape[1]: raise ValueError("Incompatible dimension for X and Y matrices") return 1. - ssd.cdist(X, Y, 'cosine') def spearman_coefficient(X, Y): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. Like Pearson Coefficient , but compares relative ranking of preference values instead of preference values themselves. That is, each user's preferences are sorted and then assign a rank as their preference value, with 1 being assigned to the least preferred item. Parameters ---------- X: array of shape (n_samples_1, n_features) Y: array of shape (n_samples_2, n_features) Returns ------- distances: array of shape (n_samples_1, n_samples_2) Examples -------- >>> from scikits.crab.metrics.pairwise import spearman_coefficient >>> X = [[('a',2.5),('b', 3.5), ('c',3.0), ('d',3.5)],[ ('e', 2.5),('f', 3.0), ('g', 2.5), ('h', 4.0)] ] >>> # distance between rows of X >>> spearman_coefficient(X, X) array([[ 1., 0.], [ 0., 1.]]) >>> spearman_coefficient(X, [[('a',2.5),('b', 3.5), ('c',3.0), ('k',3.5)]]) array([[ 1.], [ 0.]]) """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. if X is Y: X = Y = np.asanyarray(X, dtype=[('x', 'S30'), ('y', float)]) else: X = np.asanyarray(X, dtype=[('x', 'S30'), ('y', float)]) Y = np.asanyarray(Y, dtype=[('x', 'S30'), ('y', float)]) if X.shape[1] != Y.shape[1]: raise ValueError("Incompatible dimension for X and Y matrices") X.sort(order='y') Y.sort(order='y') result = [] #TODO: Check if it is possible to optimize this function i = 0 for arrayX in X: result.append([]) for arrayY in Y: Y_keys = [key for key, value in arrayY] XY = [(key, value) for key, value in arrayX if key in Y_keys] sumDiffSq = 0.0 for index, tup in enumerate(XY): sumDiffSq += pow((index + 1) - (Y_keys.index(tup[0]) + 1), 2.0) n = len(XY) if n == 0: result[i].append(0.0) else: result[i].append(1.0 - ((6.0 * sumDiffSq) / (n * (n * n - 1)))) result[i] = np.asanyarray(result[i]) i += 1 return np.asanyarray(result) def loglikehood_coefficient(n_items, X, Y): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. Parameters ---------- n_items: int Number of items in the model. X: array of shape (n_samples_1, n_features) Y: array of shape (n_samples_2, n_features) Returns ------- distances: array of shape (n_samples_1, n_samples_2) Examples -------- >>> from scikits.crab.metrics.pairwise import loglikehood_coefficient >>> X = [['a', 'b', 'c', 'd'], ['e', 'f','g', 'h']] >>> # distance between rows of X >>> n_items = 7 >>> loglikehood_coefficient(n_items,X, X) #doctest: +NORMALIZE_WHITESPACE array([[ 1., 0.], [ 0., 1.]]) >>> n_items = 8 >>> loglikehood_coefficient(n_items, X, [['a', 'b', 'c', 'k']]) #doctest: +NORMALIZE_WHITESPACE array([[ 0.67668852], [ 0. ]]) References ---------- See http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.14.5962 and http://tdunning.blogspot.com/2008/03/surprise-and-coincidence.html. """ # should not need X_norm_squared because if you could precompute that as # well as Y, then you should just pre-compute the output and not even # call this function. def safeLog(d): if d <= 0.0: return 0.0 else: return np.log(d) def logL(p, k, n): return k * safeLog(p) + (n - k) * safeLog(1.0 - p) def twoLogLambda(k1, k2, n1, n2): p = (k1 + k2) / (n1 + n2) return 2.0 * (logL(k1 / n1, k1, n1) + logL(k2 / n2, k2, n2) - logL(p, k1, n1) - logL(p, k2, n2)) if X is Y: X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) result = [] # TODO: Check if it is possible to optimize this function i = 0 for arrayX in X: result.append([]) for arrayY in Y: XY = np.intersect1d(arrayX, arrayY) if XY.size == 0: result[i].append(0.0) else: nX = arrayX.size nY = arrayY.size if (nX - XY.size == 0) or (n_items - nY) == 0: result[i].append(1.0) else: logLikelihood = twoLogLambda(float(XY.size), float(nX - XY.size), float(nY), float(n_items - nY)) result[i].append(1.0 - 1.0 / (1.0 + float(logLikelihood))) result[i] = np.asanyarray(result[i]) i += 1 return np.asanyarray(result)
bsd-3-clause
pawelswiszcz/mywedding
module/User/src/User/Mapper/Exception/RuntimeException.php
123
<?php namespace User\Mapper\Exception; class RuntimeException extends \RuntimeException implements ExceptionInterface {}
bsd-3-clause
exponent/exponent
android/expoview/src/main/java/host/exp/exponent/exceptions/ExceptionUtils.java
2959
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.exceptions; import android.content.Context; import android.provider.Settings; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import host.exp.exponent.network.ExponentNetwork; import host.exp.exponent.kernel.ExponentErrorMessage; import host.exp.expoview.Exponent; public class ExceptionUtils { // Converts an exception into and ExponentErrorMessage, which contains both a user facing // error message and a developer facing error message. // Example: // ManifestException with // manifestUrl="exp://exp.host/@exponent/pomodoro" // originalException=UnknownHostException // // turns into: // // ExponentErrorMessage with // userErrorMessage="Could not load exp://exp.host/@exponent/pomodoro. Airplane mode is on." // developerErrorMessage="java.net.UnknownHostException: Unable to resolve host" public static ExponentErrorMessage exceptionToErrorMessage(final Exception exception) { final Context context = Exponent.getInstance().getApplication(); final ExponentErrorMessage defaultResponse = ExponentErrorMessage.developerErrorMessage(exception.toString()); if (context == null) { return defaultResponse; } if (exception instanceof ExponentException) { // Grab both the user facing message from ExponentException String message = exception.toString(); // Append general exception error messages if applicable ExponentException typedException = (ExponentException) exception; if (typedException.originalException() != null) { String userErrorMessage = getUserErrorMessage(typedException.originalException(), context); if (userErrorMessage != null) { message += " " + userErrorMessage; } } return new ExponentErrorMessage(message, typedException.originalExceptionMessage()); } String userErrorMessage = getUserErrorMessage(exception, context); if (userErrorMessage != null) { return defaultResponse.addUserErrorMessage(userErrorMessage); } return defaultResponse; } private static String getUserErrorMessage(final Exception exception, final Context context) { if (exception instanceof UnknownHostException || exception instanceof ConnectException) { if (isAirplaneModeOn(context)) { return "Airplane mode is on. Please turn off and try again."; } else if (!ExponentNetwork.isNetworkAvailable(context)) { return "Can't connect to internet. Please try again."; } } else if (exception instanceof SocketTimeoutException) { return "Network response timed out."; } return null; } private static boolean isAirplaneModeOn(final Context context) { return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0; } }
bsd-3-clause
thijs1108/ParnasSys-statuspage
resources/lang/sq/cachet.php
6550
<?php /* * This file is part of Cachet. * * (c) Alt Three Services Limited * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return [ // Components 'components' => [ 'last_updated' => 'Last updated :timestamp', 'status' => [ 1 => 'Funksionim', 2 => 'Çështje të performancës', 3 => 'Ndërprerje e pjesshëm', 4 => 'Ndërprerje Kryesore', ], 'group' => [ 'other' => 'Other Components', ], ], // Incidents 'incidents' => [ 'none' => 'No incidents reported', 'past' => 'Past Incidents', 'previous_week' => 'Previous Week', 'next_week' => 'Next Week', 'scheduled' => 'Mirëmbajtje planifikuar', 'scheduled_at' => ', planifiko :timestamp', 'status' => [ 0 => 'Planifikuar', // TODO: Hopefully remove this. 1 => 'Hetimin', 2 => 'Identifikohet', 3 => 'Shikim', 4 => 'Rregulluar', ], ], // Service Status 'service' => [ 'good' => '[0,1] System operational|[2,Inf] All systems are operational', 'bad' => '[0,1] The system is currently experiencing issues|[2,Inf] Some systems are experiencing issues', 'major' => '[0,1] The service experiencing a major outage|[2,Inf] Some systems are experiencing a major outage', ], 'api' => [ 'regenerate' => 'Rikrijo çelësin e API-t', 'revoke' => 'Refuzo çelësin e API-t', ], // Metrics 'metrics' => [ 'filter' => [ 'last_hour' => 'Last Hour', 'hourly' => 'Last 12 Hours', 'weekly' => 'Week', 'monthly' => 'Month', ], ], // Subscriber 'subscriber' => [ 'subscribe' => 'Subscribe to get the most recent updates', 'button' => 'Subscribe', 'manage' => [ 'no_subscriptions' => 'You\'re currently subscribed to all updates.', 'my_subscriptions' => 'You\'re currently subscribed to the following updates.', ], 'email' => [ 'subscribe' => 'Subscribe to email updates.', 'subscribed' => 'You\'ve been subscribed to email notifications, please check your email to confirm your subscription.', 'verified' => 'Your email subscription has been confirmed. Thank you!', 'manage' => 'Manage your subscription.', 'unsubscribe' => 'Unsubscribe from email updates.', 'unsubscribed' => 'Your email subscription has been cancelled.', 'failure' => 'Something went wrong with the subscription.', 'already-subscribed' => 'Cannot subscribe :email because they\'re already subscribed.', 'verify' => [ 'text' => "Please confirm your email subscription to :app_name status updates.\n:link\nThank you, :app_name", 'html-preheader' => 'Please confirm your email subscription to :app_name status updates.', 'html' => '<p>Please confirm your email subscription to :app_name status updates.</p><p><a href=":link">:link</a></p><p>Thank you, :app_name</p>', ], 'maintenance' => [ 'text' => "New maintenance has been scheduled on :app_name.\nThank you, :app_name", 'html-preheader' => 'New maintenance has been scheduled on :app_name.', 'html' => '<p>New maintenance has been scheduled on :app_name.</p>', ], 'incident' => [ 'text' => "New incident has been reported on :app_name.\nThank you, :app_name", 'html-preheader' => 'New incident has been reported on :app_name.', 'html' => '<p>New incident has been reported on :app_name.</p><p>Thank you, :app_name</p>', ], 'component' => [ 'subject' => 'Component Status Update', 'text' => 'The component :component_name has seen a status change. The component is now at :component_human_status.\nThank you, :app_name', 'html-preheader' => 'Component Update from :app_name', 'html' => '<p>The component :component_name has seen a status change. The component is now at :component_human_status.</p><p>Thank you, :app_name</p>', 'tooltip-title' => 'Subscribe to notifications for :component_name.', ], ], ], 'users' => [ 'email' => [ 'invite' => [ 'text' => "You have been invited to the team :app_name status page, to sign up follow the next link.\n:link\nThank you, :app_name", 'html-preheader' => 'You have been invited to the team :app_name.', 'html' => '<p>You have been invited to the team :app_name status page, to sign up follow the next link.</p><p><a href=":link">:link</a></p><p>Thank you, :app_name</p>', ], ], ], 'signup' => [ 'title' => 'Sign Up', 'username' => 'Emri i përdoruesit', 'email' => 'Email', 'password' => 'Fjalëkalimi', 'success' => 'Your account has been created.', 'failure' => 'Something went wrong with the signup.', ], 'system' => [ 'update' => 'There is a newer version of Cachet available. You can learn how to update <a href="https://docs.cachethq.io/docs/updating-cachet">here</a>!', ], // Modal 'modal' => [ 'close' => 'Close', 'subscribe' => [ 'title' => 'Subscribe to component updates', 'body' => 'Enter your email address to subscribe to updates for this component. If you\'re already subscribed, you\'ll already receive emails for this component.', 'button' => 'Subscribe', ], ], // Other 'home' => 'Home', 'description' => 'Stay up to date with the latest service updates from :app.', 'powered_by' => ':app Status Page is powered by <a href="https://cachethq.io" class="links">Cachet</a>.', 'about_this_site' => 'About This Site', 'rss-feed' => 'RSS', 'atom-feed' => 'Atom', 'feed' => 'Status Feed', ];
bsd-3-clause
gajus/babel-plugin-log-deprecated
test/fixtures/preset-options/adds-console-warn-to-function-expression-with-name-from-lhs/expected.js
478
/** * @deprecated */ const foo = function () { console.warn("Deprecated: Function \"foo\" is deprecated in /fixtures/preset-options/adds-console-warn-to-function-expression-with-name-from-lhs/actual.js on line 4", { functionName: "foo", message: null, packageName: "bar", packageVersion: "1.0.0", scriptColumn: 12, scriptLine: 4, scriptPath: "fixtures/preset-options/adds-console-warn-to-function-expression-with-name-from-lhs/actual.js" }) };
bsd-3-clause
vovancho/yii2test
controllers/Fregat/RemoveaktController.php
4991
<?php namespace app\controllers\Fregat; use app\func\ReportsTemplate\RemoveaktReport; use app\models\Fregat\RemoveaktFilter; use app\models\Fregat\TrRmMat; use Exception; use Yii; use app\models\Fregat\Removeakt; use app\models\Fregat\RemoveaktSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use app\func\Proc; use yii\filters\AccessControl; use app\models\Fregat\TrRmMatSearch; /** * RemoveaktController implements the CRUD actions for Removeakt model. */ class RemoveaktController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['index', 'removeakt-report', 'removeaktfilter'], 'allow' => true, 'roles' => ['FregatUserPermission'], ], [ 'actions' => ['create', 'update', 'delete'], 'allow' => true, 'roles' => ['RemoveaktEdit'], ], ], ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], ]; } public function actionIndex() { $searchModel = new RemoveaktSearch(); $filter = Proc::SetFilter($searchModel->formName(), new RemoveaktFilter); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'filter' => $filter, ]); } public function actionCreate() { $model = new Removeakt(); if ($model->load(Yii::$app->request->post()) && $model->save()) { Proc::RemoveLastBreadcrumbsFromSession(); // Удаляем последнюю хлебную крошку из сессии (Создать меняется на Обновить) return $this->redirect(['update', 'id' => $model->removeakt_id]); } else { $model->removeakt_date = empty($model->removeakt_date) ? date('Y-m-d') : $model->removeakt_date; return $this->render('create', [ 'model' => $model, ]); } } public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(Proc::GetPreviousURLBreadcrumbsFromSession()); } else { $Request = Yii::$app->request->queryParams; $searchModel = new TrRmMatSearch(); $dataProvider = $searchModel->search($Request); return $this->render('update', [ 'model' => $model, 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } } // Печать акта снятия комплектующих с материальных ценностей public function actionRemoveaktReport() { $Report = new RemoveaktReport(); echo $Report->Execute(); } public function actionRemoveaktfilter() { $model = new RemoveaktFilter; if (Yii::$app->request->isAjax && Yii::$app->request->isGet) { Proc::PopulateFilterForm('RemoveaktSearch', $model); return $this->renderAjax('_removeaktfilter', [ 'model' => $model, ]); } } public function actionDelete($id) { if (Yii::$app->request->isAjax) { $transaction = Yii::$app->db->beginTransaction(); try { TrRmMat::deleteAll(['id_removeakt' => $id]); $Removeakt = $this->findModel($id)->delete(); if ($Removeakt === false) throw new Exception('Удаление невозможно.'); echo $Removeakt; $transaction->commit(); } catch (Exception $e) { $transaction->rollBack(); throw new Exception($e->getMessage() . ' Удаление невозможно.'); } } } /** * Finds the Removeakt model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param string $id * @return Removeakt the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Removeakt::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
bsd-3-clause
us-ignite/us_ignite
us_ignite/snippets/tests/fixtures.py
291
from us_ignite.snippets.models import Snippet def get_snippet(**kwargs): data = { 'name': 'Gigabit snippets', 'slug': 'featured', 'url': 'http://us-ignite.org/', 'image': 'ad.png', } data.update(kwargs) return Snippet.objects.create(**data)
bsd-3-clause
naohisas/KVS
Source/Core/Visualization/Widget/ColorMapBar.cpp
12881
/*****************************************************************************/ /** * @file ColorMapBar.cpp * @author Naohisa Sakamoto */ /*****************************************************************************/ #include "ColorMapBar.h" #include <kvs/Type> #include <kvs/Message> #include <kvs/String> #include <kvs/Math> #include <kvs/EventBase> #include <kvs/IgnoreUnusedVariable> // Constant variables namespace { const double MinValue = 0.0f; const double MaxValue = 255.0f; const size_t ColorMapBarWidth = 200; const size_t ColorMapBarHeight = 20; const size_t ColorMapBarMargin = 10; } namespace kvs { /*===========================================================================*/ /** * @brief Constructs a new ColorMapBar class. * @param screen [in] pointer to the parent screen */ /*===========================================================================*/ ColorMapBar::ColorMapBar( kvs::ScreenBase* screen ): kvs::WidgetBase( screen ), m_show_range_value( true ), m_texture_downloaded( false ), m_screen_updated( nullptr ), m_screen_resized( nullptr ) { BaseClass::addEventType( kvs::EventBase::PaintEvent | kvs::EventBase::ResizeEvent ); BaseClass::setMargin( ::ColorMapBarMargin ); this->setCaption( "" ); this->setOrientation( ColorMapBar::Horizontal ); this->setNumberOfDivisions( 5 ); this->setDivisionLineWidth( 1.0f ); this->setDivisionLineColor( kvs::RGBColor( 0, 0, 0 ) ); this->setRange( ::MinValue, ::MaxValue ); this->setBorderWidth( 1.0f ); this->setBorderColor( kvs::RGBColor( 0, 0, 0 ) ); this->disableAntiAliasing(); m_colormap.setResolution( 256 ); m_colormap.create(); } /*===========================================================================*/ /** * @brief Destroys the ColorMapBar class. */ /*===========================================================================*/ ColorMapBar::~ColorMapBar() { } /*===========================================================================*/ /** * @brief Set the color map to the texture. * @param colormap [in] color map */ /*===========================================================================*/ void ColorMapBar::setColorMap( const kvs::ColorMap& colormap ) { // Deep copy. kvs::ColorMap::Table colormap_table( colormap.table().data(), colormap.table().size() ); m_colormap = kvs::ColorMap( colormap_table ); if ( colormap.hasRange() ) { m_min_value = colormap.minValue(); m_max_value = colormap.maxValue(); } // Download the texture data onto GPU. m_texture_downloaded = false; } /*===========================================================================*/ /** * @brief Paint event. */ /*===========================================================================*/ void ColorMapBar::paintEvent() { this->screenUpdated(); if ( !BaseClass::isVisible() ) return; if ( !m_texture_downloaded ) { this->create_texture(); m_texture_downloaded = true; } BaseClass::painter().begin( BaseClass::screen() ); BaseClass::drawBackground(); const std::string min_value = kvs::String::From( m_min_value ); const std::string max_value = kvs::String::From( m_max_value ); const int text_height = BaseClass::painter().fontMetrics().height(); const int min_text_width = BaseClass::painter().fontMetrics().width( min_value ); const int max_text_width = BaseClass::painter().fontMetrics().width( max_value ); const int caption_height = ( m_caption.size() == 0 ) ? 0 : text_height + 5; const int value_width = ( min_value.size() > max_value.size() ) ? min_text_width : max_text_width; const int value_height = ( m_show_range_value ) ? text_height : 0; // Draw the color bar. { const int w = ( m_orientation == ColorMapBar::Vertical ) ? value_width + 5 : 0; const int h = ( m_orientation == ColorMapBar::Vertical ) ? 0 : value_height; const int x = BaseClass::x0() + BaseClass::margin(); const int y = BaseClass::y0() + BaseClass::margin() + caption_height; const int width = BaseClass::width() - BaseClass::margin() * 2 - w; const int height = BaseClass::height() - BaseClass::margin() * 2 - caption_height - h; this->draw_color_bar( x, y, width, height ); this->draw_border( x, y, width, height ); } // Draw the caption. if ( m_caption.size() != 0 ) { const int x = BaseClass::x0() + BaseClass::margin(); const int y = BaseClass::y0() + BaseClass::margin(); const kvs::Vec2 p( x, y + text_height ); BaseClass::painter().drawText( p, m_caption ); } // Draw the values. if ( m_show_range_value ) { switch ( m_orientation ) { case ColorMapBar::Horizontal: { { const int x = BaseClass::x0() + BaseClass::margin(); const int y = BaseClass::y1() - BaseClass::margin() - text_height; const kvs::Vec2 p( x, y + text_height ); BaseClass::painter().drawText( p, min_value ); } { const int x = BaseClass::x1() - BaseClass::margin() - max_text_width; const int y = BaseClass::y1() - BaseClass::margin() - text_height; const kvs::Vec2 p( x, y + text_height ); BaseClass::painter().drawText( p, max_value ); } break; } case ColorMapBar::Vertical: { { const int x = BaseClass::x1() - BaseClass::margin() - value_width; const int y = BaseClass::y0() + BaseClass::margin() + caption_height; const kvs::Vec2 p( x, y + text_height ); BaseClass::painter().drawText( p, min_value ); } { const int x = BaseClass::x1() - BaseClass::margin() - value_width; const int y = BaseClass::y1() - BaseClass::margin() - text_height; const kvs::Vec2 p( x, y + text_height ); BaseClass::painter().drawText( p, max_value ); } break; } default: break; } } BaseClass::painter().end(); } /*===========================================================================*/ /** * @brief Resize event. * @param width [in] screen width * @param height [in] screen height */ /*===========================================================================*/ void ColorMapBar::resizeEvent( int width, int height ) { kvs::IgnoreUnusedVariable( width ); kvs::IgnoreUnusedVariable( height ); const auto p = BaseClass::anchorPosition(); Rectangle::setPosition( p.x(), p.y() ); this->screenResized(); } /*===========================================================================*/ /** * @brief Returns the initial screen width. * @return screen width */ /*===========================================================================*/ int ColorMapBar::adjustedWidth() { BaseClass::painter().begin( BaseClass::screen() ); const kvs::FontMetrics metrics = BaseClass::painter().fontMetrics(); size_t width = 0; switch ( m_orientation ) { case ColorMapBar::Horizontal: { width = metrics.width( m_caption ) + BaseClass::margin() * 2; width = kvs::Math::Max( width, ::ColorMapBarWidth ); break; } case ColorMapBar::Vertical: { const std::string min_value = kvs::String::From( m_min_value ); const std::string max_value = kvs::String::From( m_max_value ); const size_t min_text_width = metrics.width( min_value ); const size_t max_text_width = metrics.width( max_value ); width = ( min_value.size() > max_value.size() ) ? min_text_width : max_text_width; width += BaseClass::margin() * 2; width = kvs::Math::Max( width, ::ColorMapBarHeight ); break; } default: break; } BaseClass::painter().end(); return static_cast<int>( width ); } /*===========================================================================*/ /** * @brief Returns the initial screen height. * @return screen height */ /*===========================================================================*/ int ColorMapBar::adjustedHeight() { BaseClass::painter().begin( BaseClass::screen() ); const kvs::FontMetrics metrics = BaseClass::painter().fontMetrics(); size_t height = 0; const size_t text_height = metrics.height(); switch ( m_orientation ) { case ColorMapBar::Horizontal: height = ::ColorMapBarHeight + ( text_height + BaseClass::margin() ) * 2; break; case ColorMapBar::Vertical: height = ::ColorMapBarWidth + text_height + BaseClass::margin() * 2; break; default: break; } BaseClass::painter().end(); return static_cast<int>( height ); } /*===========================================================================*/ /** * @brief Create a texture for the color map. */ /*===========================================================================*/ void ColorMapBar::create_texture() { const size_t nchannels = 3; const size_t width = m_colormap.resolution(); const size_t height = 1; const kvs::UInt8* data = m_colormap.table().data(); m_texture.release(); m_texture.setPixelFormat( nchannels, sizeof( kvs::UInt8 ) ); m_texture.setMinFilter( GL_NEAREST ); m_texture.setMagFilter( GL_NEAREST ); m_texture.create( width, height, data ); } /*===========================================================================*/ /** * @brief Release the texture for the color map. */ /*===========================================================================*/ void ColorMapBar::release_texture() { m_texture.release(); } /*===========================================================================*/ /** * @brief Draws the color bar. * @param x [in] x position of the bar * @param y [in] y position of the bar * @param width [in] bar width * @param height [in] bar height */ /*===========================================================================*/ void ColorMapBar::draw_color_bar( const int x, const int y, const int width, const int height ) { kvs::OpenGL::WithPushedAttrib attrib( GL_ALL_ATTRIB_BITS ); attrib.disable( GL_BLEND ); attrib.disable( GL_DEPTH_TEST ); attrib.disable( GL_TEXTURE_3D ); attrib.enable( GL_TEXTURE_2D ); const float dpr = screen()->devicePixelRatio(); const kvs::Vec2 p0 = kvs::Vec2( x, y ) * dpr; const kvs::Vec2 p1 = kvs::Vec2( x + width, y ) * dpr; const kvs::Vec2 p2 = kvs::Vec2( x + width, y + height ) * dpr; const kvs::Vec2 p3 = kvs::Vec2( x, y + height ) * dpr; kvs::Texture::Binder binder( m_texture ); switch ( m_orientation ) { case ColorMapBar::Horizontal: { kvs::OpenGL::Begin( GL_QUADS ); kvs::OpenGL::TexCoordVertex( kvs::Vec2( 0.0f, 1.0f ), p0 ); kvs::OpenGL::TexCoordVertex( kvs::Vec2( 1.0f, 1.0f ), p1 ); kvs::OpenGL::TexCoordVertex( kvs::Vec2( 1.0f, 0.0f ), p2 ); kvs::OpenGL::TexCoordVertex( kvs::Vec2( 0.0f, 0.0f ), p3 ); kvs::OpenGL::End(); break; } case ColorMapBar::Vertical: { kvs::OpenGL::Begin( GL_QUADS ); kvs::OpenGL::TexCoordVertex( kvs::Vec2( 0.0f, 0.0f ), p0 ); kvs::OpenGL::TexCoordVertex( kvs::Vec2( 0.0f, 1.0f ), p1 ); kvs::OpenGL::TexCoordVertex( kvs::Vec2( 1.0f, 1.0f ), p2 ); kvs::OpenGL::TexCoordVertex( kvs::Vec2( 1.0f, 0.0f ), p3 ); kvs::OpenGL::End(); break; } default: break; } } /*===========================================================================*/ /** * @brief Draws the border of the color map. * @param x [in] x position of the color map * @param y [in] y position of the color map * @param width [in] width * @param height [in] height */ /*===========================================================================*/ void ColorMapBar::draw_border( const int x, const int y, const int width, const int height ) { kvs::NanoVG* engine = BaseClass::painter().device()->renderEngine(); engine->beginFrame( screen()->width(), screen()->height(), screen()->devicePixelRatio() ); engine->beginPath(); engine->setStrokeWidth( m_border_width ); engine->roundedRect( x - 0.5f, y + 2.0f, width + 1.0f, height, 3 ); engine->setStrokeColor( kvs::RGBAColor( 250, 250, 250, 0.6f ) ); engine->stroke(); engine->beginPath(); engine->setStrokeWidth( m_border_width ); engine->roundedRect( x - 0.5f, y, width + 1.0f, height, 3 ); engine->setStrokeColor( m_border_color ); engine->stroke(); engine->endFrame(); } } // end of namespace kvs
bsd-3-clause
abdulquddus/classified
backend/models/OptionalfieldBridgeTable.php
961
<?php namespace backend\models; use Yii; /** * This is the model class for table "optionalfield_bridge_table". * * @property integer $id * @property integer $optional_field_key * @property integer $filter_field_key */ class OptionalfieldBridgeTable extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'optionalfield_bridge_table'; } /** * @inheritdoc */ public function rules() { return [ [['optional_field_key', 'filter_field_key'], 'required'], [['optional_field_key', 'filter_field_key'], 'integer'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'optional_field_key' => Yii::t('app', 'Optional Field Key'), 'filter_field_key' => Yii::t('app', 'Filter Field Key'), ]; } }
bsd-3-clause
LinioIT/rule-engine
src/Ast/GetVariableExpressionNode.php
334
<?php declare(strict_types=1); namespace Linio\Component\RuleEngine\Ast; class GetVariableExpressionNode extends Node { protected string $key; public function __construct(string $key) { $this->key = $key; } public function evaluate() { return $this->getContext()->get($this->key); } }
bsd-3-clause