code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
#ifndef CASEFOLDCOMPARE_H #define CASEFOLDCOMPARE_H struct casefoldCompare : public std::binary_function<Glib::ustring, Glib::ustring, bool> { bool operator () ( const Glib::ustring &lhs, const Glib::ustring &rhs ) const { return lhs.casefold() < rhs.casefold(); } }; #endif
egroeper/referencer
src/CaseFoldCompare.h
C
gpl-2.0
282
/* * Copyright (C) 2017 https://github.com/grand-farugi/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* * File: Enemy.cpp * Author: https://github.com/grand-farugi/ * * Created on 19 May 2017, 20:34 */ #include "Enemy.h" #include "../collide/collide.h" #include "../game/InGame.h" #include "Player.h" #include <cstring> #include "Explosion.h" #include "../audio/sfx.h" Enemy::Enemy(float x, float y, float radius, data_file script, data_file sprite, int _health) : EnemyBullet(x, y, radius, script, sprite) { isboss = false; int num_players; for (num_players = MAX_PLAYERS; num_players > 0; num_players--) { if (players[num_players-1] != NULL) { break; } } max_health = _health * num_players; health = max_health; } void Enemy::update() { if (!flash_timer && (normal_palette == NULL)) { normal_palette = new pixel[img->colcount]; memcpy(normal_palette, palette, img->colcount*sizeof(pixel)); } if (flash_timer && (--flash_timer < 2)) memcpy(palette, normal_palette, img->colcount*sizeof(pixel)); EnemyBullet::update(); for (int i = 0; i < sizeof(pBulletList)/sizeof(pBulletList[0]); i++) { if (pBulletList[i] && EnemyBullet::is_colliding(this, pBulletList[i])) { delete pBulletList[i]; if (--health == 0) { InGame::add_object(new Explosion(pos[0], pos[1])); InGame::remove_object(this); if (isboss) play_sfx(SFX_KILLBOSS, 0.2); else play_sfx(SFX_KILL, 0.1); break; } else if (!flash_timer) { pixel col; if ((float)health / max_health > 0.2) { col = color(255, 255, 255); play_sfx(SFX_HIT0, 0.1); } else { play_sfx(SFX_HIT1, 0.2); col = color(255, 0, 0); } for (int c = 0; c < img->colcount; c++) { if (palette[c] != transparent_col) palette[c] = col; } flash_timer = 3; } } } } Enemy::~Enemy() { if (normal_palette != NULL) delete[] normal_palette; }
grand-farugi/damncats
src/object/Enemy.cpp
C++
gpl-2.0
2,982
This folder contains real world data crawled from different websites. #zillow_data.txt (original file 6d-zillow-2245109.txt) Crawled from zillow.com. It contains data on real estates in the USA. The original format of the Zillow data set is *ID bedrooms bathrooms livingArea lotArea yearBuilt taxValue* Zillow size: 2236252 maxLevels[]: 10,10,36,45 #nba_data.txt (original file 5d-nba-17265.txt) NBA size: 17265 maxLevels[]: 10,10,10,10,10 #house_data.txt (original file 6d-hou-127931.txt) #weather_data.txt
endresma/ExplicitPreference
DataGenerator/data/readme.md
Markdown
gpl-2.0
532
#!/bin/bash if [ -z "$DB_DIR" ]; then echo "Need to set DB_DIR" exit 1 fi if [ ! -d "$DB_DIR" ]; then echo "Need to create directory DB_DIR" exit 1 fi export MYSQL_NAME=mysql export MYSQL_VERSION=5.5.28 export MYSQL_STORAGE_ENGINE=tokudb export TARBALL=blank-toku664.52174-mysql-5.5.28 export TOKUDB_COMPRESSION=quicklz export BENCH_ID=664.52174.${TOKUDB_COMPRESSION} export NUM_ROWS=50000000 export NUM_TABLES=1 export RUN_TIME_SECONDS=300 export RAND_TYPE=uniform export TOKUDB_READ_BLOCK_SIZE=64K export BENCHMARK_NUMBER=004 export DIRECTIO=N export threadCountList="0032 0064" export BENCHMARK_LOGGING=Y export LOADER_LOGGING=Y export MYSQL_DATABASE=sbtest export MYSQL_USER=root export TOKUDB_ROW_FORMAT=tokudb_${TOKUDB_COMPRESSION} echo "Creating database from ${TARBALL} in ${DB_DIR}" pushd $DB_DIR mkdb-quiet $TARBALL popd echo "Configuring my.cnf and starting database" pushd $DB_DIR echo "tokudb_read_block_size=${TOKUDB_READ_BLOCK_SIZE}" >> my.cnf echo "tokudb_row_format=${TOKUDB_ROW_FORMAT}" >> my.cnf if [ ${DIRECTIO} == "Y" ]; then echo "tokudb_cache_size=${TOKUDB_DIRECTIO_CACHE}" >> my.cnf echo "tokudb_directIO=1" >> my.cnf fi echo "max_connections=2048" >> my.cnf mstart popd echo "Loading Data" pushd fastload ./run.load.flatfiles.sh popd #echo "Running benchmark" #./run.benchmark.sh echo "Stopping database" mstop
Percona-QA/toku-qa
tokudb/software/sysbench/loader.bash
Shell
gpl-2.0
1,370
<?php /* JM-booking Copyright (C) 2007-2010 Jaermuseet <http://www.jaermuseet.no> Contact: <hn@jaermuseet.no> Project: <http://github.com/hnJaermuseet/JM-booking> Based on ARBS, Advanced Resource Booking System, copyright (C) 2005-2007 ITMC der TU Dortmund <http://sourceforge.net/projects/arbs/>. ARBS is based on MRBS by Daniel Gardner <http://mrbs.sourceforge.net/>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ include "include/admin_top.php"; //fake register globals, its save in the admin-only section foreach($_GET as $key=>$val){ $$key=$val; } //hier saven/endern $area_error=""; $category_error=""; if(isset($submit)){ } if(isset($del_type)) { } if(isset($_GET['section'])) $section = $_GET['section']; else $section = ''; if(isset($_GET['area'])) $section="areas"; if(isset($pid)) $section="periods"; include "include/admin_middel.php";
hnJaermuseet/JM-booking
admin.php
PHP
gpl-2.0
1,509
/* * jQuery Nivo Slider v2.3 * http://nivo.dev7studios.com * * Copyright 2010, Gilbert Pellegrom * Free to use and abuse under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * May 2010 - Pick random effect from specified set of effects by toronegro * May 2010 - controlNavThumbsFromRel option added by nerd-sh * May 2010 - Do not start nivoRun timer if there is only 1 slide by msielski * April 2010 - controlNavThumbs option added by Jamie Thompson (http://jamiethompson.co.uk) * March 2010 - manualAdvance option added by HelloPablo (http://hellopablo.co.uk) */ (function($) { var NivoSlider = function(element, options){ //Defaults are below var settings = $.extend({}, $.fn.nivoSlider.defaults, options); //Useful variables. Play carefully. var vars = { currentSlide: 0, currentImage: '', totalSlides: 0, randAnim: '', running: false, paused: false, stop:false }; //Get this slider var slider = $(element); slider.data('nivo:vars', vars); slider.css('position','relative'); slider.addClass('nivoSlider'); //Find our slider children var kids = slider.children(); kids.each(function() { var child = $(this); var link = ''; if(!child.is('img')){ if(child.is('a')){ child.addClass('nivo-imageLink'); link = child; } child = child.find('img:first'); } //Get img width & height var childWidth = child.width(); if(childWidth == 0) childWidth = child.attr('width'); var childHeight = child.height(); if(childHeight == 0) childHeight = child.attr('height'); //Resize the slider if(childWidth > slider.width()){ slider.width(childWidth); } if(childHeight > slider.height()){ slider.height(childHeight); } if(link != ''){ link.css('display','none'); } child.css('display','none'); vars.totalSlides++; }); //Set startSlide if(settings.startSlide > 0){ if(settings.startSlide >= vars.totalSlides) settings.startSlide = vars.totalSlides - 1; vars.currentSlide = settings.startSlide; } //Get initial image if($(kids[vars.currentSlide]).is('img')){ vars.currentImage = $(kids[vars.currentSlide]); } else { vars.currentImage = $(kids[vars.currentSlide]).find('img:first'); } //Show initial link if($(kids[vars.currentSlide]).is('a')){ $(kids[vars.currentSlide]).css('display','block'); } //Set first background slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat'); //Add initial slices for(var i = 0; i < settings.slices; i++){ var sliceWidth = Math.round(slider.width()/settings.slices); if(i == settings.slices-1){ slider.append( $('<div class="nivo-slice"></div>').css({ left:(sliceWidth*i)+'px', width:(slider.width()-(sliceWidth*i))+'px' }) ); } else { slider.append( $('<div class="nivo-slice"></div>').css({ left:(sliceWidth*i)+'px', width:sliceWidth+'px' }) ); } } //Create caption slider.append( $('<div class="nivo-caption"><p></p></div>').css({ display:'none', opacity:settings.captionOpacity }) ); //Process initial caption if(vars.currentImage.attr('title') != ''){ var title = vars.currentImage.attr('title'); if(title.substr(0,1) == '#') title = $(title).html(); $('.nivo-caption p', slider).html(title); $('.nivo-caption', slider).fadeIn(settings.animSpeed); } //In the words of Super Mario "let's a go!" var timer = 0; if(!settings.manualAdvance && kids.length > 1){ timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime); } //Add Direction nav if(settings.directionNav){ slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">Prev</a><a class="nivo-nextNav">Next</a></div>'); //Hide Direction nav if(settings.directionNavHide){ $('.nivo-directionNav', slider).hide(); slider.hover(function(){ $('.nivo-directionNav', slider).show(); }, function(){ $('.nivo-directionNav', slider).hide(); }); } $('a.nivo-prevNav', slider).live('click', function(){ if(vars.running) return false; clearInterval(timer); timer = ''; vars.currentSlide-=2; nivoRun(slider, kids, settings, 'prev'); }); $('a.nivo-nextNav', slider).live('click', function(){ if(vars.running) return false; clearInterval(timer); timer = ''; nivoRun(slider, kids, settings, 'next'); }); } //Add Control nav if(settings.controlNav){ var nivoControl = $('<div class="nivo-controlNav"></div>'); slider.append(nivoControl); for(var i = 0; i < kids.length; i++){ if(settings.controlNavThumbs){ var child = kids.eq(i); if(!child.is('img')){ child = child.find('img:first'); } if (settings.controlNavThumbsFromRel) { nivoControl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('rel') + '" alt="" /></a>'); } else { nivoControl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('src').replace(settings.controlNavThumbsSearch, settings.controlNavThumbsReplace) +'" alt="" /></a>'); } } else { nivoControl.append('<a class="nivo-control" rel="'+ i +'">'+ (i + 1) +'</a>'); } } //Set initial active link $('.nivo-controlNav a:eq('+ vars.currentSlide +')', slider).addClass('active'); $('.nivo-controlNav a', slider).live('click', function(){ if(vars.running) return false; if($(this).hasClass('active')) return false; clearInterval(timer); timer = ''; slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat'); vars.currentSlide = $(this).attr('rel') - 1; nivoRun(slider, kids, settings, 'control'); }); } //Keyboard Navigation if(settings.keyboardNav){ $(window).keypress(function(event){ //Left if(event.keyCode == '37'){ if(vars.running) return false; clearInterval(timer); timer = ''; vars.currentSlide-=2; nivoRun(slider, kids, settings, 'prev'); } //Right if(event.keyCode == '39'){ if(vars.running) return false; clearInterval(timer); timer = ''; nivoRun(slider, kids, settings, 'next'); } }); } //For pauseOnHover setting if(settings.pauseOnHover){ slider.hover(function(){ vars.paused = true; clearInterval(timer); timer = ''; }, function(){ vars.paused = false; //Restart the timer if(timer == '' && !settings.manualAdvance){ timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime); } }); } //Event when Animation finishes slider.bind('nivo:animFinished', function(){ vars.running = false; //Hide child links $(kids).each(function(){ if($(this).is('a')){ $(this).css('display','none'); } }); //Show current link if($(kids[vars.currentSlide]).is('a')){ $(kids[vars.currentSlide]).css('display','block'); } //Restart the timer if(timer == '' && !vars.paused && !settings.manualAdvance){ timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime); } //Trigger the afterChange callback settings.afterChange.call(this); }); // Private run method var nivoRun = function(slider, kids, settings, nudge){ //Get our vars var vars = slider.data('nivo:vars'); //Trigger the lastSlide callback if(vars && (vars.currentSlide == vars.totalSlides - 1)){ settings.lastSlide.call(this); } // Stop if((!vars || vars.stop) && !nudge) return false; //Trigger the beforeChange callback settings.beforeChange.call(this); //Set current background before change if(!nudge){ slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat'); } else { if(nudge == 'prev'){ slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat'); } if(nudge == 'next'){ slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat'); } } vars.currentSlide++; //Trigger the slideshowEnd callback if(vars.currentSlide == vars.totalSlides){ vars.currentSlide = 0; settings.slideshowEnd.call(this); } if(vars.currentSlide < 0) vars.currentSlide = (vars.totalSlides - 1); //Set vars.currentImage if($(kids[vars.currentSlide]).is('img')){ vars.currentImage = $(kids[vars.currentSlide]); } else { vars.currentImage = $(kids[vars.currentSlide]).find('img:first'); } //Set acitve links if(settings.controlNav){ $('.nivo-controlNav a', slider).removeClass('active'); $('.nivo-controlNav a:eq('+ vars.currentSlide +')', slider).addClass('active'); } //Process caption if(vars.currentImage.attr('title') != ''){ var title = vars.currentImage.attr('title'); if(title.substr(0,1) == '#') title = $(title).html(); if($('.nivo-caption', slider).css('display') == 'block'){ $('.nivo-caption p', slider).fadeOut(settings.animSpeed, function(){ $(this).html(title); $(this).fadeIn(settings.animSpeed); }); } else { $('.nivo-caption p', slider).html(title); } $('.nivo-caption', slider).fadeIn(settings.animSpeed); } else { $('.nivo-caption', slider).fadeOut(settings.animSpeed); } //Set new slice backgrounds var i = 0; $('.nivo-slice', slider).each(function(){ var sliceWidth = Math.round(slider.width()/settings.slices); $(this).css({ height:'0px', opacity:'0', background: 'url("'+ vars.currentImage.attr('src') +'") no-repeat -'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px 0%' }); i++; }); if(settings.effect == 'random'){ var anims = new Array("sliceDownRight","sliceDownLeft","sliceUpRight","sliceUpLeft","sliceUpDown","sliceUpDownLeft","fold","fade"); vars.randAnim = anims[Math.floor(Math.random()*(anims.length + 1))]; if(vars.randAnim == undefined) vars.randAnim = 'fade'; } //Run random effect from specified set (eg: effect:'fold,fade') if(settings.effect.indexOf(',') != -1){ var anims = settings.effect.split(','); vars.randAnim = $.trim(anims[Math.floor(Math.random()*anims.length)]); } //Run effects vars.running = true; if(settings.effect == 'sliceDown' || settings.effect == 'sliceDownRight' || vars.randAnim == 'sliceDownRight' || settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft'){ var timeBuff = 0; var i = 0; var slices = $('.nivo-slice', slider); if(settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft') slices = $('.nivo-slice', slider)._reverse(); slices.each(function(){ var slice = $(this); slice.css('top','0px'); if(i == settings.slices-1){ setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; i++; }); } else if(settings.effect == 'sliceUp' || settings.effect == 'sliceUpRight' || vars.randAnim == 'sliceUpRight' || settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft'){ var timeBuff = 0; var i = 0; var slices = $('.nivo-slice', slider); if(settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft') slices = $('.nivo-slice', slider)._reverse(); slices.each(function(){ var slice = $(this); slice.css('bottom','0px'); if(i == settings.slices-1){ setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; i++; }); } else if(settings.effect == 'sliceUpDown' || settings.effect == 'sliceUpDownRight' || vars.randAnim == 'sliceUpDown' || settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft'){ var timeBuff = 0; var i = 0; var v = 0; var slices = $('.nivo-slice', slider); if(settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft') slices = $('.nivo-slice', slider)._reverse(); slices.each(function(){ var slice = $(this); if(i == 0){ slice.css('top','0px'); i++; } else { slice.css('bottom','0px'); i = 0; } if(v == settings.slices-1){ setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; v++; }); } else if(settings.effect == 'fold' || vars.randAnim == 'fold'){ var timeBuff = 0; var i = 0; $('.nivo-slice', slider).each(function(){ var slice = $(this); var origWidth = slice.width(); slice.css({ top:'0px', height:'100%', width:'0px' }); if(i == settings.slices-1){ setTimeout(function(){ slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); }); }, (100 + timeBuff)); } else { setTimeout(function(){ slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed); }, (100 + timeBuff)); } timeBuff += 50; i++; }); } else if(settings.effect == 'fade' || vars.randAnim == 'fade'){ var i = 0; $('.nivo-slice', slider).each(function(){ $(this).css('height','100%'); if(i == settings.slices-1){ $(this).animate({ opacity:'1.0' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); }); } else { $(this).animate({ opacity:'1.0' }, (settings.animSpeed*2)); } i++; }); } } // For debugging var trace = function(msg){ if (this.console && typeof console.log != "undefined") console.log(msg); } // Start / Stop this.stop = function(){ if(!$(element).data('nivo:vars').stop){ $(element).data('nivo:vars').stop = true; trace('Stop Slider'); } } this.start = function(){ if($(element).data('nivo:vars').stop){ $(element).data('nivo:vars').stop = false; trace('Start Slider'); } } //Trigger the afterLoad callback settings.afterLoad.call(this); }; $.fn.nivoSlider = function(options) { return this.each(function(){ var element = $(this); // Return early if this element already has a plugin instance if (element.data('nivoslider')) return; // Pass options to plugin constructor var nivoslider = new NivoSlider(this, options); // Store plugin object in this element's data element.data('nivoslider', nivoslider); }); }; //Default settings $.fn.nivoSlider.defaults = { effect:'random', slices:15, animSpeed:500, pauseTime:3000, startSlide:0, directionNav:true, directionNavHide:true, controlNav:false, controlNavThumbs:false, controlNavThumbsFromRel:false, controlNavThumbsSearch:'.jpg', controlNavThumbsReplace:'_thumb.jpg', keyboardNav:true, pauseOnHover:true, manualAdvance:false, captionOpacity:0.8, beforeChange: function(){}, afterChange: function(){}, slideshowEnd: function(){}, lastSlide: function(){}, afterLoad: function(){} }; $.fn._reverse = [].reverse; })(jQuery);
acrisdesign/bizchoco
js/jquery.nivo.slider.js
JavaScript
gpl-2.0
18,911
<?php /* Raws Test cases generated on: 2011-03-22 17:23:50 : 1300811030*/ App::import('Controller', 'Raws'); class TestRawsController extends RawsController { var $autoRender = false; function redirect($url, $status = null, $exit = true) { $this->redirectUrl = $url; } } class RawsControllerTestCase extends CakeTestCase { var $fixtures = array('app.raw', 'app.phenotype', 'app.program', 'app.plant', 'app.culture', 'app.experiment', 'app.sample', 'app.phenotype_bbch', 'app.bbch', 'app.species', 'app.phenotype_entity', 'app.entity', 'app.phenotype_raw', 'app.phenotype_value', 'app.value'); function startTest() { $this->Raws =& new TestRawsController(); $this->Raws->constructClasses(); } function endTest() { unset($this->Raws); ClassRegistry::flush(); } function testIndex() { } function testView() { } function testAdd() { } function testEdit() { } function testDelete() { } } ?>
ingkebil/trost
site/cakephp-cakephp-ba95d56/app/tests/cases/controllers/raws_controller.test.php
PHP
gpl-2.0
929
<?php /** * HUBzero CMS * * Copyright 2005-2015 HUBzero Foundation, LLC. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * HUBzero is a registered trademark of Purdue University. * * @package hubzero-cms * @author Shawn Rice <zooley@purdue.edu> * @copyright Copyright 2005-2015 HUBzero Foundation, LLC. * @license http://opensource.org/licenses/MIT MIT */ // No direct access defined('_HZEXEC_') or die(); Toolbar::title(Lang::txt('COM_TOOLS') . ': ' . Lang::txt('COM_TOOLS_SESSIONS'), 'tools'); Toolbar::deleteList(); Toolbar::spacer(); Toolbar::help('sessions'); Html::behavior('tooltip'); ?> <?php $this->view('_submenu') ->display(); ?> <form action="<?php echo Route::url('index.php?option=' . $this->option . '&controller=' . $this->controller); ?>" method="post" name="adminForm" id="adminForm"> <fieldset id="filter-bar"> <label for="filter_appname"><?php echo Lang::txt('COM_TOOLS_APPNAME'); ?>:</label> <select name="appname" id="filter_appname" onchange="document.adminForm.submit();"> <option value=""><?php echo Lang::txt('COM_TOOLS_APPNAME_SELECT'); ?></option> <?php foreach ($this->appnames as $record) { $html = ' <option value="' . $record->appname . '"'; if ($this->filters['appname'] == $record->appname) { $html .= ' selected="selected"'; } $html .= '>' . $this->escape(stripslashes($record->appname)) . '</option>' . "\n"; echo $html; } ?> </select> <label for="filter_exechost"><?php echo Lang::txt('COM_TOOLS_EXECHOST'); ?>:</label> <select name="exechost" id="filter_exechost" onchange="document.adminForm.submit();"> <option value=""><?php echo Lang::txt('COM_TOOLS_EXECHOST_SELECT'); ?></option> <?php foreach ($this->exechosts as $record) { $html = ' <option value="' . $record->exechost . '"'; if ($this->filters['exechost'] == $record->exechost) { $html .= ' selected="selected"'; } $html .= '>' . $this->escape(stripslashes($record->exechost)) . '</option>' . "\n"; echo $html; } ?> </select> <label for="filter_username"><?php echo Lang::txt('COM_TOOLS_USERNAME'); ?>:</label> <select name="username" id="filter_username" onchange="document.adminForm.submit();"> <option value=""><?php echo Lang::txt('COM_TOOLS_USERNAME_SELECT'); ?></option> <?php foreach ($this->usernames as $record) { $html = ' <option value="' . $record->viewuser . '"'; if ($this->filters['username'] == $record->viewuser) { $html .= ' selected="selected"'; } $html .= '>' . $this->escape(stripslashes($record->viewuser)) . '</option>' . "\n"; echo $html; } ?> </select> <a class="refresh button" href="<?php echo Route::url('index.php?option=' . $this->option . '&controller=' . $this->controller . '&username=&appname=&exechost=&start=0'); ?>"> <span><?php echo Lang::txt('JSEARCH_FILTER_CLEAR'); ?></span> </a> </fieldset> <table class="adminlist"> <thead> <tr> <th scope="col"><input type="checkbox" name="toggle" value="" onclick="Joomla.checkAll(this);" /></th> <th scope="col"><?php echo Html::grid('sort', 'COM_TOOLS_COL_SESSION', 'sessnum', @$this->filters['sort_Dir'], @$this->filters['sort']); ?></th> <th scope="col" class="priority-2"><?php echo Html::grid('sort', 'COM_TOOLS_COL_OWNER', 'username', @$this->filters['sort_Dir'], @$this->filters['sort']); ?></th> <th scope="col" class="priority-2"><?php echo Html::grid('sort', 'COM_TOOLS_COL_VIEWER', 'viewuser', @$this->filters['sort_Dir'], @$this->filters['sort']); ?></th> <th scope="col" class="priority-4"><?php echo Html::grid('sort', 'COM_TOOLS_COL_STARTED', 'start', @$this->filters['sort_Dir'], @$this->filters['sort']); ?></th> <th scope="col" class="priority-3"><?php echo Html::grid('sort', 'COM_TOOLS_COL_LAST_ACCESSED', 'accesstime', @$this->filters['sort_Dir'], @$this->filters['sort']); ?></th> <th scope="col" class="priority-3"><?php echo Html::grid('sort', 'COM_TOOLS_COL_TOOL', 'appname', @$this->filters['sort_Dir'], @$this->filters['sort']); ?></th> <th scope="col" class="priority-4"><?php echo Html::grid('sort', 'COM_TOOLS_COL_EXEC_HOST', 'exechost', @$this->filters['sort_Dir'], @$this->filters['sort']); ?></th> <th scope="col"><?php echo Lang::txt('COM_TOOLS_COL_STOP'); ?></th> </tr> </thead> <tfoot> <tr> <td colspan="9"> <?php // Initiate paging echo $this->pagination( $this->total, $this->filters['start'], $this->filters['limit'] ); ?> </td> </tr> </tfoot> <tbody> <?php if ($this->rows) { $i = 0; foreach ($this->rows as $row) { ?> <tr> <td> <input type="checkbox" name="id[]" id="cb<?php echo $i; ?>" value="<?php echo $row->sessnum; ?>" onclick="Joomla.isChecked(this.checked);" /> </td> <td> <span class="editlinktip hasTip" title="<?php echo $this->escape(stripslashes($row->sessname)); ?>::Host: <?php echo $row->exechost; ?>&lt;br /&gt;IP: <?php echo $row->remoteip; ?>"> <span><?php echo $this->escape($row->sessnum); ?></span> </span> </td> <td class="priority-2"> <a href="<?php echo Route::url('index.php?option=' . $this->option . '&controller=' . $this->controller . '&username=' . $row->username); ?>"> <span><?php echo $this->escape($row->username); ?></span> </a> </td> <td class="priority-2"> <span><?php echo $this->escape($row->viewuser); ?></span> </td> <td class="priority-4"> <time datetime="<?php echo $this->escape($row->start); ?>"> <?php echo $this->escape($row->start); ?> </time> </td> <td class="priority-3"> <time datetime="<?php echo $this->escape($row->accesstime); ?>"> <?php echo $this->escape($row->accesstime); ?> </time> </td> <td class="priority-3"> <a class="tool" href="<?php echo Route::url('index.php?option=' . $this->option . '&controller=' . $this->controller . '&appname=' . $row->appname); ?>"> <span><?php echo $this->escape($row->appname); ?></span> </a> </td> <td class="priority-4"> <a class="tool" href="<?php echo Route::url('index.php?option=' . $this->option . '&controller=' . $this->controller . '&exechost=' . $row->exechost); ?>"> <span><?php echo $this->escape($row->exechost); ?></span> </a> </td> <td> <a class="state trash" href="<?php echo Route::url('index.php?option=' . $this->option . '&controller=' . $this->controller . '&task=remove&id=' . $row->sessnum . '&' . Session::getFormToken() . '=1'); ?>" title="<?php echo Lang::txt('COM_TOOLS_TERMINATE'); ?>"> <span><?php echo Lang::txt('COM_TOOLS_TERMINATE'); ?></span> </a> </td> </tr> <?php $i++; } } ?> </tbody> </table> <input type="hidden" name="option" value="<?php echo $this->option; ?>" /> <input type="hidden" name="controller" value="<?php echo $this->controller; ?>" /> <input type="hidden" name="task" value="" autocomplete="off" /> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="filter_order" value="<?php echo $this->escape($this->filters['sort']); ?>" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $this->escape($this->filters['sort_Dir']); ?>" /> <?php echo Html::input('token'); ?> </form>
mulligaj/hubzero-cms
core/components/com_tools/admin/views/sessions/tmpl/display.php
PHP
gpl-2.0
8,450
//----------------------------------------------------------------------------- // File: ConfigurableElementColumns.h //----------------------------------------------------------------------------- // Project: Kactus2 // Author: Mikko Teuho // Date: 30.01.2015 // // Description: // Common declarations for editing configurable element values. //----------------------------------------------------------------------------- namespace ConfigurableElementsColumns { //----------------------------------------------------------------------------- // Constants defining which column represents what kind of information. //----------------------------------------------------------------------------- enum Columns { NAME, //!< Column for the name of the configurable element. VALUE, //!< Column for the configurable value. DEFAULT_VALUE, //!< Column for the original value of the parameter. CHOICE, //!< Column for the selected choice of the parameter. ARRAY_LEFT, //!< Column for the left side of the parameters array. ARRAY_RIGHT, //!< Column for the right side of the parameters array. TYPE, //!< Column for the type of the parameter. COLUMN_COUNT }; }
kactus2/kactus2dev
editors/common/ComponentInstanceEditor/ConfigurableElementsColumns.h
C
gpl-2.0
1,341
\featname{Stolen Breath [Elemental]} As the [Fiend] feat of the same name, except where noted below. \shortability{Prerequisites:}{(Air) Subtype or Drowning Grasp, Character level 3+}
vlad-malkav/Tome-Rules-with-Errata
current-source/phb/feats/elemental/stolen_breath.tex
TeX
gpl-2.0
186
#ifndef GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS #endif #include "MatrixStack.h" #include <glm/gtc/matrix_transform.hpp> namespace GL { MatrixStack::MatrixStack() { _stack.push(glm::mat4(1.0f)); } MatrixStack::~MatrixStack() { } void MatrixStack::loadID() { loadMatrix(glm::mat4(1.0f)); } void MatrixStack::loadMatrix(glm::mat4& matrix) { _stack.top() = matrix; } void MatrixStack::multiplyMatrix(glm::mat4& matrix) { _stack.top() *= matrix; } void MatrixStack::popMatrix() { _stack.pop(); } void MatrixStack::pushMatrix() { pushMatrix(_stack.top()); } void MatrixStack::pushMatrix(glm::mat4& matrix) { _stack.push(matrix); } void MatrixStack::rotate(float angle, float x, float y, float z) { rotate(angle, glm::vec3(x, y, z)); } void MatrixStack::rotate(float angle, glm::vec3& vector) { _stack.top() = glm::rotate(_stack.top(), angle, vector); } void MatrixStack::translate(float x, float y, float z) { translate(glm::vec3(x, y, z)); } void MatrixStack::translate(glm::vec3& vector) { _stack.top() = glm::translate(_stack.top(), vector); } void MatrixStack::scale(float x, float y, float z) { scale(glm::vec3(x, y, z)); } void MatrixStack::scale(glm::vec3& vector) { _stack.top() = glm::scale(_stack.top(), vector); } const glm::mat4& MatrixStack::getMatrix() const { return _stack.top(); } }
RippeR37/Hexanoid
src/Utils/GL+/MatrixStack.cpp
C++
gpl-2.0
1,555
/** ======================================================================== */ /** */ /** @copyright Copyright (c) 2010-2015, S2S s.r.l. */ /** @license http://www.gnu.org/licenses/gpl-2.0.html GNU Public License v.2 */ /** @version 6.0 */ /** This file is part of SdS - Sistema della Sicurezza . */ /** SdS - Sistema della Sicurezza is free software: you can redistribute it and/or modify */ /** it under the terms of the GNU General Public License as published by */ /** the Free Software Foundation, either version 3 of the License, or */ /** (at your option) any later version. */ /** SdS - Sistema della Sicurezza is distributed in the hope that it will be useful, */ /** but WITHOUT ANY WARRANTY; without even the implied warranty of */ /** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /** GNU General Public License for more details. */ /** You should have received a copy of the GNU General Public License */ /** along with SdS - Sistema della Sicurezza . If not, see <http://www.gnu.org/licenses/gpl-2.0.html> GNU Public License v.2 */ /** */ /** ======================================================================== */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.apconsulting.luna.ejb.Dipendente; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collection; import javax.ejb.CreateException; import javax.ejb.EJBException; import javax.ejb.FinderException; import javax.ejb.NoSuchEntityException; import s2s.ejb.pseudoejb.BMPConnection; import s2s.ejb.pseudoejb.BMPEntityBean; import s2s.ejb.pseudoejb.EntityContextWrapper; import s2s.utils.text.StringManager; /** * * @author Dario */ public class DipendenteBean extends BMPEntityBean implements IDipendenteHome, IDipendente { // Zdes opredeliajutsia peremennie EJB obiekta //<comment description="Member Variables"> long COD_DPD; //0 long COD_AZL; //1 long COD_DTE; //2 - Nullable long COD_FUZ_AZL; //3 String STA_DPD; //4 String MTR_DPD; //5 String COG_DPD; //6 String NOM_DPD; //7 String COD_FIS_DPD; //8 - Nullable long COD_STA; //9 - Nullable String LUO_NAS_DPD; //10 - Nullable java.sql.Date DAT_NAS_DPD; //11 String IDZ_DPD; //12 - Nullable String NUM_CIC_DPD; //13 - Nullable String CAP_DPD; //14 - Nullable String CIT_DPD; //15 - Nullable String PRV_DPD; //16 - Nullable String IDZ_PSA_ELT_DPD; //17 - Nullable String RAP_LAV_AZL; //18 java.sql.Date DAT_ASS_DPD; //19 - Nullable String LIV_DPD; //20 - Nullable java.sql.Date DAT_CES_DPD; //21 - Nullable String NOT_DPD; String SEX_DPD; /* String File; //19 - Computing from COD_AZL String FileDimensione; //20 - Computing from COD_AZL java.sql.Date FileUltModif; //21 - Computing from COD_AZL String NOM_AZL; //22 - Computing from COD_AZL String NOM_DTE; //23 - Computing from COD_DTE String NOM_FUZ_AZL; //24 - Computing from COD_FUZ_AZL */ //</comment> ////////////////////// CONSTRUCTOR/////////////////// private static DipendenteBean ys = null; private DipendenteBean() { } public static DipendenteBean getInstance() { if (ys == null) { ys = new DipendenteBean(); } return ys; } ////////////////////////////ATTENTION!!////////////////////////////////////////////////////////////////////////////// //<comment description="Zdes opredeliayutsia metody EJB objecta kotorie budut rabotat v JSP Containere (Zaglushki)"/> // (Home Intrface) create() public IDipendente create(long COD_AZL, long COD_FUZ_AZL, String STA_DPD, String MTR_DPD, String COG_DPD, String NOM_DPD, java.sql.Date DAT_NAS_DPD, String RAP_LAV_AZL) throws CreateException { DipendenteBean bean = new DipendenteBean(); try { Object primaryKey = bean.ejbCreate(COD_AZL, COD_FUZ_AZL, STA_DPD, MTR_DPD, COG_DPD, NOM_DPD, DAT_NAS_DPD, RAP_LAV_AZL); bean.setEntityContext(new EntityContextWrapper(primaryKey)); bean.ejbPostCreate(COD_AZL, COD_FUZ_AZL, STA_DPD, MTR_DPD, COG_DPD, NOM_DPD, DAT_NAS_DPD, RAP_LAV_AZL); return bean; } catch (Exception ex) { ex.printStackTrace(System.err); throw new javax.ejb.CreateException(ex.getMessage()); } } // (Home Intrface) remove() @Override public void remove(Object primaryKey) { DipendenteBean iDipendenteBean = new DipendenteBean(); try { Object obj = iDipendenteBean.ejbFindByPrimaryKey((Long) primaryKey); iDipendenteBean.setEntityContext(new EntityContextWrapper(obj)); iDipendenteBean.ejbActivate(); iDipendenteBean.ejbLoad(); iDipendenteBean.ejbRemove(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } } public void enable(Object primaryKey) { DipendenteBean iDipendenteBean = new DipendenteBean(); try { Object obj = iDipendenteBean.ejbFindByPrimaryKey((Long) primaryKey); iDipendenteBean.setEntityContext(new EntityContextWrapper(obj)); iDipendenteBean.ejbActivate(); iDipendenteBean.ejbLoad(); iDipendenteBean.ejbEnable(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } } // (Home Intrface) findByPrimaryKey() public IDipendente findByPrimaryKey(Long primaryKey) throws FinderException { DipendenteBean bean = new DipendenteBean(); try { bean.setEntityContext(new EntityContextWrapper(primaryKey)); bean.ejbActivate(); bean.ejbLoad(); return bean; } catch (Exception ex) { ex.printStackTrace(System.err); throw new javax.ejb.FinderException(ex.getMessage()); } } // (Home Intrface) findAll() public Collection findAll() throws FinderException { try { return this.ejbFindAll(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new javax.ejb.FinderException(ex.getMessage()); } } // (Home Intrface) VIEWS public Collection getDipendentiByAZLID_View(long AZL_ID) { return (new DipendenteBean()).ejbGetDipendentiByAZLID_View(AZL_ID); } public Collection getDipendentiByAZLID_View_CAN(long AZL_ID,long COD_DTE) { return (new DipendenteBean()).ejbGetDipendentiByAZLID_View_CAN(AZL_ID,COD_DTE); } public Collection getDipendentiByAZLID_RLS_View(long AZL_ID) { return (new DipendenteBean()).ejbGetDipendentiByAZLID_RLS_View(AZL_ID); } public Collection getDipendentiBySOP_View(long COD_SOP) { return (new DipendenteBean()).ejbgetDipendentiBySOP_View(COD_SOP); } public Collection getDipendentiEstBySOP_View(long COD_SOP) { return (new DipendenteBean()).ejbgetDipendentiEstBySOP_View(COD_SOP); } public Collection getDipendenti_Names_View(long AZL_ID) { return (new DipendenteBean()).ejbGetDipendenti_Names_View(AZL_ID); } //<report> public DipendenteFunzioneView getDipendenteFunzioneView(long lCOD_DPD) { return (new DipendenteBean()).ejbGetDipendenteFunzioneView(lCOD_DPD); } //--- Podmasteriev------------- public Collection getScadenzario_DPI_View(long lCOD_AZL, long lNOM_COR, String lNOM_DCT, java.sql.Date dDAT_PIF_EGZ_COR_DAL, java.sql.Date dDAT_PIF_EGZ_COR_AL, String strSTA_INT, java.sql.Date dEFF_DAT_DAL, java.sql.Date dEFF_DAT_AL, String strRAGGRUPPATI, String strTYPE, String strFROM) { return (new DipendenteBean()).ejbGetScadenzario_DPI_View(lCOD_AZL, lNOM_COR, lNOM_DCT, dDAT_PIF_EGZ_COR_DAL, dDAT_PIF_EGZ_COR_AL, strSTA_INT, dEFF_DAT_DAL, dEFF_DAT_AL, strRAGGRUPPATI, strTYPE, strFROM); } public Collection getDipendenti_SCH_DPI_View() { return (new DipendenteBean()).ejbGetDipendenti_SCH_DPI_View(); } public Collection getDipendenti_Search_View(long AZL_ID) { return (new DipendenteBean()).ejbGetDipendenti_Search_View(AZL_ID); } public Collection getDipendentePercorsiFormativi_View(long COD_DPD) { return (new DipendenteBean()).ejbGetDipendentePercorsiFormativi_View(COD_DPD); } public Collection getDipendente_CORCOM_View() { return (new DipendenteBean()).ejbGetDipendente_CORCOM_View(); } public Collection getDipendenti_Lavoratori_View(long lCOD_DPD) { return (new DipendenteBean()).ejbGetDipendenti_Lavoratori_View(lCOD_DPD, null, null); } public Collection getDipendenti_Lavoratori_View(long lCOD_DPD, String columnOrdered, String orderType) { return (new DipendenteBean()).ejbGetDipendenti_Lavoratori_View(lCOD_DPD, columnOrdered, orderType); } public Collection getDipendenti_FOD_DBT_View(long lAZL_ID, String newNOM_MAN, boolean orderDesc) { return (new DipendenteBean()).ejbGetDipendenti_FOD_DBT_View(lAZL_ID, newNOM_MAN, orderDesc); } public Collection getDipendenteByDitta(long lCOD_AZL, long lCOD_DTE) { return (new DipendenteBean()).ejbGetDipendenteByDitta(lCOD_AZL, lCOD_DTE); } public Collection findUOListToSendMail(long lCOD_AZL, long lCOD_MAN) { return (new DipendenteBean()).ejbFindUOListToSendMail(lCOD_AZL, lCOD_MAN); } public Collection findDipendentiAttivitaLavorativeByCOD_UNI_ORG(long lCOD_AZL, long lCOD_MAN, long lCOD_UNI_ORG) { return (new DipendenteBean()).ejbFindDipendentiAttivitaLavorativeByCOD_UNI_ORG(lCOD_AZL, lCOD_MAN, lCOD_UNI_ORG); } public Collection findDipendenteAttivitaLavorativaByCOD_UNI_ORG(long lCOD_AZL, long lCOD_DPD, long lCOD_MAN, long lCOD_UNI_ORG,java.sql.Date lDAT_INZ,boolean activeATT_LAV) { return (new DipendenteBean()).ejbFindDipendenteAttivitaLavorativaByCOD_UNI_ORG(lCOD_AZL, lCOD_DPD, lCOD_MAN, lCOD_UNI_ORG,lDAT_INZ,activeATT_LAV); } public Collection getDipendenteByMTR(long lCOD_AZL, String strMTR_DIP) { return (new DipendenteBean()).ejbGetDipendenteByMTR(lCOD_AZL, strMTR_DIP); } /*public Collection getDipendenteBySEX(long lCOD_AZL, String strSEX_DPD) { return (new DipendenteBean()).ejbGetDipendenteBySEX(lCOD_AZL, strSEX_DPD); }*/ /////////////////////ATTENTION!!//////////////////////////////////////////////////////////////////////////// //<comment description="Zdes opredeliayutsia metody home intefeisa kotorie budut rabotat v EJB Containere"/> //</IDipendenteHome-implementation> public Collection ejbFindUOListToSendMail(long lCOD_AZL, long lCOD_MAN) { BMPConnection bmp = getConnection(); java.util.ArrayList al = new java.util.ArrayList(); try { PreparedStatement ps = bmp.prepareStatement("select distinct(cod_uni_org) from man_dpd_uni_org_tab where (dat_fie is null or dat_fie >= current_date) and cod_azl = ? and cod_man = ?"); ps.setLong(1, lCOD_AZL); ps.setLong(2, lCOD_MAN); ps.executeQuery(); ResultSet rs = ps.executeQuery(); while (rs.next()) { Dipendenti_Lavoratori_View obj = new Dipendenti_Lavoratori_View(); obj.COD_UNI_ORG = rs.getLong(1); al.add(obj); } } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } return al; } public Collection ejbFindDipendentiAttivitaLavorativeByCOD_UNI_ORG(long lCOD_AZL, long lCOD_MAN, long lCOD_UNI_ORG) { BMPConnection bmp = getConnection(); java.util.ArrayList al = new java.util.ArrayList(); try { PreparedStatement ps = bmp.prepareStatement( "select " + " a.cod_uni_org, " + " a.cod_dpd, " + " b.nom_uni_org, " + " c.mtr_dpd, " + " c.nom_dpd, " + " c.cog_dpd " + "from " + " man_dpd_uni_org_tab a, " + " ana_uni_org_tab b, " + " view_ana_dpd_tab c " + "where " + " a.cod_uni_org = b.cod_uni_org " + " and a.cod_dpd = c.cod_dpd " + " and (dat_fie is null or dat_fie >= current_date) " + " and a.cod_azl = ? " + " and cod_man = ? " + " and a.cod_uni_org = ?"); ps.setLong(1, lCOD_AZL); ps.setLong(2, lCOD_MAN); ps.setLong(3, lCOD_UNI_ORG); ps.executeQuery(); ResultSet rs = ps.executeQuery(); while (rs.next()) { Dipendenti_Lavoratori_View obj = new Dipendenti_Lavoratori_View(); obj.COD_UNI_ORG = rs.getLong(1); obj.COD_DPD = rs.getLong(2); obj.NOM_UNI_ORG = rs.getString(3); obj.MTR_DPD = rs.getString(4); obj.NOM_DPD = rs.getString(5); obj.COG_DPD = rs.getString(6); al.add(obj); } } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } return al; } public Collection ejbFindDipendenteAttivitaLavorativaByCOD_UNI_ORG(long lCOD_AZL, long lCOD_DPD, long lCOD_MAN, long lCOD_UNI_ORG,java.sql.Date lDAT_INZ,boolean activeATT_LAV) { BMPConnection bmp = getConnection(); java.util.ArrayList al = new java.util.ArrayList(); try { String sql= "select " + "a.cod_uni_org, " + "a.cod_dpd, " + "b.nom_uni_org, " + "c.nom_dpd, " + "c.cog_dpd, " + "a.cod_tpl_con " + "from " + "man_dpd_uni_org_tab a, " + "ana_uni_org_tab b, " + "view_ana_dpd_tab c " + "where " + "a.cod_uni_org = b.cod_uni_org " + "and a.cod_dpd = c.cod_dpd " + (activeATT_LAV==true?"and (dat_fie is null or dat_fie >= current_date) ":"") + "and a.cod_azl = ? " + "and a.cod_dpd = ? " + "and cod_man = ? " + "and a.cod_uni_org = ?"; if(lDAT_INZ!=null) sql+=" and a.dat_inz=? "; PreparedStatement ps = bmp.prepareStatement(sql); ps.setLong(1, lCOD_AZL); ps.setLong(2, lCOD_DPD); ps.setLong(3, lCOD_MAN); ps.setLong(4, lCOD_UNI_ORG); if(lDAT_INZ!=null) ps.setDate(5, lDAT_INZ); ps.executeQuery(); ResultSet rs = ps.executeQuery(); while (rs.next()) { Dipendenti_Lavoratori_View obj = new Dipendenti_Lavoratori_View(); obj.COD_UNI_ORG = rs.getLong(1); obj.COD_DPD = rs.getLong(2); obj.NOM_UNI_ORG = rs.getString(3); obj.NOM_DPD = rs.getString(4); obj.COG_DPD = rs.getString(5); obj.COD_TPL_CON = rs.getLong(6); al.add(obj); } } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } return al; } public Long ejbCreate(long COD_AZL, long COD_FUZ_AZL, String STA_DPD, String MTR_DPD, String COG_DPD, String NOM_DPD, java.sql.Date DAT_NAS_DPD, String RAP_LAV_AZL) { this.COD_DPD = NEW_ID(); // unic ID this.COD_AZL = COD_AZL; this.COD_FUZ_AZL = COD_FUZ_AZL; this.STA_DPD = STA_DPD; this.MTR_DPD = MTR_DPD; this.COG_DPD = COG_DPD; this.NOM_DPD = NOM_DPD; this.DAT_NAS_DPD = DAT_NAS_DPD; this.RAP_LAV_AZL = RAP_LAV_AZL; this.unsetModified(); BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("INSERT INTO ana_dpd_tab (cod_dpd,cod_azl, cod_fuz_azl, sta_dpd, mtr_dpd, cog_dpd, nom_dpd, dat_nas_dpd, rap_lav_azl) VALUES(?,?,?,?,?,?,?,?,?)"); ps.setLong(1, COD_DPD); ps.setLong(2, COD_AZL); ps.setLong(3, COD_FUZ_AZL); ps.setString(4, STA_DPD); ps.setString(5, MTR_DPD); ps.setString(6, COG_DPD); ps.setString(7, NOM_DPD); ps.setDate(8, DAT_NAS_DPD); ps.setString(9, RAP_LAV_AZL); ps.executeUpdate(); return new Long(COD_DPD); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //------------------------------------------------------- public void ejbPostCreate(long COD_AZL, long COD_FUZ_AZL, String STA_DPD, String MTR_DPD, String COG_DPD, String NOM_DPD, java.sql.Date DAT_NAS_DPD, String RAP_LAV_AZL) { } //-------------------------------------------------- public Collection ejbFindAll() { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT cod_dpd FROM view_ana_dpd_tab"); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { al.add(new Long(rs.getLong(1))); } return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //----------------------------------------------------------- public Long ejbFindByPrimaryKey(Long primaryKey) { return primaryKey; } //---------------------------------------------------------- public void ejbActivate() { this.COD_DPD = ((Long) this.getEntityKey()).longValue(); } //---------------------------------------------------------- public void ejbPassivate() { this.COD_DPD = -1; } //---------------------------------------------------------- public void ejbLoad() { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT * FROM ana_dpd_tab WHERE cod_dpd=?"); ps.setLong(1, COD_DPD); ResultSet rs = ps.executeQuery(); if (rs.next()) { this.COD_DPD = rs.getLong("COD_DPD"); this.COD_AZL = rs.getLong("COD_AZL"); this.COD_DTE = rs.getLong("COD_DTE"); this.COD_FUZ_AZL = rs.getLong("COD_FUZ_AZL"); this.STA_DPD = rs.getString("STA_DPD"); this.MTR_DPD = rs.getString("MTR_DPD"); this.COG_DPD = rs.getString("COG_DPD"); this.NOM_DPD = rs.getString("NOM_DPD"); this.COD_FIS_DPD = rs.getString("COD_FIS_DPD"); this.COD_STA = rs.getLong("COD_STA"); this.LUO_NAS_DPD = rs.getString("LUO_NAS_DPD"); this.DAT_NAS_DPD = rs.getDate("DAT_NAS_DPD"); this.IDZ_DPD = rs.getString("IDZ_DPD"); this.NUM_CIC_DPD = rs.getString("NUM_CIC_DPD"); this.CAP_DPD = rs.getString("CAP_DPD"); this.CIT_DPD = rs.getString("CIT_DPD"); this.PRV_DPD = rs.getString("PRV_DPD"); this.IDZ_PSA_ELT_DPD = rs.getString("IDZ_PSA_ELT_DPD"); this.RAP_LAV_AZL = rs.getString("RAP_LAV_AZL"); this.DAT_ASS_DPD = rs.getDate("DAT_ASS_DPD"); this.LIV_DPD = rs.getString("LIV_DPD"); this.DAT_CES_DPD = rs.getDate("DAT_CES_DPD"); this.NOT_DPD = rs.getString("NOT_DPD"); this.SEX_DPD = rs.getString("SEX_DPD"); } else { throw new NoSuchEntityException("Dipendente con ID= non è trovata"); } } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //---------------------------------------------------------- public void ejbRemove() { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("DELETE FROM ana_dpd_tab WHERE cod_dpd=?"); ps.setLong(1, COD_DPD); if (ps.executeUpdate() == 0) { throw new NoSuchEntityException("Dipendente con ID=" + COD_DPD + " non è trovata"); } } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //---------------------------------------------------------- public void ejbEnable() { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("UPDATE ana_dpd_tab SET DAT_CES_DPD = NULL WHERE COD_DPD=?"); ps.setLong(1, COD_DPD); if (ps.executeUpdate() == 0) { throw new NoSuchEntityException("Dipendente con ID=" + COD_DPD + " non è stato trovato"); } } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //---------------------------------------------------------- public void ejbStore() { if (!isModified()) { return; } BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement( "UPDATE " + "ana_dpd_tab " + "SET " + "cod_azl=?, " + "cod_dte=?, " + "cod_fuz_azl=?, " + "sta_dpd=?, " + "mtr_dpd=?, " + "cog_dpd=?, " + "nom_dpd=?, " + "cod_fis_dpd=?, " + "cod_sta=?, " + "luo_nas_dpd=?, " + "dat_nas_dpd=?, " + "idz_dpd=?, " + "num_cic_dpd=?, " + "cap_dpd=?, " + "cit_dpd=?, " + "prv_dpd=?, " + "idz_psa_elt_dpd=?, " + "rap_lav_azl=?, " + "dat_ass_dpd=?, " + "liv_dpd=?, " + "dat_ces_dpd=?, " + "not_dpd=?, " + "sex_dpd=? " + "WHERE " + "cod_dpd=?"); ps.setLong(1, COD_AZL); if (COD_DTE == 0) { ps.setNull(2, java.sql.Types.BIGINT); } else { ps.setLong(2, COD_DTE); } ps.setLong(3, COD_FUZ_AZL); ps.setString(4, STA_DPD); ps.setString(5, MTR_DPD); ps.setString(6, COG_DPD); ps.setString(7, NOM_DPD); if ("".equals(COD_FIS_DPD)) { ps.setNull(8, java.sql.Types.BIGINT); } else { ps.setString(8, COD_FIS_DPD); } if (COD_STA == 0) { ps.setNull(9, java.sql.Types.BIGINT); } else { ps.setLong(9, COD_STA); } ps.setString(10, LUO_NAS_DPD); ps.setDate(11, DAT_NAS_DPD); ps.setString(12, IDZ_DPD); ps.setString(13, NUM_CIC_DPD); ps.setString(14, CAP_DPD); ps.setString(15, CIT_DPD); ps.setString(16, PRV_DPD); ps.setString(17, IDZ_PSA_ELT_DPD); ps.setString(18, RAP_LAV_AZL); ps.setDate(19, DAT_ASS_DPD); ps.setString(20, LIV_DPD); ps.setDate(21, DAT_CES_DPD); ps.setString(22, NOT_DPD); ps.setString(23, SEX_DPD); ps.setLong(24, COD_DPD); if (ps.executeUpdate() == 0) { throw new NoSuchEntityException("Dipendente with ID= not found"); } } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //------------------------------------------------------------- /////////////////////////////////ATTENTION!!////////////////////////////// //<comment description="Zdes opredeliayutsia metody (remote) interfeisa"/> //<comment description="setter/getters"> public long getCOD_DPD() { return COD_DPD; } // COD_AZL public void setCOD_AZL(long newCOD_AZL) { if (COD_AZL == newCOD_AZL) { return; } COD_AZL = newCOD_AZL; setModified(); } public long getCOD_AZL() { return COD_AZL; } // COD_DTE public void setCOD_DTE(long newCOD_DTE) { if (COD_DTE == newCOD_DTE) { return; } COD_DTE = newCOD_DTE; setModified(); } public long getCOD_DTE() { return COD_DTE; } // COD_FUZ_AZL public void setCOD_FUZ_AZL(long newCOD_FUZ_AZL) { if (COD_FUZ_AZL == newCOD_FUZ_AZL) { return; } COD_FUZ_AZL = newCOD_FUZ_AZL; setModified(); } public long getCOD_FUZ_AZL() { return COD_FUZ_AZL; } // STA_DPD public void setSTA_DPD(String newSTA_DPD) { if (STA_DPD != null) { if (STA_DPD.equals(newSTA_DPD)) { return; } } STA_DPD = newSTA_DPD; setModified(); } public String getSTA_DPD() { return (STA_DPD != null) ? STA_DPD : ""; } // MTR_DPD public void setMTR_DPD(String newMTR_DPD) { if (MTR_DPD != null) { if (MTR_DPD.equals(newMTR_DPD)) { return; } } MTR_DPD = newMTR_DPD; setModified(); } public String getMTR_DPD() { return (MTR_DPD != null) ? MTR_DPD : ""; } // COG_DPD public void setCOG_DPD(String newCOG_DPD) { if (COG_DPD != null) { if (COG_DPD.equals(newCOG_DPD)) { return; } } COG_DPD = newCOG_DPD; setModified(); } public String getCOG_DPD() { return (COG_DPD != null) ? COG_DPD : ""; } // NOM_DPD public void setNOM_DPD(String newNOM_DPD) { if (NOM_DPD != null) { if (NOM_DPD.equals(newNOM_DPD)) { return; } } NOM_DPD = newNOM_DPD; setModified(); } public String getNOM_DPD() { return (NOM_DPD != null) ? NOM_DPD : ""; } // COD_FIS_DPD public void setCOD_FIS_DPD(String newCOD_FIS_DPD) { if (COD_FIS_DPD != null) { if (COD_FIS_DPD.equals(newCOD_FIS_DPD)) { return; } } COD_FIS_DPD = newCOD_FIS_DPD; setModified(); } public String getCOD_FIS_DPD() { return (COD_FIS_DPD != null) ? COD_FIS_DPD : ""; } // SEX_DPD public String getSEX_DPD() { if (SEX_DPD == null) { return SEX_DPD = ""; } return SEX_DPD; } // SEX_DPD public void setSEX_DPD(String newSEX_DPD) { if (SEX_DPD != null) { if (SEX_DPD.equals(newSEX_DPD)) { return; } /*else{ SEX_DPD =""; }*/ } SEX_DPD = newSEX_DPD; setModified(); } // COD_STA public void setCOD_STA(long newCOD_STA) { if (COD_STA == newCOD_STA) { return; } COD_STA = newCOD_STA; setModified(); } public long getCOD_STA() { return COD_STA; } public String getsCOD_STA() { return new Long(COD_STA).toString(); } // LUO_NAS_DPD public void setLUO_NAS_DPD(String newLUO_NAS_DPD) { if (LUO_NAS_DPD != null) { if (LUO_NAS_DPD.equals(newLUO_NAS_DPD)) { return; } } LUO_NAS_DPD = newLUO_NAS_DPD; setModified(); } public String getLUO_NAS_DPD() { return (LUO_NAS_DPD != null) ? LUO_NAS_DPD : ""; } // DAT_NAS_DPD public void setDAT_NAS_DPD(java.sql.Date newDAT_NAS_DPD) { if (DAT_NAS_DPD != null) { if (DAT_NAS_DPD.equals(newDAT_NAS_DPD)) { return; } } DAT_NAS_DPD = newDAT_NAS_DPD; setModified(); } public java.sql.Date getDAT_NAS_DPD() { return DAT_NAS_DPD; } public String getsDAT_NAS_DPD() { return (DAT_NAS_DPD != null) ? DAT_NAS_DPD.toString() : ""; } // IDZ_DPD public void setIDZ_DPD(String newIDZ_DPD) { if (IDZ_DPD != null) { if (IDZ_DPD.equals(newIDZ_DPD)) { return; } } IDZ_DPD = newIDZ_DPD; setModified(); } public String getIDZ_DPD() { return (IDZ_DPD != null) ? IDZ_DPD : ""; } // NUM_CIC_DPD public void setNUM_CIC_DPD(String newNUM_CIC_DPD) { if (NUM_CIC_DPD != null) { if (NUM_CIC_DPD.equals(newNUM_CIC_DPD)) { return; } } NUM_CIC_DPD = newNUM_CIC_DPD; setModified(); } public String getNUM_CIC_DPD() { return (NUM_CIC_DPD != null) ? NUM_CIC_DPD : ""; } // CAP_DPD public void setCAP_DPD(String newCAP_DPD) { if (CAP_DPD != null) { if (CAP_DPD.equals(newCAP_DPD)) { return; } } CAP_DPD = newCAP_DPD; setModified(); } public String getCAP_DPD() { return (CAP_DPD != null) ? CAP_DPD : ""; } // CIT_DPD public void setCIT_DPD(String newCIT_DPD) { if (CIT_DPD != null) { if (CIT_DPD.equals(newCIT_DPD)) { return; } } CIT_DPD = newCIT_DPD; setModified(); } public String getCIT_DPD() { return (CIT_DPD != null) ? CIT_DPD : ""; } // PRV_DPD public void setPRV_DPD(String newPRV_DPD) { if (PRV_DPD != null) { if (PRV_DPD.equals(newPRV_DPD)) { return; } } PRV_DPD = newPRV_DPD; setModified(); } public String getPRV_DPD() { return (PRV_DPD != null) ? PRV_DPD : ""; } // IDZ_PSA_ELT_DPD public void setIDZ_PSA_ELT_DPD(String newIDZ_PSA_ELT_DPD) { if (IDZ_PSA_ELT_DPD != null) { if (IDZ_PSA_ELT_DPD.equals(newIDZ_PSA_ELT_DPD)) { return; } } IDZ_PSA_ELT_DPD = newIDZ_PSA_ELT_DPD; setModified(); } public String getIDZ_PSA_ELT_DPD() { return (IDZ_PSA_ELT_DPD != null) ? IDZ_PSA_ELT_DPD : ""; } // RAP_LAV_AZL public void setRAP_LAV_AZL(String newRAP_LAV_AZL) { if (RAP_LAV_AZL != null) { if (RAP_LAV_AZL.equals(newRAP_LAV_AZL)) { return; } } RAP_LAV_AZL = newRAP_LAV_AZL; setModified(); } public String getRAP_LAV_AZL() { return (RAP_LAV_AZL != null) ? RAP_LAV_AZL : ""; } // DAT_ASS_DPD public void setDAT_ASS_DPD(java.sql.Date newDAT_ASS_DPD) { if (DAT_ASS_DPD != null) { if (DAT_ASS_DPD.equals(newDAT_ASS_DPD)) { return; } } DAT_ASS_DPD = newDAT_ASS_DPD; setModified(); } public java.sql.Date getDAT_ASS_DPD() { return DAT_ASS_DPD; } // LIV_DPD public void setLIV_DPD(String newLIV_DPD) { if (LIV_DPD != null) { if (LIV_DPD.equals(newLIV_DPD)) { return; } } LIV_DPD = newLIV_DPD; setModified(); } public String getLIV_DPD() { return (LIV_DPD != null) ? LIV_DPD : ""; } // DAT_CES_DPD public void setDAT_CES_DPD(java.sql.Date newDAT_CES_DPD) { if (DAT_CES_DPD != null) { if (DAT_CES_DPD.equals(newDAT_CES_DPD)) { return; } } DAT_CES_DPD = newDAT_CES_DPD; setModified(); } public java.sql.Date getDAT_CES_DPD() { return DAT_CES_DPD; } // NOT_DPD public void setNOT_DPD(String newNOT_DPD) { if (NOT_DPD != null) { if (NOT_DPD.equals(newNOT_DPD)) { return; } } NOT_DPD = newNOT_DPD; setModified(); } public String getNOT_DPD() { return (NOT_DPD != null) ? NOT_DPD : ""; } // NOM_AZL public String getNOM_AZL() { String NOM_AZL = ""; BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT rag_scl_azl FROM ana_azl_tab WHERE cod_azl=?"); ps.setLong(1, COD_AZL); ResultSet rs = ps.executeQuery(); if (rs.next()) { NOM_AZL = rs.getString(1); } bmp.close(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } return NOM_AZL; } // NOM_DTE public String getNOM_DTE() { String NOM_DTE = ""; BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT rag_scl_dte FROM ana_dte_tab WHERE cod_dte=?"); ps.setLong(1, COD_DTE); ResultSet rs = ps.executeQuery(); if (rs.next()) { NOM_DTE = rs.getString(1); } bmp.close(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } return NOM_DTE; } // NOM_FUZ_AZL public String getNOM_FUZ_AZL() { String NOM_FUZ_AZL = ""; BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT nom_fuz_azl FROM ana_fuz_azl_tab WHERE cod_fuz_azl=?"); ps.setLong(1, COD_FUZ_AZL); ResultSet rs = ps.executeQuery(); if (rs.next()) { NOM_FUZ_AZL = rs.getString(1); } bmp.close(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } return NOM_FUZ_AZL; } public java.sql.Date getDAT_INZ(long MAN_ID, long UNI_ORG_ID,java.sql.Date nwDAT_INZ) { java.sql.Date DAT_INZ = null; BMPConnection bmp = getConnection(); try { String sql="SELECT dat_inz FROM man_dpd_uni_org_tab " + "WHERE cod_azl=? AND cod_dpd=? AND cod_man=? " + "AND cod_uni_org=?"; if(nwDAT_INZ!=null) sql+=" AND dat_inz=?"; PreparedStatement ps = bmp.prepareStatement(sql); ps.setLong(1, COD_AZL); ps.setLong(2, COD_DPD); ps.setLong(3, MAN_ID); ps.setLong(4, UNI_ORG_ID); if(nwDAT_INZ!=null) ps.setDate(5, nwDAT_INZ); ResultSet rs = ps.executeQuery(); if (rs.next()) { DAT_INZ = rs.getDate(1); } bmp.close(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } return DAT_INZ; } public java.sql.Date getDAT_FIE(long MAN_ID, long UNI_ORG_ID,java.sql.Date nwDAT_INZ) { java.sql.Date DAT_FIE = null; BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT dat_fie FROM man_dpd_uni_org_tab " + "WHERE cod_azl=? AND cod_dpd=? AND cod_man=? " + "AND cod_uni_org=? AND dat_inz=?"); ps.setLong(1, COD_AZL); ps.setLong(2, COD_DPD); ps.setLong(3, MAN_ID); ps.setLong(4, UNI_ORG_ID); ps.setDate(5, nwDAT_INZ); ResultSet rs = ps.executeQuery(); if (rs.next()) { DAT_FIE = rs.getDate(1); } bmp.close(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } return DAT_FIE; } //</comment> ///////////ATTENTION!!////////////////////////////////////// //<comment description="Zdes opredeliayutsia metody-views"/> public Collection ejbGetDipendentiByAZLID_View(long AZL_ID) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT cod_dpd,nom_dpd,cog_dpd,idz_dpd, mtr_dpd FROM view_ana_dpd_tab WHERE cod_azl=? ORDER BY cog_dpd "); ps.setLong(1, AZL_ID); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { DipendentiByAZLID_View obj = new DipendentiByAZLID_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.IDZ_DPD = rs.getString(4); obj.MTR_DPD = rs.getString(5); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } public Collection ejbGetDipendentiByAZLID_View_CAN(long AZL_ID,long COD_DTE) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT cod_dpd,nom_dpd,cog_dpd,idz_dpd, mtr_dpd FROM view_ana_dpd_tab WHERE cod_azl=? AND cod_dte=? ORDER BY cog_dpd "); ps.setLong(1, AZL_ID); ps.setLong(2, COD_DTE); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { DipendentiByAZLID_View obj = new DipendentiByAZLID_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.IDZ_DPD = rs.getString(4); obj.MTR_DPD = rs.getString(5); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } // public Collection ejbgetDipendentiBySOP_View(long COD_SOP) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement( /* "select ana_dpd_tab.cod_dpd,nom_dpd,cog_dpd,nom_fuz_azl,idz_psa_elt_dpd,ana_dte_tab.rag_scl_dte "+ "from ana_sop_tab,sop_dpd_tab,ana_fuz_azl_tab,ana_dpd_tab "+ " left join ana_dte_tab on (ana_dte_tab.cod_dte=ana_dpd_tab.cod_dte) "+ "where ana_sop_tab.cod_sop=sop_dpd_tab.cod_sop and "+ "sop_dpd_tab.cod_dpd=ana_dpd_tab.cod_dpd and "+ "sop_dpd_tab.cod_azl=ana_dpd_tab.cod_azl and "+ "ana_dpd_tab.cod_fuz_azl=ana_fuz_azl_tab.cod_fuz_azl and "+ "ana_sop_tab.cod_sop = ? "); */ "select ana_dpd_tab.cod_dpd,nom_dpd,cog_dpd,nom_fuz_azl,idz_psa_elt_dpd "+ "from ana_sop_tab,sop_dpd_tab,ana_dpd_tab,ana_fuz_azl_tab "+ "where ana_sop_tab.cod_sop=sop_dpd_tab.cod_sop and "+ "sop_dpd_tab.cod_dpd=ana_dpd_tab.cod_dpd and "+ "sop_dpd_tab.cod_azl=ana_dpd_tab.cod_azl and "+ "ana_dpd_tab.cod_fuz_azl=ana_fuz_azl_tab.cod_fuz_azl and "+ "ana_sop_tab.cod_sop = ?"); ps.setLong(1, COD_SOP); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { DipendentiBySOP_View obj = new DipendentiBySOP_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.NOM_FUZ_AZL = rs.getString(4); obj.IDZ_PSA_ELT_DPD = rs.getString(5); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } public Collection ejbgetDipendentiEstBySOP_View(long COD_SOP) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement( /* "select ana_dpd_tab.cod_dpd,nom_dpd,cog_dpd,nom_fuz_azl,idz_psa_elt_dpd "+ " from ana_sop_tab,sop_dpd_imp_tab,ana_dpd_tab,ana_fuz_azl_tab "+ " where ana_sop_tab.cod_sop=sop_dpd_imp_tab.cod_sop and "+ " sop_dpd_imp_tab.cod_dpd=ana_dpd_tab.cod_dpd and "+ " sop_dpd_imp_tab.cod_azl=ana_dpd_tab.cod_azl and "+ " ana_dpd_tab.cod_fuz_azl=ana_fuz_azl_tab.cod_fuz_azl and "+ " ana_sop_tab.cod_sop = ?"); */ "select ana_dpd_tab.cod_dpd,nom_dpd,cog_dpd,nom_fuz_azl,idz_psa_elt_dpd,ana_dte_tab.rag_scl_dte "+ " from ana_sop_tab,sop_dpd_imp_tab,ana_dpd_tab,ana_fuz_azl_tab,ana_dte_tab "+ " where ana_sop_tab.cod_sop=sop_dpd_imp_tab.cod_sop and "+ " sop_dpd_imp_tab.cod_dpd=ana_dpd_tab.cod_dpd and "+ " sop_dpd_imp_tab.cod_azl=ana_dpd_tab.cod_azl and "+ " ana_dpd_tab.cod_fuz_azl=ana_fuz_azl_tab.cod_fuz_azl and "+ " ana_dte_tab.cod_dte=ana_dpd_tab.cod_dte and "+ " ana_sop_tab.cod_sop = ?"); ps.setLong(1, COD_SOP); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { DipendentiBySOP_View obj = new DipendentiBySOP_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.NOM_FUZ_AZL = rs.getString(4); obj.IDZ_PSA_ELT_DPD = rs.getString(5); obj.IMPRESA = rs.getString(6); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } public Collection ejbGetDipendentiByAZLID_RLS_View(long AZL_ID) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement( "SELECT cod_dpd,nom_dpd,cog_dpd,idz_dpd, mtr_dpd " + "FROM view_ana_dpd_tab WHERE cod_azl=? AND rap_lav_azl='S' ORDER BY cog_dpd "); ps.setLong(1, AZL_ID); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { DipendentiByAZLID_View obj = new DipendentiByAZLID_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.IDZ_DPD = rs.getString(4); obj.MTR_DPD = rs.getString(5); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public Collection ejbGetDipendenti_Names_View(long AZL_ID) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT cod_dpd, UPPER(nom_dpd), UPPER(cog_dpd), mtr_dpd FROM view_ana_dpd_tab WHERE cod_azl=? ORDER BY cog_dpd "); ps.setLong(1, AZL_ID); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Dipendenti_Names_View obj = new Dipendenti_Names_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.MTR_DPD = rs.getString(4); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } ///added by Podmasteriev Alexandr public Collection ejbGetDipendenti_SCH_DPI_View() { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement( "SELECT " + " cod_dpd, " + " nom_dpd, " + " cog_dpd, " + " mtr_dpd " + "FROM " + " view_ana_dpd_tab " + "ORDER BY " + " cog_dpd "); // ps.setLong(1, AZL_ID); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Dipendenti_Names_View obj = new Dipendenti_Names_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.MTR_DPD = rs.getString(4); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //=========================================================================== public Collection ejbGetDipendenti_Search_View(long AZL_ID) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement( "SELECT " + " a.cod_dpd, " + " UPPER(a.nom_dpd), " + " UPPER(a.cog_dpd), " + " a.mtr_dpd, " + " UPPER(b.nom_fuz_azl), " + " a.dat_nas_dpd, " + " a.luo_nas_dpd, " + " a.cit_dpd " + "FROM " + " view_ana_dpd_tab a, " + " ana_fuz_azl_tab b " + "WHERE " + " a.cod_fuz_azl=b.cod_fuz_azl " + " AND a.cod_azl=? " + "ORDER BY " + " cog_dpd " // "SELECT distinct a.cod_dpd, UPPER(a.nom_dpd) AS nom_dpd, UPPER(a.cog_dpd) AS cog_dpd, b.nom_fuz_azl, a.dat_nas_dpd, a.luo_nas_dpd, a.cit_dpd, a.dat_ces_dpd, d.rag_scl_dte FROM ana_dpd_tab a left outer join ana_dte_tab d ON a.cod_dte=d.cod_dte,ana_fuz_azl_tab b,ana_dpd_tab c WHERE a.cod_fuz_azl = b.cod_fuz_azl AND a.cod_azl = 1 ORDER BY cog_dpd" ); ps.setLong(1, AZL_ID); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Dipendenti_Search_View obj = new Dipendenti_Search_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.MTR_DPD = rs.getString(4); obj.NOM_FUZ_AZL = rs.getString(5); obj.DAT_NAS_DPD = rs.getDate(6); obj.LUO_NAS_DPD = rs.getString(7); obj.CIT_DPD = rs.getString(8); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //======================================================================= public Collection ejbGetDipendentePercorsiFormativi_View(long COD_DPD) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT dpd.cod_pcs_frm, ana.nom_pcs_frm, ana.des_pcs_frm FROM ana_pcs_frm_tab ana, pcs_frm_dpd_tab dpd WHERE dpd.cod_pcs_frm=ana.cod_pcs_frm and dpd.cod_dpd=? order by ana.nom_pcs_frm"); ps.setLong(1, COD_DPD); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { DipendentePercorsiFormativi_View obj = new DipendentePercorsiFormativi_View(); obj.COD_PCS_FRM = rs.getLong(1); obj.NOM_PCS_FRM = rs.getString(2); obj.DES_PCS_FRM = rs.getString(3); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //================================================================== public Collection ejbGetDipendente_CORCOM_View() { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement( "SELECT " + "cod_cor, " + "nom_cor, " + "des_cor " + "FROM " + "ana_cor_tab " + "ORDER BY " + "nom_cor"); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Dipendente_CORCOM_View obj = new Dipendente_CORCOM_View(); obj.COD_COR = rs.getLong(1); obj.NOM_COR = rs.getString(2); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //==================================================================== public Collection ejbGetDipendenti_Lavoratori_View(long lCOD_DPD_ID, String columnOrdered, String orderType) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement( "SELECT " + " mduo.cod_dpd, " + " mduo.cod_uni_org, " + " mduo.cod_man, " + " am.nom_man, " + " auo.nom_uni_org, " + " mduo.dat_inz, " + " mduo.dat_fie " + "FROM " + " man_dpd_uni_org_tab mduo, " + " ana_uni_org_tab auo, " + " ana_man_tab am " + "WHERE " + " mduo.cod_uni_org=auo.cod_uni_org " + " and am.cod_man=mduo.cod_man " + " and mduo.cod_dpd=? " + "order by " + (StringManager.isNotEmpty(columnOrdered) && StringManager.isNotEmpty(orderType) ?Integer.parseInt(columnOrdered)+3+" " + orderType + ", mduo.dat_inz" :"mduo.dat_inz")); ps.setLong(1, lCOD_DPD_ID); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Dipendenti_Lavoratori_View obj = new Dipendenti_Lavoratori_View(); obj.COD_DPD = rs.getLong(1); obj.COD_UNI_ORG = rs.getLong(2); obj.COD_MAN = rs.getLong(3); obj.NOM_MAN = rs.getString(4); obj.NOM_UNI_ORG = rs.getString(5); obj.DAT_INZ = rs.getDate(6); obj.DAT_FIE = rs.getDate(7); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //======================================================== //======================================================== public void addCOD_PCS_FRM(long newCOD_PCS_FRM) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("INSERT INTO pcs_frm_dpd_tab (cod_dpd,cod_pcs_frm,cod_azl) VALUES(?,?,?)"); ps.setLong(1, COD_DPD); ps.setLong(2, newCOD_PCS_FRM); ps.setLong(3, COD_AZL); ps.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //======================================================== public void removeCOD_PCS_FRM(long newCOD_PCS_FRM) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("DELETE FROM pcs_frm_dpd_tab WHERE cod_dpd=? AND cod_pcs_frm=? AND cod_azl=?"); ps.setLong(1, COD_DPD); ps.setLong(2, newCOD_PCS_FRM); ps.setLong(3, COD_AZL); if (ps.executeUpdate() == 0) { throw new NoSuchEntityException("Corsi con ID=" + newCOD_PCS_FRM + " non e' trovata"); } } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //=========================================================== public void addCOD_MAN(long newCOD_UNI_ORG, long newCOD_MAN, java.sql.Date newDAT_INZ, java.sql.Date newDAT_FIE, long lCOD_TPL_CON) { BMPConnection bmp = getConnection(); try { PreparedStatement ps2 = bmp.prepareStatement( "SELECT " + "* " + "FROM " + "man_uni_org_tab " + "WHERE " + "cod_uni_org=? " + "AND cod_man=?"); ps2.setLong(1, newCOD_UNI_ORG); ps2.setLong(2, newCOD_MAN); ResultSet rs = ps2.executeQuery(); if (!rs.next()) { PreparedStatement ps1 = bmp.prepareStatement( "INSERT INTO " + "man_uni_org_tab " + "(cod_uni_org," + "cod_man) " + "VALUES " + "(?,?)"); ps1.setLong(1, newCOD_UNI_ORG); ps1.setLong(2, newCOD_MAN); ps1.executeUpdate(); } PreparedStatement ps = bmp.prepareStatement( "INSERT INTO " + "man_dpd_uni_org_tab " + "(cod_dpd," + "cod_azl," + "cod_uni_org," + "cod_man," + "dat_inz," + "dat_fie," + "cod_tpl_con) " + "VALUES" + "(?,?,?,?,?,?,?)"); ps.setLong(1, COD_DPD); ps.setLong(2, COD_AZL); ps.setLong(3, newCOD_UNI_ORG); ps.setLong(4, newCOD_MAN); ps.setDate(5, newDAT_INZ); ps.setDate(6, newDAT_FIE); if (lCOD_TPL_CON == 0) ps.setNull(7, java.sql.Types.BIGINT); else ps.setLong(7, lCOD_TPL_CON); ps.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //==================================================== public void removeCOD_MAN(long newCOD_MAN, long newCOD_UNI_ORG,java.sql.Date DAT_INZ) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("DELETE FROM man_dpd_uni_org_tab " + "WHERE cod_dpd=? AND cod_man=? AND cod_uni_org=? " + "AND cod_azl=? AND dat_inz=?"); ps.setLong(1, COD_DPD); ps.setLong(2, newCOD_MAN); ps.setLong(3, newCOD_UNI_ORG); ps.setLong(4, COD_AZL); ps.setDate(5, DAT_INZ); if (ps.executeUpdate() == 0) { throw new NoSuchEntityException("Riga con ID=" + newCOD_MAN + "|" + newCOD_UNI_ORG + " non e' trovata"); } } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //==================================================== public void addCOR_DPD(String sATE_FRE_DPD, String sESI_TES_VRF, String sMAT_CSG, long lCOD_COR, java.sql.Date sDAT_EFT_COR) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("INSERT INTO " + " cor_dpd_tab (cod_dpd,cod_cor,cod_azl,ate_fre_dpd," + " esi_tes_vrf,mat_csg, dat_eft_cor) " + " VALUES(?,?,?,?,?,?,?)"); ps.setLong(1, COD_DPD); ps.setLong(2, lCOD_COR); ps.setLong(3, COD_AZL); ps.setString(4, sATE_FRE_DPD); ps.setString(5, sESI_TES_VRF); ps.setString(6, sMAT_CSG); ps.setDate(7, sDAT_EFT_COR); ps.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //--- mary 06/04/2004 public void removeCOR_DPD(long lCOD_COR_DPD, java.sql.Date sDAT_EFT_COR) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("select cod_dpd FROM sch_egz_cor_tab sessione, isc_cor_tab iscritti " + "WHERE sessione.COD_SCH_EGZ_COR = iscritti.COD_SCH_EGZ_COR " + "and iscritti.cod_dpd = ? " + "and iscritti.cod_azl = ? " + "and sessione.cod_cor = ? " + "and sessione.DAT_PIF_EGZ_COR = ? " + "and sessione.cod_azl = ? "); ps.setLong(1, COD_DPD); ps.setLong(2, COD_AZL); ps.setLong(3, lCOD_COR_DPD); ps.setDate(4, sDAT_EFT_COR); ps.setLong(5, COD_AZL); ResultSet rs = ps.executeQuery(); if (rs.next()) { throw new Exception("Non e' possibile eliminare un corso con sessione aperta."); } PreparedStatement ps1 = bmp.prepareStatement("DELETE FROM cor_dpd_tab " + " WHERE cod_dpd=? AND cod_azl=? " + " AND cod_cor=? AND dat_eft_cor=?"); ps1.setLong(1, COD_DPD); ps1.setLong(2, COD_AZL); ps1.setLong(3, lCOD_COR_DPD); ps1.setDate(4, sDAT_EFT_COR); if (ps1.executeUpdate() == 0) { throw new NoSuchEntityException("Riga con ID=" + lCOD_COR_DPD + " non e' trovata"); } } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } public void editCOR_DPD(long COR_ID,String sMAT_CSG, String sESI_TES_VRF, String sATE_FRE_DPD, java.sql.Date dDAT_CSG_MAT,java.sql.Date sDAT_EFT_COR,java.sql.Date dDAT_EFT_TES_VRF, long lPTG_OTT_DPD,java.sql.Date oldDAT_EFT_COR) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("UPDATE cor_dpd_tab " + " SET dat_csg_mat=?,dat_eft_tes_vrf=?,ptg_ott_dpd=?," + " dat_eft_cor=?, mat_csg=?,esi_tes_vrf=?,ate_fre_dpd=?" + " WHERE cod_cor=? AND cod_dpd=? " + " AND cod_azl=? AND dat_eft_cor=?"); ps.setDate(1, dDAT_CSG_MAT); ps.setDate(2, dDAT_EFT_TES_VRF); ps.setLong(3, lPTG_OTT_DPD); ps.setDate(4, sDAT_EFT_COR); ps.setString(5, sMAT_CSG); ps.setString(6, sESI_TES_VRF); ps.setString(7, sATE_FRE_DPD); ps.setLong(8, COR_ID); ps.setLong(9, COD_DPD); ps.setLong(10, COD_AZL); ps.setDate(11, oldDAT_EFT_COR); ps.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } public Collection ejbGetDipendenti_FOD_DBT_View(long lAZL_ID, String newNOM_MAN, boolean orderDesc) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement( /* Estrae tutti i corsi associati ai dipendenti esclusi quelli conclusi positivamente */ "SELECT " + "z.cod_cor, " + "z.nom_cor, " + "a.cog_dpd, " + "a.nom_dpd, " + "a.cod_dpd, " + "b.dat_eft_cor as dat_cor " + "FROM " + "view_ana_dpd_tab a, " + "cor_dpd_tab b, " + "ana_cor_tab z " + "WHERE " + "a.cod_dpd = b.cod_dpd " + "AND b.cod_cor = z.cod_cor " + "AND upper(b.esi_tes_vrf) != 'P' " + "AND a.cod_azl = b.cod_azl " + "AND a.cod_azl = ? " + "UNION " /* Estrae tutti i corsi associati ai percorsi formativi associati ai dipendenti esclusi quelli conclusi positivamente*/ + "SELECT " + "z.cod_cor, " + "z.nom_cor, " + "a.cog_dpd, " + "a.nom_dpd, " + "a.cod_dpd, " + "CAST(NULL AS DATE) AS dat_cor " + "FROM " + "view_ana_dpd_tab a, " + "pcs_frm_dpd_tab f, " + "cor_pcs_frm_tab g, " + "ana_cor_tab z " + "WHERE " + "a.cod_dpd = f.cod_dpd " + "AND f.cod_pcs_frm = g.cod_pcs_frm " + "AND a.cod_azl = ? " + "AND g.cod_cor = z.cod_cor " + "AND g.cod_cor NOT IN (" + "SELECT " + "cod_cor " + "FROM " + "cor_dpd_tab b " + "WHERE " + "a.cod_dpd = b.cod_dpd " + "AND upper(b.esi_tes_vrf) = 'P') " + "UNION " /* Estrae tutti i corsi associati alle mansioni associate ai dipendenti esclusi quelli conclusi positivamente*/ + "SELECT " + "z.cod_cor, " + "z.nom_cor, " + "a.cog_dpd, " + "a.nom_dpd, " + "a.cod_dpd, " + "d.dat_inz as dat_cor " + "FROM " + "view_ana_dpd_tab a, " + "man_dpd_uni_org_tab c, " + "cor_man_tab d, " + "ana_cor_tab z, " + "ana_man_tab b, " + "ana_uni_org_tab e " + "WHERE " + "a.cod_dpd = c.cod_dpd " + "AND c.cod_man = d.cod_man " + "AND c.cod_man = b.cod_man " + "AND c.cod_uni_org = e.cod_uni_org " + "AND d.cod_cor = z.cod_cor " + "AND d.cod_cor NOT IN (" + "SELECT " + "cod_cor " + "FROM " + "cor_dpd_tab b " + "WHERE " + "a.cod_dpd = b.cod_dpd " + "AND upper(b.esi_tes_vrf) = 'P') " + "AND a.cod_azl = ? " + "AND b.nom_man=? " + "ORDER BY " + "cog_dpd " + (orderDesc?"desc":"") + ", " + "nom_dpd " + (orderDesc?"desc":"") + ", " + "nom_cor, " + "dat_cor desc"); ps.setLong(1, lAZL_ID); ps.setLong(2, lAZL_ID); ps.setLong(3, lAZL_ID); ps.setString(4, newNOM_MAN); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Dipendenti_FOD_DBT_View obj = new Dipendenti_FOD_DBT_View(); obj.COD_COR = rs.getLong(1); obj.NOM_COR = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.NOM_DPD = rs.getString(4); obj.COD_DPD = rs.getLong(5); obj.DAT_COR = rs.getDate(6); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //----------------------------------------------- /////////////////////VIEW By Podmasteriv in SCH_COR form//////////////////////////////////// public Collection ejbGetScadenzario_DPI_View(long lCOD_AZL, long lNOM_COR, String lNOM_DCT, java.sql.Date dDAT_PIF_EGZ_COR_DAL, java.sql.Date dDAT_PIF_EGZ_COR_AL, String strSTA_INT, java.sql.Date dEFF_DAT_DAL, java.sql.Date dEFF_DAT_AL, String strRAGGRUPPATI, String strTYPE, String strFR) { int icounterWhere = 3; int iCOUNT_NOM_COR = 0, iCOUNT_NOM_DCT = 0, iCOUNT_DAT_PIF_EGZ_COR_DAL = 0, iCOUNT_DAT_PIF_EGZ_COR_AL = 0, iCOUNT_EFF_DAT_DAL = 0, iCOUNT_EFF_DAT_AL = 0; String strFROM = "", strWHERE = "", strGROUP = ""; //--- Nome Tipologia organizativa if (lNOM_COR != 0) { iCOUNT_NOM_COR = icounterWhere; icounterWhere++; strFROM = strFROM + " ,tpl_dpi_tab c "; strWHERE = strWHERE + " AND c.cod_tpl_dpi = ? "; } //--- Responsabile organizativa if (lNOM_DCT != "") { //A.NOM_RSP_INR iCOUNT_NOM_DCT = icounterWhere; icounterWhere++; strFROM = strFROM + " ,sch_inr_dpi_tab a "; strWHERE = strWHERE + " AND a.nom_rsp_inr LIKE ? "; } //--- DATA PIANIFICAZIONE VISITA if ((dDAT_PIF_EGZ_COR_DAL != null) && (dDAT_PIF_EGZ_COR_AL != null)) { iCOUNT_DAT_PIF_EGZ_COR_DAL = icounterWhere; icounterWhere++; iCOUNT_DAT_PIF_EGZ_COR_AL = icounterWhere; icounterWhere++; //A.dat_pif_inr strWHERE = strWHERE + " AND a.dat_pif_inr BETWEEN ? AND ? "; } if ((dDAT_PIF_EGZ_COR_DAL != null) && (dDAT_PIF_EGZ_COR_AL == null)) { iCOUNT_DAT_PIF_EGZ_COR_DAL = icounterWhere; icounterWhere++; strWHERE = strWHERE + " AND a.dat_pif_inr >= ? "; } if ((dDAT_PIF_EGZ_COR_DAL == null) && (dDAT_PIF_EGZ_COR_AL != null)) { iCOUNT_DAT_PIF_EGZ_COR_AL = icounterWhere; icounterWhere++; strWHERE = strWHERE + " AND a.dat_pif_inr <= ? "; } //--- Stato misura if (strSTA_INT.equals("G")) { strWHERE = strWHERE + " AND a.dat_inr IS NOT NULL "; } if (strSTA_INT.equals("D")) { strWHERE = strWHERE + " AND a.dat_inr IS NULL "; dEFF_DAT_DAL = null; dEFF_DAT_AL = null; } //--- DATA EFFETTUAZIONE if ((dEFF_DAT_DAL != null) && (dEFF_DAT_AL != null)) { iCOUNT_EFF_DAT_DAL = icounterWhere; icounterWhere++; iCOUNT_EFF_DAT_AL = icounterWhere; icounterWhere++; strWHERE = strWHERE + " AND a.dat_inr BETWEEN ? AND ? "; } if ((dEFF_DAT_DAL != null) && (dEFF_DAT_AL == null)) { iCOUNT_EFF_DAT_DAL = icounterWhere; icounterWhere++; strWHERE = strWHERE + " AND a.dat_inr >= ? "; } if ((dEFF_DAT_DAL == null) && (dEFF_DAT_AL != null)) { iCOUNT_EFF_DAT_AL = icounterWhere; icounterWhere++; strWHERE = strWHERE + " AND a.dat_inr <= ? "; } //*** ORDER ***// //--- Raggruppati = N String VAR_ORDER = ""; String strSOR = ""; if (!"".equals(strTYPE)) { if ("INRup".equals(strTYPE)) { strSOR = ", a.dat_pif_inr "; VAR_ORDER = " ORDER BY a.dat_pif_inr "; } if ("EFTup".equals(strTYPE)) { strSOR = ",a.dat_inr "; VAR_ORDER = " ORDER BY a.dat_inr "; } if ("INRdw".equals(strTYPE)) { strSOR = ", a.dat_pif_inr DESC "; VAR_ORDER = " ORDER BY a.dat_pif_inr DESC "; } if ("EFTdw".equals(strTYPE)) { strSOR = ", a.dat_inr DESC "; VAR_ORDER = " ORDER BY a.dat_inr DESC "; } } //strSORT_DAT_PIF=strSORT_DAT_PIF.replaceAll("\'","\\"); //strSORT_DAT_EFT=strSORT_DAT_EFT.replaceAll("\'","\\"); if (strRAGGRUPPATI.equals("N")) { strGROUP = VAR_ORDER; } //--- Raggruppati = T if (strRAGGRUPPATI.equals("T")) { strGROUP = " ORDER BY c.nom_tpl_dpi " + strSOR; } //--- Raggruppati = L if (strRAGGRUPPATI.equals("L")) { strGROUP = " ORDER BY b.ide_lot_dpi " + strSOR; } //--- Raggruppati = A if (strRAGGRUPPATI.equals("A")) { strGROUP = " ORDER BY d.rag_scl_azl " + strSOR; } BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT a.cod_sch_inr_dpi, b.ide_lot_dpi,c.nom_tpl_dpi, a.dat_pif_inr, a.dat_inr, d.rag_scl_azl ,d.cod_azl FROM sch_inr_dpi_tab a, ana_lot_dpi_tab b, tpl_dpi_tab c, ana_azl_tab d WHERE a.cod_lot_dpi = b.cod_lot_dpi AND b.cod_tpl_dpi = c.cod_tpl_dpi AND b.cod_azl= d.cod_azl AND d.cod_azl=? AND a.tpl_inr_dpi LIKE ? " + strWHERE + " " + strGROUP); ps.setLong(1, lCOD_AZL); ps.setString(2, strFR); if (iCOUNT_NOM_COR != 0) { ps.setLong(iCOUNT_NOM_COR, lNOM_COR); } if (iCOUNT_NOM_DCT != 0) { ps.setString(iCOUNT_NOM_DCT, lNOM_DCT + "%"); } if (iCOUNT_DAT_PIF_EGZ_COR_DAL != 0) { ps.setDate(iCOUNT_DAT_PIF_EGZ_COR_DAL, dDAT_PIF_EGZ_COR_DAL); } if (iCOUNT_DAT_PIF_EGZ_COR_AL != 0) { ps.setDate(iCOUNT_DAT_PIF_EGZ_COR_AL, dDAT_PIF_EGZ_COR_AL); } if (iCOUNT_EFF_DAT_DAL != 0) { ps.setDate(iCOUNT_EFF_DAT_DAL, dEFF_DAT_DAL); } if (iCOUNT_EFF_DAT_AL != 0) { ps.setDate(iCOUNT_EFF_DAT_AL, dEFF_DAT_AL); } ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Scadenzario_DPI_View obj = new Scadenzario_DPI_View(); obj.COD_SCH_INR_DPI = rs.getLong(1); obj.IDE_LOT_DPI = rs.getString(2); obj.NOM_TPL_DPI = rs.getString(3); obj.DAT_PIF_INR = rs.getDate(4); obj.DAT_INR = rs.getDate(5); obj.RAG_SCL_AZL = rs.getString(6); obj.COD_AZL = rs.getLong(7); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //--------------------------------------------------------------- //<report> public DipendenteFunzioneView ejbGetDipendenteFunzioneView(long lCOD_DPD) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("select a.cod_dpd ,a.nom_dpd ,a.cog_dpd ,a.cod_fis_dpd ,a.cod_fuz_azl, b.nom_fuz_azl ,a.mtr_dpd from view_ana_dpd_tab a, ana_fuz_azl_tab b where a.cod_fuz_azl = b.cod_fuz_azl and a.cod_dpd=?"); ps.setLong(1, lCOD_DPD); ResultSet rs = ps.executeQuery(); DipendenteFunzioneView obj = new DipendenteFunzioneView(); if (rs.next()) { obj.lCOD_DPD = rs.getLong(1); obj.strNOM_DPD = rs.getString(2); obj.strCOG_DPD = rs.getString(3); obj.strCOD_FIS_DPD = rs.getString(4); obj.lCOD_FUZ_AZL = rs.getLong(5); obj.strNOM_FUZ_AZL = rs.getString(6); obj.strMTR_DPD = rs.getString(7); } bmp.close(); return obj; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } public Collection findEx(long lCOD_AZL, String strNOM_DPD, String strCOG_DPD, String strMTR_DPD, Long lCOD_FUZ_AZL, java.sql.Date dtDAT_NAS_DPD, String strLUO_NAS_DPD, String strCIT_DPD, String strIDZ_DPD, String strNUM_CIC_DPD, String strCAP_DPD, String strPRV_DPD, Long lCOD_DTE, java.sql.Date dtDAT_ASS_DPD, String strLIV_DPD, java.sql.Date dtDAT_CES_DPD, String strSEX_DPD, boolean ViewCessati, int iOrderParameter ) { return (new DipendenteBean()).ejbFindEx(lCOD_AZL, strNOM_DPD, strCOG_DPD, strMTR_DPD, lCOD_FUZ_AZL, dtDAT_NAS_DPD, strLUO_NAS_DPD, strCIT_DPD, strIDZ_DPD, strNUM_CIC_DPD, strCAP_DPD, strPRV_DPD, lCOD_DTE, dtDAT_ASS_DPD, strLIV_DPD, dtDAT_CES_DPD, strSEX_DPD, ViewCessati, iOrderParameter); // } ; public Collection ejbFindEx(long lCOD_AZL, String strNOM_DPD, String strCOG_DPD, String strMTR_DPD, Long lCOD_FUZ_AZL, java.sql.Date dtDAT_NAS_DPD, String strLUO_NAS_DPD, String strCIT_DPD, String strIDZ_DPD, String strNUM_CIC_DPD, String strCAP_DPD, String strPRV_DPD, Long lCOD_DTE, java.sql.Date dtDAT_ASS_DPD, String strLIV_DPD, java.sql.Date dtDAT_CES_DPD, String strSEX_DPD, boolean ViewCessati, int iOrderParameter ) { return (new DipendenteBean()).ejbFindExSOP(lCOD_AZL, strNOM_DPD, strCOG_DPD, strMTR_DPD, lCOD_FUZ_AZL, dtDAT_NAS_DPD, strLUO_NAS_DPD, strCIT_DPD, strIDZ_DPD, strNUM_CIC_DPD, strCAP_DPD, strPRV_DPD, lCOD_DTE, dtDAT_ASS_DPD, strLIV_DPD, dtDAT_CES_DPD, strSEX_DPD , ViewCessati,null, iOrderParameter); } /* public Collection ejbFindEx(long lCOD_AZL, String strNOM_DPD, String strCOG_DPD, String strMTR_DPD, Long lCOD_FUZ_AZL, java.sql.Date dtDAT_NAS_DPD, String strLUO_NAS_DPD, String strCIT_DPD, String strIDZ_DPD, String strNUM_CIC_DPD, String strCAP_DPD, String strPRV_DPD, Long lCOD_DTE, java.sql.Date dtDAT_ASS_DPD, String strLIV_DPD, java.sql.Date dtDAT_CES_DPD, boolean ViewCessati, int iOrderParameter ) { String Table = ViewCessati ? "ana_dpd_tab" : "view_ana_dpd_tab"; String strSql = "SELECT a.cod_dpd, UPPER(a.nom_dpd) AS nom_dpd, UPPER(a.cog_dpd) AS cog_dpd, b.nom_fuz_azl, a.dat_nas_dpd, a.luo_nas_dpd, a.cit_dpd, a.dat_ces_dpd " + "FROM " + Table + " a,ana_fuz_azl_tab b WHERE a.cod_fuz_azl = b.cod_fuz_azl AND cod_azl = ? "; if (strNOM_DPD != null) { strSql = strSql + " AND UPPER(nom_dpd) LIKE ?"; } ; if (lCOD_FUZ_AZL != null) { strSql = strSql + " AND b.cod_fuz_azl = ?"; } ; if (strCOG_DPD != null) { strSql = strSql + " AND UPPER(cog_dpd) LIKE ?"; } ; if (strMTR_DPD != null) { strSql = strSql + " AND UPPER(mtr_dpd) LIKE ?"; } ; if (dtDAT_NAS_DPD != null) { strSql = strSql + " AND dat_nas_dpd = ?"; } ; if (strLUO_NAS_DPD != null) { strSql = strSql + " AND UPPER(luo_nas_dpd) LIKE ?"; } ; if (strCIT_DPD != null) { strSql = strSql + " AND UPPER(cit_dpd) LIKE ?"; } ; if (strIDZ_DPD != null) { strSql = strSql + " AND UPPER(idz_dpd) LIKE ?"; } ; if (strNUM_CIC_DPD != null) { strSql = strSql + " AND UPPER(num_cic_dpd) LIKE ?"; } ; if (strCAP_DPD != null) { strSql = strSql + " AND UPPER(cap_dpd) LIKE ?"; } ; if (strPRV_DPD != null) { strSql = strSql + " AND UPPER(prv_dpd) LIKE ?"; } ; if (lCOD_DTE != null) { strSql = strSql + " AND cod_dte = ?"; } ; if (dtDAT_ASS_DPD != null) { strSql = strSql + " AND dat_ass_dpd = ?"; } ; if (strLIV_DPD != null) { strSql = strSql + " AND UPPER(liv_dpd) LIKE ?"; } ; if (dtDAT_CES_DPD != null) { strSql = strSql + " AND dat_ces_dpd = ?"; } ; strSql += " ORDER BY 3,2"; int i = 1; BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement(strSql); ps.setLong(i++, lCOD_AZL); if (strNOM_DPD != null) { ps.setString(i++, strNOM_DPD.toUpperCase()); } ; if (lCOD_FUZ_AZL != null) { ps.setLong(i++, lCOD_FUZ_AZL.longValue()); } ; if (strCOG_DPD != null) { ps.setString(i++, strCOG_DPD.toUpperCase()); } ; if (strMTR_DPD != null) { ps.setString(i++, strMTR_DPD.toUpperCase()); } ; if (dtDAT_NAS_DPD != null) { ps.setDate(i++, dtDAT_NAS_DPD); } ; if (strLUO_NAS_DPD != null) { ps.setString(i++, strLUO_NAS_DPD.toUpperCase()); } ; if (strCIT_DPD != null) { ps.setString(i++, strCIT_DPD.toUpperCase()); } ; if (strIDZ_DPD != null) { ps.setString(i++, strIDZ_DPD.toUpperCase()); } ; if (strNUM_CIC_DPD != null) { ps.setString(i++, strNUM_CIC_DPD.toUpperCase()); } ; if (strCAP_DPD != null) { ps.setString(i++, strCAP_DPD.toUpperCase()); } ; if (strPRV_DPD != null) { ps.setString(i++, strPRV_DPD.toUpperCase()); } ; if (lCOD_DTE != null) { ps.setLong(i++, lCOD_DTE.longValue()); } ; if (dtDAT_ASS_DPD != null) { ps.setDate(i++, dtDAT_ASS_DPD); } ; if (strLIV_DPD != null) { ps.setString(i++, strLIV_DPD); } ; if (dtDAT_CES_DPD != null) { ps.setDate(i++, dtDAT_CES_DPD); } ; //---------------------------------------------------------------------- ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Dipendenti_Search_View obj = new Dipendenti_Search_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.NOM_FUZ_AZL = rs.getString(4); obj.DAT_NAS_DPD = rs.getDate(5); obj.LUO_NAS_DPD = rs.getString(6); obj.CIT_DPD = rs.getString(7); obj.DAT_CES_DPD = rs.getDate(8); al.add(obj); } return al; //---------------------------------------------------------------------- } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(strSql + "\n" + ex); } finally { bmp.close(); } }*/ public Collection findExSOP(long lCOD_AZL, String strNOM_DPD, String strCOG_DPD, String strMTR_DPD, Long lCOD_FUZ_AZL, java.sql.Date dtDAT_NAS_DPD, String strLUO_NAS_DPD, String strCIT_DPD, String strIDZ_DPD, String strNUM_CIC_DPD, String strCAP_DPD, String strPRV_DPD, Long lCOD_DTE, java.sql.Date dtDAT_ASS_DPD, String strLIV_DPD, java.sql.Date dtDAT_CES_DPD, String strSEX_DPD, boolean ViewCessati, String strSubject, int iOrderParameter /*not used for now*/) { return (new DipendenteBean()).ejbFindExSOP(lCOD_AZL, strNOM_DPD, strCOG_DPD, strMTR_DPD, lCOD_FUZ_AZL, dtDAT_NAS_DPD, strLUO_NAS_DPD, strCIT_DPD, strIDZ_DPD, strNUM_CIC_DPD, strCAP_DPD, strPRV_DPD, lCOD_DTE, dtDAT_ASS_DPD, strLIV_DPD, dtDAT_CES_DPD, strSEX_DPD, ViewCessati, strSubject, iOrderParameter ); } ; public Collection ejbFindExSOP(long lCOD_AZL, String strNOM_DPD, String strCOG_DPD, String strMTR_DPD, Long lCOD_FUZ_AZL, java.sql.Date dtDAT_NAS_DPD, String strLUO_NAS_DPD, String strCIT_DPD, String strIDZ_DPD, String strNUM_CIC_DPD, String strCAP_DPD, String strPRV_DPD, Long lCOD_DTE, java.sql.Date dtDAT_ASS_DPD, String strLIV_DPD, java.sql.Date dtDAT_CES_DPD, String strSEX_DPD, boolean ViewCessati, String strSubject, int iOrderParameter /*not used for now*/) { String Table = ViewCessati ? "ana_dpd_tab" : "view_ana_dpd_tab"; String strSql = "SELECT a.cod_dpd, UPPER(a.nom_dpd) AS nom_dpd, UPPER(a.cog_dpd) AS cog_dpd, b.nom_fuz_azl, a.dat_nas_dpd, a.luo_nas_dpd, a.cit_dpd, d.rag_scl_dte, a.dat_ces_dpd, a.mtr_dpd, a.sex_dpd " + "FROM " + Table + " a left outer join ana_dte_tab d ON a.cod_dte=d.cod_dte,ana_fuz_azl_tab b WHERE a.cod_fuz_azl = b.cod_fuz_azl AND a.cod_azl = ? "; if (strNOM_DPD != null) { strSql = strSql + " AND UPPER(nom_dpd) LIKE ?"; } if (lCOD_FUZ_AZL != null) { strSql = strSql + " AND b.cod_fuz_azl = ?"; } if (strCOG_DPD != null) { strSql = strSql + " AND UPPER(cog_dpd) LIKE ?"; } if (strMTR_DPD != null) { strSql = strSql + " AND UPPER(mtr_dpd) LIKE ?"; } if (dtDAT_NAS_DPD != null) { strSql = strSql + " AND dat_nas_dpd = ?"; } if (strLUO_NAS_DPD != null) { strSql = strSql + " AND UPPER(luo_nas_dpd) LIKE ?"; } if (strCIT_DPD != null) { strSql = strSql + " AND UPPER(cit_dpd) LIKE ?"; } if (strIDZ_DPD != null) { strSql = strSql + " AND UPPER(idz_dpd) LIKE ?"; } if (strNUM_CIC_DPD != null) { strSql = strSql + " AND UPPER(num_cic_dpd) LIKE ?"; } if (strCAP_DPD != null) { strSql = strSql + " AND UPPER(cap_dpd) LIKE ?"; } if (strPRV_DPD != null) { strSql = strSql + " AND UPPER(prv_dpd) LIKE ?"; } if ((strSubject!=null)&&(strSubject.equals("DPD_INT"))){ //if (lCOD_DTE == null) { strSql = strSql + " AND a.cod_dte is null "; // } } else if((strSubject!=null)&&(strSubject.equals("DPD_EST"))){ //if (lCOD_DTE == null) { strSql = strSql + " AND a.cod_dte <> 0"; //} } if (lCOD_DTE != null) { strSql = strSql + " AND a.cod_dte = ?"; } if (dtDAT_ASS_DPD != null) { strSql = strSql + " AND dat_ass_dpd = ?"; } if (strLIV_DPD != null) { strSql = strSql + " AND UPPER(liv_dpd) LIKE ?"; } if (dtDAT_CES_DPD != null) { strSql = strSql + " AND dat_ces_dpd = ?"; } if (strSEX_DPD != null) { strSql = strSql + " AND UPPER(a.sex_dpd) LIKE ?"; } strSql += " ORDER BY 3,2"; int i = 1; BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement(strSql); ps.setLong(i++, lCOD_AZL); if (strNOM_DPD != null) { ps.setString(i++, strNOM_DPD.toUpperCase()); } if (lCOD_FUZ_AZL != null) { ps.setLong(i++, lCOD_FUZ_AZL.longValue()); } if (strCOG_DPD != null) { ps.setString(i++, strCOG_DPD.toUpperCase()); } if (strMTR_DPD != null) { ps.setString(i++, strMTR_DPD.toUpperCase()); } if (dtDAT_NAS_DPD != null) { ps.setDate(i++, dtDAT_NAS_DPD); } if (strLUO_NAS_DPD != null) { ps.setString(i++, strLUO_NAS_DPD.toUpperCase()); } if (strCIT_DPD != null) { ps.setString(i++, strCIT_DPD.toUpperCase()); } if (strIDZ_DPD != null) { ps.setString(i++, strIDZ_DPD.toUpperCase()); } if (strNUM_CIC_DPD != null) { ps.setString(i++, strNUM_CIC_DPD.toUpperCase()); } if (strCAP_DPD != null) { ps.setString(i++, strCAP_DPD.toUpperCase()); } if (strPRV_DPD != null) { ps.setString(i++, strPRV_DPD.toUpperCase()); } if (lCOD_DTE != null) { ps.setLong(i++, lCOD_DTE.longValue()); } if (dtDAT_ASS_DPD != null) { ps.setDate(i++, dtDAT_ASS_DPD); } if (strLIV_DPD != null) { ps.setString(i++, strLIV_DPD); } if (dtDAT_CES_DPD != null) { ps.setDate(i++, dtDAT_CES_DPD); } if (strSEX_DPD != null) { ps.setString(i++, strSEX_DPD.toUpperCase()); } //---------------------------------------------------------------------- ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Dipendenti_Search_View obj = new Dipendenti_Search_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); obj.NOM_FUZ_AZL = rs.getString(4); obj.DAT_NAS_DPD = rs.getDate(5); obj.LUO_NAS_DPD = rs.getString(6); obj.CIT_DPD = rs.getString(7); obj.RAG_SCL_DTE=rs.getString(8); obj.DAT_CES_DPD = rs.getDate(9); obj.MTR_DPD = rs.getString(10); obj.SEX_DPD = rs.getString(11); al.add(obj); } return al; //---------------------------------------------------------------------- } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(strSql + "\n" + ex); } finally { bmp.close(); } } //<alex date="21/04/2004"> public Collection ejbGetDipendenteByDitta(long lCOD_AZL, long lCOD_DTE) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT cod_dpd,nom_dpd,cog_dpd FROM view_ana_dpd_tab WHERE cod_azl=? and cod_dte=? ORDER BY cog_dpd "); ps.setLong(1, lCOD_AZL); ps.setLong(2, lCOD_DTE); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Dipendenti_Names_View obj = new Dipendenti_Names_View(); obj.COD_DPD = rs.getLong(1); obj.NOM_DPD = rs.getString(2); obj.COG_DPD = rs.getString(3); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } public Collection ejbGetDipendenteByMTR(long lCOD_AZL, String strMTR_DIP) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement("SELECT cod_dpd FROM view_ana_dpd_tab WHERE cod_azl=? and mtr_dpd=?"); ps.setLong(1, lCOD_AZL); ps.setString(2, strMTR_DIP); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { Dipendenti_Names_View obj = new Dipendenti_Names_View(); obj.COD_DPD = rs.getLong(1); al.add(obj); } bmp.close(); return al; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } public boolean CodiceFiscaleExists(String strCOD_FIS_DPD, long lCOD_AZL, String strMTR_DPD, long lCOD_DPD) { boolean result = false; if (strCOD_FIS_DPD != null && !strCOD_FIS_DPD.trim().equals("")) { BMPConnection bmp = getConnection(); try { PreparedStatement ps = bmp.prepareStatement( "SELECT cod_fis_dpd FROM view_ana_dpd_tab WHERE " + "cod_fis_dpd=? and " + "cod_azl=? and " + "mtr_dpd=? and " + "cod_dpd<>?"); ps.setString(1, strCOD_FIS_DPD); ps.setLong(2, lCOD_AZL); ps.setString(3, strMTR_DPD); ps.setLong(4, lCOD_DPD); ResultSet rs = ps.executeQuery(); result = rs.next(); } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } return result; } public boolean dipendenteCessato(java.sql.Date dDAT_CES_DPD) { DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); try { java.util.Date currentDate = dateFormat.parse(dateFormat.format(new java.util.Date())); return dDAT_CES_DPD != null && !dDAT_CES_DPD.equals("") && currentDate.compareTo(dDAT_CES_DPD) > 0 == true; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } } public String[] getCountDipendenteAttiviCessati(long lCOD_AZL) { BMPConnection bmp = getConnection(); try { StringBuilder sb= new StringBuilder(); sb.append(" select counT(*) as cessati from ana_dpd_tab where " ); sb.append(" dat_ces_dpd is not null "); sb.append(" and cod_azl = ?"); sb.append("union " ); sb.append("select counT(*) as attivi from ana_dpd_tab where " ); sb.append("dat_ces_dpd is null"); sb.append(" and cod_azl = ?"); PreparedStatement ps = bmp.prepareStatement(sb.toString()); ps.setLong(1, lCOD_AZL); ps.setLong(2, lCOD_AZL); ResultSet rs = ps.executeQuery(); java.util.ArrayList al = new java.util.ArrayList(); while (rs.next()) { String obj = new String(); obj = rs.getString(1); al.add(obj); } bmp.close(); String[] ritorno =new String[2]; if(al!=null){ ritorno[0]=al.get(0).toString(); ritorno[1]=al.get(1).toString(); } return ritorno; } catch (Exception ex) { ex.printStackTrace(System.err); throw new EJBException(ex); } finally { bmp.close(); } } //</alex> ///////////ATTENTION!!//////////////////////////////////////// }
s2sprodotti/SDS
SistemaDellaSicurezza/src/com/apconsulting/luna/ejb/Dipendente/DipendenteBean.java
Java
gpl-2.0
97,429
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> //Functions to be ran on thread: pth void *testFunction(){ int i; for(i=0;i<10;i++){ sleep(1); printf("Test1 Loop %d\n", i); } } //Functions to be ran on thread: pth1 void *testFunction1(){ int i; for(i=0;i<10;i++){ sleep(1); printf("Test2 Loop %d\n", i); } } int main(){ //Define threads pthread_t pth, pth1; //Create thread -> Start thread //If the function is not void, then the create function would return a value // depends on the type of the function pthread_create(&pth, NULL, testFunction, NULL); pthread_create(&pth1, NULL, testFunction1, NULL); //Thread join here, afterward return values can be fetched. pthread_join(pth, NULL); pthread_join(pth1, NULL); //Continues return 0; }
vodaben/CSCI4430A1
threadSample/thread.c
C
gpl-2.0
806
from django import forms from getresults_aliquot.models import Aliquot from .models import Order class OrderForm(forms.ModelForm): def clean_aliquot_identifier(self): aliquot_identifier = self.cleaned_data.get('aliquot_identifier') try: Aliquot.objects.get(aliquot_identifier=aliquot_identifier) except Aliquot.DoesNotExist: raise forms.ValidationError('Invalid Aliquot Identifier. Got {}'.format(aliquot_identifier)) class Meta: model = Order
botswana-harvard/getresults-order
getresults_order/forms.py
Python
gpl-2.0
514
je_coupon ========= JobEngine's Coupon Plugin
louisludwik/wptest
wp-content/plugins/je_coupon/README.md
Markdown
gpl-2.0
46
package org.rmath.util; import java.io.IOException; import java.util.HashMap; import java.util.Locale; public class OSInfo { private static HashMap<String, String> archMapping = new HashMap<String, String>(); public static final String X86 = "x86"; public static final String X86_64 = "x86_64"; public static final String IA64_32 = "ia64_32"; public static final String IA64 = "ia64"; public static final String PPC = "ppc"; public static final String PPC64 = "ppc64"; public static final String IBMZ = "s390"; public static final String IBMZ_64 = "s390x"; public static final String AARCH_64 = "aarch64"; static { // x86 mappings archMapping.put(X86, X86); archMapping.put("i386", X86); archMapping.put("i486", X86); archMapping.put("i586", X86); archMapping.put("i686", X86); archMapping.put("pentium", X86); // x86_64 mappings archMapping.put(X86_64, X86_64); archMapping.put("amd64", X86_64); archMapping.put("em64t", X86_64); archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac // Itenium 64-bit mappings archMapping.put(IA64, IA64); archMapping.put("ia64w", IA64); // Itenium 32-bit mappings, usually an HP-UX construct archMapping.put(IA64_32, IA64_32); archMapping.put("ia64n", IA64_32); // PowerPC mappings archMapping.put(PPC, PPC); archMapping.put("power", PPC); archMapping.put("powerpc", PPC); archMapping.put("power_pc", PPC); archMapping.put("power_rs", PPC); // TODO: PowerPC 64bit mappings archMapping.put(PPC64, PPC64); archMapping.put("power64", PPC64); archMapping.put("powerpc64", PPC64); archMapping.put("power_pc64", PPC64); archMapping.put("power_rs64", PPC64); // IBM z mappings archMapping.put(IBMZ, IBMZ); // IBM z 64-bit mappings archMapping.put(IBMZ_64, IBMZ_64); // Aarch64 mappings archMapping.put(AARCH_64, AARCH_64); } public static void main(String[] args) { if (args.length >= 1) { if ("--os".equals(args[0])) { System.out.print(getOSName()); return; } else if ("--arch".equals(args[0])) { System.out.print(getArchName()); return; } } System.out.print(getNativeLibFolderPathForCurrentOS()); } public static String getNativeLibFolderPathForCurrentOS() { return getOSName().toLowerCase() + "-" + getArchName(); } public static String getOSName() { return translateOSNameToFolderName(System.getProperty("os.name")); } public static String getArchName() { // if running Linux on ARM, need to determine ABI of JVM String osArch = System.getProperty("os.arch"); if (osArch.startsWith("arm") && System.getProperty("os.name").contains("Linux")) { String javaHome = System.getProperty("java.home"); try { // determine if first JVM found uses ARM hard-float ABI String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome + "' -name 'libjvm.so' | head -1 | xargs readelf -A | " + "grep 'Tag_ABI_VFP_args: VFP registers'"}; int exitCode = Runtime.getRuntime().exec(cmdarray).waitFor(); if (exitCode == 0) { return "armhf"; } } catch (IOException e) { // ignored: fall back to "arm" arch (soft-float ABI) } catch (InterruptedException e) { // ignored: fall back to "arm" arch (soft-float ABI) } } else { String lc = osArch.toLowerCase(Locale.US); if (archMapping.containsKey(lc)) { return archMapping.get(lc); } } return translateArchNameToFolderName(osArch); } static String translateOSNameToFolderName(String osName) { if (osName.contains("Windows")) { return "win32"; } else if (osName.contains("Mac")) { return "Mac"; } else if (osName.contains("Linux")) { return "Linux"; } else if (osName.contains("AIX")) { return "AIX"; } else { return osName.replaceAll("\\W", ""); } } static String translateArchNameToFolderName(String archName) { return archName.replaceAll("\\W", ""); } }
git-rbanerjee/rmath-jni
rmath-jni/src/main/java/org/rmath/util/OSInfo.java
Java
gpl-2.0
4,722
<?php /* core/themes/stable/templates/admin/views-ui-container.html.twig */ class __TwigTemplate_44b34f3cd2c220691287fdb39f56ba6cc8f9b413246d166293bf82689c752021 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array(); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array(), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 11 echo "<div"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["attributes"]) ? $context["attributes"] : null), "html", null, true)); echo ">"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["children"]) ? $context["children"] : null), "html", null, true)); echo "</div> "; } public function getTemplateName() { return "core/themes/stable/templates/admin/views-ui-container.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 43 => 11,); } } /* {#*/ /* /***/ /* * @file*/ /* * Theme override for a generic views UI container/wrapper.*/ /* **/ /* * Available variables:*/ /* * - attributes: HTML attributes to apply to the container element.*/ /* * - children: The remaining elements such as dropbuttons and tabs.*/ /* *//* */ /* #}*/ /* <div{{ attributes }}>{{ children }}</div>*/ /* */
sergiustici1993/ffw
sites/default/files/php/twig/9a2bf118_views-ui-container.html.twig_dd286289cc2f182ae6d26ec9ceed18f7796db4fe91acde4072775bc47bb948d6/2a9444a26aa5a52555074837abd5076cc262b92ca9c33b5ef9971a6de8918af8.php
PHP
gpl-2.0
2,587
#!/work/expasy/bin/perl use strict; my $link = $ARGV[0]; my $anchor = $ARGV[1]; print "Content-type:text/html\n\n"; print "<html>\n"; print "<head><title>Popitam Help</title></head>\n"; print "<frameset rows = \"12%,*\">\n"; print "<frame src=\"/tools/popitam/header.html\" name=\"headerframe\"></frame>\n"; print "<frameset cols = \"20%,*\">\n"; print "<frame src=\"/tools/popitam/menu.html\" name=\"menuframe\"></frame>\n"; if($link){ print "<frame src=\"/tools/popitam/"; print $link; if($anchor) { print "#"; print $anchor; } print "\" name=\"contentframe\"></frame>\n"; }else{ print "<frame src=\"/tools/popitam/main.html\" name=\"contentframe\"></frame>\n"; } print " </frameset>\n"; print " </frameset>\n"; print "</html>\n";
chernan/popitam
form/html/help.pl
Perl
gpl-2.0
792
/* * Copyright (C) 2001 Sistina Software (UK) Limited. * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved. * * This file is released under the LGPL. */ #ifndef _LINUX_DEVICE_MAPPER_H #define _LINUX_DEVICE_MAPPER_H #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/ratelimit.h> struct dm_dev; struct dm_target; struct dm_table; struct mapped_device; struct bio_vec; typedef enum { STATUSTYPE_INFO, STATUSTYPE_TABLE } status_type_t; union map_info { void *ptr; unsigned long long ll; unsigned target_request_nr; }; typedef int (*dm_ctr_fn) (struct dm_target *target, unsigned int argc, char **argv); typedef void (*dm_dtr_fn) (struct dm_target *ti); typedef int (*dm_map_fn) (struct dm_target *ti, struct bio *bio, union map_info *map_context); typedef int (*dm_map_request_fn) (struct dm_target *ti, struct request *clone, union map_info *map_context); typedef int (*dm_endio_fn) (struct dm_target *ti, struct bio *bio, int error, union map_info *map_context); typedef int (*dm_request_endio_fn) (struct dm_target *ti, struct request *clone, int error, union map_info *map_context); typedef void (*dm_flush_fn) (struct dm_target *ti); typedef void (*dm_presuspend_fn) (struct dm_target *ti); typedef void (*dm_postsuspend_fn) (struct dm_target *ti); typedef int (*dm_preresume_fn) (struct dm_target *ti); typedef void (*dm_resume_fn) (struct dm_target *ti); typedef int (*dm_status_fn) (struct dm_target *ti, status_type_t status_type, char *result, unsigned int maxlen); typedef int (*dm_message_fn) (struct dm_target *ti, unsigned argc, char **argv); typedef int (*dm_ioctl_fn) (struct dm_target *ti, unsigned int cmd, unsigned long arg); typedef int (*dm_merge_fn) (struct dm_target *ti, struct bvec_merge_data *bvm, struct bio_vec *biovec, int max_size); typedef int (*iterate_devices_callout_fn) (struct dm_target *ti, struct dm_dev *dev, sector_t start, sector_t len, void *data); typedef int (*dm_iterate_devices_fn) (struct dm_target *ti, iterate_devices_callout_fn fn, void *data); typedef void (*dm_io_hints_fn) (struct dm_target *ti, struct queue_limits *limits); typedef int (*dm_busy_fn) (struct dm_target *ti); void dm_error(const char *message); int dm_set_device_limits(struct dm_target *ti, struct dm_dev *dev, sector_t start, sector_t len, void *data); struct dm_dev { struct block_device *bdev; fmode_t mode; char name[16]; }; int dm_get_device(struct dm_target *ti, const char *path, fmode_t mode, struct dm_dev **result); void dm_put_device(struct dm_target *ti, struct dm_dev *d); struct target_type { uint64_t features; const char *name; struct module *module; unsigned version[3]; dm_ctr_fn ctr; dm_dtr_fn dtr; dm_map_fn map; dm_map_request_fn map_rq; dm_endio_fn end_io; dm_request_endio_fn rq_end_io; dm_flush_fn flush; dm_presuspend_fn presuspend; dm_postsuspend_fn postsuspend; dm_preresume_fn preresume; dm_resume_fn resume; dm_status_fn status; dm_message_fn message; dm_ioctl_fn ioctl; dm_merge_fn merge; dm_busy_fn busy; dm_iterate_devices_fn iterate_devices; dm_io_hints_fn io_hints; struct list_head list; }; #define DM_TARGET_SINGLETON 0x00000001 #define dm_target_needs_singleton(type) ((type)->features & DM_TARGET_SINGLETON) #define DM_TARGET_ALWAYS_WRITEABLE 0x00000002 #define dm_target_always_writeable(type) \ ((type)->features & DM_TARGET_ALWAYS_WRITEABLE) #define DM_TARGET_IMMUTABLE 0x00000004 #define dm_target_is_immutable(type) ((type)->features & DM_TARGET_IMMUTABLE) struct dm_target { struct dm_table *table; struct target_type *type; sector_t begin; sector_t len; sector_t split_io; unsigned num_flush_requests; unsigned num_discard_requests; void *private; char *error; unsigned discards_supported:1; unsigned discard_zeroes_data_unsupported:1; }; struct dm_target_callbacks { struct list_head list; int (*congested_fn) (struct dm_target_callbacks *, int); }; int dm_register_target(struct target_type *t); void dm_unregister_target(struct target_type *t); struct dm_arg_set { unsigned argc; char **argv; }; struct dm_arg { unsigned min; unsigned max; char *error; }; int dm_read_arg(struct dm_arg *arg, struct dm_arg_set *arg_set, unsigned *value, char **error); int dm_read_arg_group(struct dm_arg *arg, struct dm_arg_set *arg_set, unsigned *num_args, char **error); const char *dm_shift_arg(struct dm_arg_set *as); void dm_consume_args(struct dm_arg_set *as, unsigned num_args); #define DM_ANY_MINOR (-1) int dm_create(int minor, struct mapped_device **md); struct mapped_device *dm_get_md(dev_t dev); void dm_get(struct mapped_device *md); void dm_put(struct mapped_device *md); void dm_set_mdptr(struct mapped_device *md, void *ptr); void *dm_get_mdptr(struct mapped_device *md); int dm_suspend(struct mapped_device *md, unsigned suspend_flags); int dm_resume(struct mapped_device *md); uint32_t dm_get_event_nr(struct mapped_device *md); int dm_wait_event(struct mapped_device *md, int event_nr); uint32_t dm_next_uevent_seq(struct mapped_device *md); void dm_uevent_add(struct mapped_device *md, struct list_head *elist); const char *dm_device_name(struct mapped_device *md); int dm_copy_name_and_uuid(struct mapped_device *md, char *name, char *uuid); struct gendisk *dm_disk(struct mapped_device *md); int dm_suspended(struct dm_target *ti); int dm_noflush_suspending(struct dm_target *ti); union map_info *dm_get_mapinfo(struct bio *bio); union map_info *dm_get_rq_mapinfo(struct request *rq); int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo); int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo); int dm_table_create(struct dm_table **result, fmode_t mode, unsigned num_targets, struct mapped_device *md); int dm_table_add_target(struct dm_table *t, const char *type, sector_t start, sector_t len, char *params); void dm_table_add_target_callbacks(struct dm_table *t, struct dm_target_callbacks *cb); int dm_table_complete(struct dm_table *t); struct dm_table *dm_get_live_table(struct mapped_device *md); void dm_table_get(struct dm_table *t); void dm_table_put(struct dm_table *t); sector_t dm_table_get_size(struct dm_table *t); unsigned int dm_table_get_num_targets(struct dm_table *t); fmode_t dm_table_get_mode(struct dm_table *t); struct mapped_device *dm_table_get_md(struct dm_table *t); void dm_table_event(struct dm_table *t); struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *t); void *dm_vcalloc(unsigned long nmemb, unsigned long elem_size); #define DM_NAME "device-mapper" #ifdef CONFIG_PRINTK extern struct ratelimit_state dm_ratelimit_state; #define dm_ratelimit() __ratelimit(&dm_ratelimit_state) #else #define dm_ratelimit() 0 #endif #define DMCRIT(f, arg...) \ printk(KERN_CRIT DM_NAME ": " DM_MSG_PREFIX ": " f "\n", ## arg) #define DMERR(f, arg...) \ printk(KERN_ERR DM_NAME ": " DM_MSG_PREFIX ": " f "\n", ## arg) #define DMERR_LIMIT(f, arg...) \ do { \ if (dm_ratelimit()) \ printk(KERN_ERR DM_NAME ": " DM_MSG_PREFIX ": " \ f "\n", ## arg); \ } while (0) #define DMWARN(f, arg...) \ printk(KERN_WARNING DM_NAME ": " DM_MSG_PREFIX ": " f "\n", ## arg) #define DMWARN_LIMIT(f, arg...) \ do { \ if (dm_ratelimit()) \ printk(KERN_WARNING DM_NAME ": " DM_MSG_PREFIX ": " \ f "\n", ## arg); \ } while (0) #define DMINFO(f, arg...) \ printk(KERN_INFO DM_NAME ": " DM_MSG_PREFIX ": " f "\n", ## arg) #define DMINFO_LIMIT(f, arg...) \ do { \ if (dm_ratelimit()) \ printk(KERN_INFO DM_NAME ": " DM_MSG_PREFIX ": " f \ "\n", ## arg); \ } while (0) #ifdef CONFIG_DM_DEBUG # define DMDEBUG(f, arg...) \ printk(KERN_DEBUG DM_NAME ": " DM_MSG_PREFIX " DEBUG: " f "\n", ## arg) # define DMDEBUG_LIMIT(f, arg...) \ do { \ if (dm_ratelimit()) \ printk(KERN_DEBUG DM_NAME ": " DM_MSG_PREFIX ": " f \ "\n", ## arg); \ } while (0) #else # define DMDEBUG(f, arg...) do {} while (0) # define DMDEBUG_LIMIT(f, arg...) do {} while (0) #endif #define DMEMIT(x...) sz += ((sz >= maxlen) ? \ 0 : scnprintf(result + sz, maxlen - sz, x)) #define SECTOR_SHIFT 9 #define DM_ENDIO_INCOMPLETE 1 #define DM_ENDIO_REQUEUE 2 #define DM_MAPIO_SUBMITTED 0 #define DM_MAPIO_REMAPPED 1 #define DM_MAPIO_REQUEUE DM_ENDIO_REQUEUE #define dm_div_up(n, sz) (((n) + (sz) - 1) / (sz)) #define dm_sector_div_up(n, sz) ( \ { \ sector_t _r = ((n) + (sz) - 1); \ sector_div(_r, (sz)); \ _r; \ } \ ) #define dm_round_up(n, sz) (dm_div_up((n), (sz)) * (sz)) #define dm_array_too_big(fixed, obj, num) \ ((num) > (UINT_MAX - (fixed)) / (obj)) #define dm_target_offset(ti, sector) ((sector) - (ti)->begin) static inline sector_t to_sector(unsigned long n) { return (n >> SECTOR_SHIFT); } static inline unsigned long to_bytes(sector_t n) { return (n << SECTOR_SHIFT); } void dm_dispatch_request(struct request *rq); void dm_requeue_unmapped_request(struct request *rq); void dm_kill_unmapped_request(struct request *rq, int error); int dm_underlying_device_busy(struct request_queue *q); void dm_end_request(struct request *clone, int error); #endif
Owain94/android_kernel_htc_msm8974
include/linux/device-mapper.h
C
gpl-2.0
9,266
/* * BRLTTY - A background process providing access to the console screen (when in * text mode) for a blind person using a refreshable braille display. * * Copyright (C) 1995-2013 by The BRLTTY Developers. * * BRLTTY comes with ABSOLUTELY NO WARRANTY. * * This is free software, placed under the terms of the * GNU General Public License, as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any * later version. Please see the file LICENSE-GPL for details. * * Web Page: http://mielke.cc/brltty/ * * This software is maintained by Dave Mielke <dave@mielke.cc>. */ /* Virtual/braille.h - Configurable definitions for the Virtual driver * * Edit as necessary for your system. */ #define VR_DEFAULT_SOCKET "127.0.0.1" #define VR_DEFAULT_PORT 35752
Qwaz/solved-hacking-problem
GoogleCTF/2018 Quals/feel_it/brltty/Drivers/Virtual/braille.h
C
gpl-2.0
824
/* Copyright (c) 2008, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 2.5.0 */ /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires * @param {Object} oScope The context the event will fire from. "this" will * refer to this object in the callback. Default value: * the window object. The listener can override this. * @param {boolean} silent pass true to prevent the event from writing to * the debugsystem * @param {int} signature the signature that the custom event subscriber * will receive. YAHOO.util.CustomEvent.LIST or * YAHOO.util.CustomEvent.FLAT. The default is * YAHOO.util.CustomEvent.LIST. * @namespace YAHOO.util * @class CustomEvent * @constructor */ YAHOO.util.CustomEvent = function(type, oScope, silent, signature) { /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The scope the the event will fire from by default. Defaults to the window * obj * @property scope * @type object */ this.scope = oScope || window; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = silent; /** * Custom events support two styles of arguments provided to the event * subscribers. * <ul> * <li>YAHOO.util.CustomEvent.LIST: * <ul> * <li>param1: event name</li> * <li>param2: array of arguments sent to fire</li> * <li>param3: <optional> a custom object supplied by the subscriber</li> * </ul> * </li> * <li>YAHOO.util.CustomEvent.FLAT * <ul> * <li>param1: the first argument passed to fire. If you need to * pass multiple parameters, use and array or object literal</li> * <li>param2: <optional> a custom object supplied by the subscriber</li> * </ul> * </li> * </ul> * @property signature * @type int */ this.signature = signature || YAHOO.util.CustomEvent.LIST; /** * The subscribers to this event * @property subscribers * @type Subscriber[] */ this.subscribers = []; if (!this.silent) { YAHOO.log( "Creating " + this, "info", "Event" ); } var onsubscribeType = "_YUICEOnSubscribe"; // Only add subscribe events for events that are not generated by // CustomEvent if (type !== onsubscribeType) { /** * Custom events provide a custom event that fires whenever there is * a new subscriber to the event. This provides an opportunity to * handle the case where there is a non-repeating event that has * already fired has a new subscriber. * * @event subscribeEvent * @type YAHOO.util.CustomEvent * @param {Function} fn The function to execute * @param {Object} obj An object to be passed along when the event * fires * @param {boolean|Object} override If true, the obj passed in becomes * the execution scope of the listener. * if an object, that object becomes the * the execution scope. */ this.subscribeEvent = new YAHOO.util.CustomEvent(onsubscribeType, this, true); } /** * In order to make it possible to execute the rest of the subscriber * stack when one thows an exception, the subscribers exceptions are * caught. The most recent exception is stored in this property * @property lastError * @type Error */ this.lastError = null; }; /** * Subscriber listener sigature constant. The LIST type returns three * parameters: the event type, the array of args passed to fire, and * the optional custom object * @property YAHOO.util.CustomEvent.LIST * @static * @type int */ YAHOO.util.CustomEvent.LIST = 0; /** * Subscriber listener sigature constant. The FLAT type returns two * parameters: the first argument passed to fire and the optional * custom object * @property YAHOO.util.CustomEvent.FLAT * @static * @type int */ YAHOO.util.CustomEvent.FLAT = 1; YAHOO.util.CustomEvent.prototype = { /** * Subscribes the caller to this event * @method subscribe * @param {Function} fn The function to execute * @param {Object} obj An object to be passed along when the event * fires * @param {boolean|Object} override If true, the obj passed in becomes * the execution scope of the listener. * if an object, that object becomes the * the execution scope. */ subscribe: function(fn, obj, override) { if (!fn) { throw new Error("Invalid callback for subscriber to '" + this.type + "'"); } if (this.subscribeEvent) { this.subscribeEvent.fire(fn, obj, override); } this.subscribers.push( new YAHOO.util.Subscriber(fn, obj, override) ); }, /** * Unsubscribes subscribers. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} obj The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {boolean} True if the subscriber was found and detached. */ unsubscribe: function(fn, obj) { if (!fn) { return this.unsubscribeAll(); } var found = false; for (var i=0, len=this.subscribers.length; i<len; ++i) { var s = this.subscribers[i]; if (s && s.contains(fn, obj)) { this._delete(i); found = true; } } return found; }, /** * Notifies the subscribers. The callback functions will be executed * from the scope specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise */ fire: function() { var len=this.subscribers.length; if (!len && this.silent) { return true; } var args=[], ret=true, i, rebuild=false; for (i=0; i<arguments.length; ++i) { args.push(arguments[i]); } if (!this.silent) { YAHOO.log( "Firing " + this + ", " + "args: " + args + ", " + "subscribers: " + len, "info", "Event" ); } for (i=0; i<len; ++i) { var s = this.subscribers[i]; if (!s) { rebuild=true; } else { if (!this.silent) { YAHOO.log( this.type + "->" + (i+1) + ": " + s, "info", "Event" ); } var scope = s.getScope(this.scope); if (this.signature == YAHOO.util.CustomEvent.FLAT) { var param = null; if (args.length > 0) { param = args[0]; } try { ret = s.fn.call(scope, param, s.obj); } catch(e) { this.lastError = e; YAHOO.log(this + " subscriber exception: " + e, "error", "Event"); } } else { try { ret = s.fn.call(scope, this.type, args, s.obj); } catch(ex) { this.lastError = ex; YAHOO.log(this + " subscriber exception: " + ex, "error", "Event"); } } if (false === ret) { if (!this.silent) { YAHOO.log("Event cancelled, subscriber " + i + " of " + len, "info", "Event"); } //break; return false; } } } if (rebuild) { var newlist=[],subs=this.subscribers; for (i=0,len=subs.length; i<len; i=i+1) { newlist.push(subs[i]); } this.subscribers=newlist; } return true; }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed */ unsubscribeAll: function() { for (var i=0, len=this.subscribers.length; i<len; ++i) { this._delete(len - 1 - i); } this.subscribers=[]; return i; }, /** * @method _delete * @private */ _delete: function(index) { var s = this.subscribers[index]; if (s) { delete s.fn; delete s.obj; } this.subscribers[index]=null; }, /** * @method toString */ toString: function() { return "CustomEvent: " + "'" + this.type + "', " + "scope: " + this.scope; } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The function to execute * @param {Object} obj An object to be passed along when the event fires * @param {boolean} override If true, the obj passed in becomes the execution * scope of the listener * @class Subscriber * @constructor */ YAHOO.util.Subscriber = function(fn, obj, override) { /** * The callback that will be execute when the event fires * @property fn * @type function */ this.fn = fn; /** * An optional custom object that will passed to the callback when * the event fires * @property obj * @type object */ this.obj = YAHOO.lang.isUndefined(obj) ? null : obj; /** * The default execution scope for the event listener is defined when the * event is created (usually the object which contains the event). * By setting override to true, the execution scope becomes the custom * object passed in by the subscriber. If override is an object, that * object becomes the scope. * @property override * @type boolean|object */ this.override = override; }; /** * Returns the execution scope for this listener. If override was set to true * the custom obj will be the scope. If override is an object, that is the * scope, otherwise the default scope will be used. * @method getScope * @param {Object} defaultScope the scope to use if this listener does not * override it. */ YAHOO.util.Subscriber.prototype.getScope = function(defaultScope) { if (this.override) { if (this.override === true) { return this.obj; } else { return this.override; } } return defaultScope; }; /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute * @param {Object} obj an object to be passed along when the event fires * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ YAHOO.util.Subscriber.prototype.contains = function(fn, obj) { if (obj) { return (this.fn == fn && this.obj == obj); } else { return (this.fn == fn); } }; /** * @method toString */ YAHOO.util.Subscriber.prototype.toString = function() { return "Subscriber { obj: " + this.obj + ", override: " + (this.override || "no") + " }"; }; /** * The Event Utility provides utilities for managing DOM Events and tools * for building event systems * * @module event * @title Event Utility * @namespace YAHOO.util * @requires yahoo */ // The first instance of Event will win if it is loaded more than once. // @TODO this needs to be changed so that only the state data that needs to // be preserved is kept, while methods are overwritten/added as needed. // This means that the module pattern can't be used. if (!YAHOO.util.Event) { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ YAHOO.util.Event = function() { /** * True after the onload event has fired * @property loadComplete * @type boolean * @static * @private */ var loadComplete = false; /** * Cache of wrapped listeners * @property listeners * @type array * @static * @private */ var listeners = []; /** * User-defined unload function that will be fired before all events * are detached * @property unloadListeners * @type array * @static * @private */ var unloadListeners = []; /** * Cache of DOM0 event handlers to work around issues with DOM2 events * in Safari * @property legacyEvents * @static * @private */ var legacyEvents = []; /** * Listener stack for DOM0 events * @property legacyHandlers * @static * @private */ var legacyHandlers = []; /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property retryCount * @static * @private */ var retryCount = 0; /** * onAvailable listeners * @property onAvailStack * @static * @private */ var onAvailStack = []; /** * Lookup table for legacy events * @property legacyMap * @static * @private */ var legacyMap = []; /** * Counter for auto id generation * @property counter * @static * @private */ var counter = 0; /** * Normalized keycodes for webkit/safari * @property webkitKeymap * @type {int: int} * @private * @static * @final */ var webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9 // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) }; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 2000@amp;20 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 2000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 20, /** * Element to bind, int constant * @property EL * @type int * @static * @final */ EL: 0, /** * Type of event, int constant * @property TYPE * @type int * @static * @final */ TYPE: 1, /** * Function to execute, int constant * @property FN * @type int * @static * @final */ FN: 2, /** * Function wrapped for scope correction and cleanup, int constant * @property WFN * @type int * @static * @final */ WFN: 3, /** * Object passed in by the user that will be returned as a * parameter to the callback, int constant. Specific to * unload listeners * @property OBJ * @type int * @static * @final */ UNLOAD_OBJ: 3, /** * Adjusted scope, either the element we are registering the event * on or the custom object passed in by the listener, int constant * @property ADJ_SCOPE * @type int * @static * @final */ ADJ_SCOPE: 4, /** * The original obj passed into addListener * @property OBJ * @type int * @static * @final */ OBJ: 5, /** * The original scope parameter passed into addListener * @property OVERRIDE * @type int * @static * @final */ OVERRIDE: 6, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * Safari detection * @property isSafari * @private * @static * @deprecated use YAHOO.env.ua.webkit */ isSafari: YAHOO.env.ua.webkit, /** * webkit version * @property webkit * @type string * @private * @static * @deprecated use YAHOO.env.ua.webkit */ webkit: YAHOO.env.ua.webkit, /** * IE detection * @property isIE * @private * @static * @deprecated use YAHOO.env.ua.ie */ isIE: YAHOO.env.ua.ie, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!this._interval) { var self = this; var callback = function() { self._tryPreloadAttach(); }; this._interval = setInterval(callback, this.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} p_id the id of the element, or an array * of ids to look for. * @param {function} p_fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to p_fn. * @param {boolean|object} p_override If set to true, p_fn will execute * in the scope of p_obj, if set to an object it * will execute in the scope of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static */ onAvailable: function(p_id, p_fn, p_obj, p_override, checkContent) { var a = (YAHOO.lang.isString(p_id)) ? [p_id] : p_id; for (var i=0; i<a.length; i=i+1) { onAvailStack.push({id: a[i], fn: p_fn, obj: p_obj, override: p_override, checkReady: checkContent }); } retryCount = this.POLL_RETRYS; this.startInterval(); }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} p_id the id of the element to look for. * @param {function} p_fn what to execute when the element is ready. * @param {object} p_obj an optional object to be passed back as * a parameter to p_fn. * @param {boolean|object} p_override If set to true, p_fn will execute * in the scope of p_obj. If an object, p_fn will * exectute in the scope of that object * * @static */ onContentReady: function(p_id, p_fn, p_obj, p_override) { this.onAvailable(p_id, p_fn, p_obj, p_override, true); }, /** * Executes the supplied callback when the DOM is first usable. This * will execute immediately if called after the DOMReady event has * fired. @todo the DOMContentReady event does not fire when the * script is dynamically injected into the page. This means the * DOMReady custom event will never fire in FireFox or Opera when the * library is injected. It _will_ fire in Safari, and the IE * implementation would allow for us to fire it if the defered script * is not available. We want this to behave the same in all browsers. * Is there a way to identify when the script has been injected * instead of included inline? Is there a way to know whether the * window onload event has fired without having had a listener attached * to it when it did so? * * <p>The callback is a CustomEvent, so the signature is:</p> * <p>type &lt;string&gt;, args &lt;array&gt;, customobject &lt;object&gt;</p> * <p>For DOMReady events, there are no fire argments, so the * signature is:</p> * <p>"DOMReady", [], obj</p> * * * @method onDOMReady * * @param {function} p_fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to p_fn. * @param {boolean|object} p_scope If set to true, p_fn will execute * in the scope of p_obj, if set to an object it * will execute in the scope of that object * * @static */ onDOMReady: function(p_fn, p_obj, p_override) { if (this.DOMReady) { setTimeout(function() { var s = window; if (p_override) { if (p_override === true) { s = p_obj; } else { s = p_override; } } p_fn.call(s, "DOMReady", [], p_obj); }, 0); } else { this.DOMReadyEvent.subscribe(p_fn, p_obj, p_override); } }, /** * Appends an event handler * * @method addListener * * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {String} sType The type of event to append * @param {Function} fn The method the event invokes * @param {Object} obj An arbitrary object that will be * passed as a parameter to the handler * @param {Boolean|object} override If true, the obj passed in becomes * the execution scope of the listener. If an * object, this object becomes the execution * scope. * @return {Boolean} True if the action was successful or defered, * false if one or more of the elements * could not have the listener attached, * or if the operation throws an exception. * @static */ addListener: function(el, sType, fn, obj, override) { if (!fn || !fn.call) { // throw new TypeError(sType + " addListener call failed, callback undefined"); YAHOO.log(sType + " addListener call failed, invalid callback", "error", "Event"); return false; } // The el argument can be an array of elements or element ids. if ( this._isValidCollection(el)) { var ok = true; for (var i=0,len=el.length; i<len; ++i) { ok = this.on(el[i], sType, fn, obj, override) && ok; } return ok; } else if (YAHOO.lang.isString(el)) { var oEl = this.getEl(el); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until onload event fires // check to see if we need to delay hooking up the event // until after the page loads. if (oEl) { el = oEl; } else { // defer adding the event until the element is available this.onAvailable(el, function() { YAHOO.util.Event.on(el, sType, fn, obj, override); }); return true; } } // Element should be an html element or an array if we get // here. if (!el) { // this.logger.debug("unable to attach event " + sType); return false; } // we need to make sure we fire registered unload events // prior to automatically unhooking them. So we hang on to // these instead of attaching them to the window and fire the // handles explicitly during our one unload event. if ("unload" == sType && obj !== this) { unloadListeners[unloadListeners.length] = [el, sType, fn, obj, override]; return true; } // this.logger.debug("Adding handler: " + el + ", " + sType); // if the user chooses to override the scope, we use the custom // object passed in, otherwise the executing scope will be the // HTML element that the event is registered on var scope = el; if (override) { if (override === true) { scope = obj; } else { scope = override; } } // wrap the function so we can return the obj object when // the event fires; var wrappedFn = function(e) { return fn.call(scope, YAHOO.util.Event.getEvent(e, el), obj); }; var li = [el, sType, fn, wrappedFn, scope, obj, override]; var index = listeners.length; // cache the listener so we can try to automatically unload listeners[index] = li; if (this.useLegacyEvent(el, sType)) { var legacyIndex = this.getLegacyIndex(el, sType); // Add a new dom0 wrapper if one is not detected for this // element if ( legacyIndex == -1 || el != legacyEvents[legacyIndex][0] ) { legacyIndex = legacyEvents.length; legacyMap[el.id + sType] = legacyIndex; // cache the signature for the DOM0 event, and // include the existing handler for the event, if any legacyEvents[legacyIndex] = [el, sType, el["on" + sType]]; legacyHandlers[legacyIndex] = []; el["on" + sType] = function(e) { YAHOO.util.Event.fireLegacyEvent( YAHOO.util.Event.getEvent(e), legacyIndex); }; } // add a reference to the wrapped listener to our custom // stack of events //legacyHandlers[legacyIndex].push(index); legacyHandlers[legacyIndex].push(li); } else { try { this._simpleAdd(el, sType, wrappedFn, false); } catch(ex) { // handle an error trying to attach an event. If it fails // we need to clean up the cache this.lastError = ex; this.removeListener(el, sType, fn); return false; } } return true; }, /** * When using legacy events, the handler is routed to this object * so we can fire our custom listener stack. * @method fireLegacyEvent * @static * @private */ fireLegacyEvent: function(e, legacyIndex) { // this.logger.debug("fireLegacyEvent " + legacyIndex); var ok=true,le,lh,li,scope,ret; lh = legacyHandlers[legacyIndex]; for (var i=0,len=lh.length; i<len; ++i) { li = lh[i]; if ( li && li[this.WFN] ) { scope = li[this.ADJ_SCOPE]; ret = li[this.WFN].call(scope, e); ok = (ok && ret); } } // Fire the original handler if we replaced one. We fire this // after the other events to keep stopPropagation/preventDefault // that happened in the DOM0 handler from touching our DOM2 // substitute le = legacyEvents[legacyIndex]; if (le && le[2]) { le[2](e); } return ok; }, /** * Returns the legacy event index that matches the supplied * signature * @method getLegacyIndex * @static * @private */ getLegacyIndex: function(el, sType) { var key = this.generateId(el) + sType; if (typeof legacyMap[key] == "undefined") { return -1; } else { return legacyMap[key]; } }, /** * Logic that determines when we should automatically use legacy * events instead of DOM2 events. Currently this is limited to old * Safari browsers with a broken preventDefault * @method useLegacyEvent * @static * @private */ useLegacyEvent: function(el, sType) { if (this.webkit && ("click"==sType || "dblclick"==sType)) { var v = parseInt(this.webkit, 10); if (!isNaN(v) && v<418) { return true; } } return false; }, /** * Removes an event listener * * @method removeListener * * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to remove * the listener from. * @param {String} sType the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @return {boolean} true if the unbind was successful, false * otherwise. * @static */ removeListener: function(el, sType, fn) { var i, len, li; // The el argument can be a string if (typeof el == "string") { el = this.getEl(el); // The el argument can be an array of elements or element ids. } else if ( this._isValidCollection(el)) { var ok = true; for (i=0,len=el.length; i<len; ++i) { ok = ( this.removeListener(el[i], sType, fn) && ok ); } return ok; } if (!fn || !fn.call) { // this.logger.debug("Error, function is not valid " + fn); //return false; return this.purgeElement(el, false, sType); } if ("unload" == sType) { for (i=0, len=unloadListeners.length; i<len; i++) { li = unloadListeners[i]; if (li && li[0] == el && li[1] == sType && li[2] == fn) { //unloadListeners.splice(i, 1); unloadListeners[i]=null; return true; } } return false; } var cacheItem = null; // The index is a hidden parameter; needed to remove it from // the method signature because it was tempting users to // try and take advantage of it, which is not possible. var index = arguments[3]; if ("undefined" === typeof index) { index = this._getCacheIndex(el, sType, fn); } if (index >= 0) { cacheItem = listeners[index]; } if (!el || !cacheItem) { // this.logger.debug("cached listener not found"); return false; } // this.logger.debug("Removing handler: " + el + ", " + sType); if (this.useLegacyEvent(el, sType)) { var legacyIndex = this.getLegacyIndex(el, sType); var llist = legacyHandlers[legacyIndex]; if (llist) { for (i=0, len=llist.length; i<len; ++i) { li = llist[i]; if (li && li[this.EL] == el && li[this.TYPE] == sType && li[this.FN] == fn) { //llist.splice(i, 1); llist[i]=null; break; } } } } else { try { this._simpleRemove(el, sType, cacheItem[this.WFN], false); } catch(ex) { this.lastError = ex; return false; } } // removed the wrapped handler delete listeners[index][this.WFN]; delete listeners[index][this.FN]; //listeners.splice(index, 1); listeners[index]=null; return true; }, /** * Returns the event's target element. Safari sometimes provides * a text node, and this is automatically resolved to the text * node's parent so that it behaves like other browsers. * @method getTarget * @param {Event} ev the event * @param {boolean} resolveTextNode when set to true the target's * parent will be returned if the target is a * text node. @deprecated, the text node is * now resolved automatically * @return {HTMLElement} the event's target * @static */ getTarget: function(ev, resolveTextNode) { var t = ev.target || ev.srcElement; return this.resolveTextNode(t); }, /** * In some cases, some browsers will return a text node inside * the actual element that was targeted. This normalizes the * return value for getTarget and getRelatedTarget. * @method resolveTextNode * @param {HTMLElement} node node to resolve * @return {HTMLElement} the normized node * @static */ resolveTextNode: function(n) { try { if (n && 3 == n.nodeType) { return n.parentNode; } } catch(e) { } return n; }, /** * Returns the event's pageX * @method getPageX * @param {Event} ev the event * @return {int} the event's pageX * @static */ getPageX: function(ev) { var x = ev.pageX; if (!x && 0 !== x) { x = ev.clientX || 0; if ( this.isIE ) { x += this._getScrollLeft(); } } return x; }, /** * Returns the event's pageY * @method getPageY * @param {Event} ev the event * @return {int} the event's pageY * @static */ getPageY: function(ev) { var y = ev.pageY; if (!y && 0 !== y) { y = ev.clientY || 0; if ( this.isIE ) { y += this._getScrollTop(); } } return y; }, /** * Returns the pageX and pageY properties as an indexed array. * @method getXY * @param {Event} ev the event * @return {[x, y]} the pageX and pageY properties of the event * @static */ getXY: function(ev) { return [this.getPageX(ev), this.getPageY(ev)]; }, /** * Returns the event's related target * @method getRelatedTarget * @param {Event} ev the event * @return {HTMLElement} the event's relatedTarget * @static */ getRelatedTarget: function(ev) { var t = ev.relatedTarget; if (!t) { if (ev.type == "mouseout") { t = ev.toElement; } else if (ev.type == "mouseover") { t = ev.fromElement; } } return this.resolveTextNode(t); }, /** * Returns the time of the event. If the time is not included, the * event is modified using the current time. * @method getTime * @param {Event} ev the event * @return {Date} the time of the event * @static */ getTime: function(ev) { if (!ev.time) { var t = new Date().getTime(); try { ev.time = t; } catch(ex) { this.lastError = ex; return t; } } return ev.time; }, /** * Convenience method for stopPropagation + preventDefault * @method stopEvent * @param {Event} ev the event * @static */ stopEvent: function(ev) { this.stopPropagation(ev); this.preventDefault(ev); }, /** * Stops event propagation * @method stopPropagation * @param {Event} ev the event * @static */ stopPropagation: function(ev) { if (ev.stopPropagation) { ev.stopPropagation(); } else { ev.cancelBubble = true; } }, /** * Prevents the default behavior of the event * @method preventDefault * @param {Event} ev the event * @static */ preventDefault: function(ev) { if (ev.preventDefault) { ev.preventDefault(); } else { ev.returnValue = false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} boundEl the element the listener is attached to * @return {Event} the event * @static */ getEvent: function(e, boundEl) { var ev = e || window.event; if (!ev) { var c = this.getEvent.caller; while (c) { ev = c.arguments[0]; if (ev && Event == ev.constructor) { break; } c = c.caller; } } return ev; }, /** * Returns the charcode for an event * @method getCharCode * @param {Event} ev the event * @return {int} the event's charCode * @static */ getCharCode: function(ev) { var code = ev.keyCode || ev.charCode || 0; // webkit key normalization if (YAHOO.env.ua.webkit && (code in webkitKeymap)) { code = webkitKeymap[code]; } return code; }, /** * Locating the saved event handler data by function ref * * @method _getCacheIndex * @static * @private */ _getCacheIndex: function(el, sType, fn) { for (var i=0,len=listeners.length; i<len; ++i) { var li = listeners[i]; if ( li && li[this.FN] == fn && li[this.EL] == el && li[this.TYPE] == sType ) { return i; } } return -1; }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { var id = el.id; if (!id) { id = "yuievtautoid-" + counter; ++counter; el.id = id; } return id; }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @static * @private */ _isValidCollection: function(o) { try { return ( o && // o is something typeof o !== "string" && // o is not a string o.length && // o is indexed !o.tagName && // o is not an HTML element !o.alert && // o is not a window typeof o[0] !== "undefined" ); } catch(ex) { YAHOO.log("_isValidCollection error, assuming that " + " this is a cross frame problem and not a collection", "warn"); return false; } }, /** * @private * @property elCache * DOM element cache * @static * @deprecated Elements are not cached due to issues that arise when * elements are removed and re-added */ elCache: {}, /** * We cache elements bound by id because when the unload event * fires, we can no longer use document.getElementById * @method getEl * @static * @private * @deprecated Elements are not cached any longer */ getEl: function(id) { return (typeof id === "string") ? document.getElementById(id) : id; }, /** * Clears the element cache * @deprecated Elements are not cached any longer * @method clearCache * @static * @private */ clearCache: function() { }, /** * Custom event the fires when the dom is initially usable * @event DOMReadyEvent */ DOMReadyEvent: new YAHOO.util.CustomEvent("DOMReady", this), /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!loadComplete) { loadComplete = true; var EU = YAHOO.util.Event; // Just in case DOMReady did not go off for some reason EU._ready(); // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification EU._tryPreloadAttach(); } }, /** * Fires the DOMReady event listeners the first time the document is * usable. * @method _ready * @static * @private */ _ready: function(e) { var EU = YAHOO.util.Event; if (!EU.DOMReady) { EU.DOMReady=true; // Fire the content ready custom event EU.DOMReadyEvent.fire(); // Remove the DOMContentLoaded (FF/Opera) EU._simpleRemove(document, "DOMContentLoaded", EU._ready); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _tryPreloadAttach * @static * @private */ _tryPreloadAttach: function() { if (this.locked) { return false; } if (this.isIE) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. if (!this.DOMReady) { this.startInterval(); return false; } } this.locked = true; // this.logger.debug("tryPreloadAttach"); // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var tryAgain = !loadComplete; if (!tryAgain) { tryAgain = (retryCount > 0); } // onAvailable var notAvail = []; var executeItem = function (el, item) { var scope = el; if (item.override) { if (item.override === true) { scope = item.obj; } else { scope = item.override; } } item.fn.call(scope, item.obj); }; var i,len,item,el; // onAvailable for (i=0,len=onAvailStack.length; i<len; ++i) { item = onAvailStack[i]; if (item && !item.checkReady) { el = this.getEl(item.id); if (el) { executeItem(el, item); onAvailStack[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=onAvailStack.length; i<len; ++i) { item = onAvailStack[i]; if (item && item.checkReady) { el = this.getEl(item.id); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (loadComplete || el.nextSibling) { executeItem(el, item); onAvailStack[i] = null; } } else { notAvail.push(item); } } } retryCount = (notAvail.length === 0) ? 0 : retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here this.startInterval(); } else { clearInterval(this._interval); this._interval = null; } this.locked = false; return true; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} sType optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, sType) { var oEl = (YAHOO.lang.isString(el)) ? this.getEl(el) : el; var elListeners = this.getListeners(oEl, sType), i, len; if (elListeners) { for (i=0,len=elListeners.length; i<len ; ++i) { var l = elListeners[i]; this.removeListener(oEl, l.type, l.fn, l.index); } } if (recurse && oEl && oEl.childNodes) { for (i=0,len=oEl.childNodes.length; i<len ; ++i) { this.purgeElement(oEl.childNodes[i], recurse, sType); } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param sType {string} optional type of listener to return. If * left out, all listeners will be returned * @return {Object} the listener. Contains the following fields: * &nbsp;&nbsp;type: (string) the type of event * &nbsp;&nbsp;fn: (function) the callback supplied to addListener * &nbsp;&nbsp;obj: (object) the custom object supplied to addListener * &nbsp;&nbsp;adjust: (boolean|object) whether or not to adjust the default scope * &nbsp;&nbsp;scope: (boolean) the derived scope based on the adjust parameter * &nbsp;&nbsp;index: (int) its position in the Event util listener cache * @static */ getListeners: function(el, sType) { var results=[], searchLists; if (!sType) { searchLists = [listeners, unloadListeners]; } else if (sType === "unload") { searchLists = [unloadListeners]; } else { searchLists = [listeners]; } var oEl = (YAHOO.lang.isString(el)) ? this.getEl(el) : el; for (var j=0;j<searchLists.length; j=j+1) { var searchList = searchLists[j]; if (searchList && searchList.length > 0) { for (var i=0,len=searchList.length; i<len ; ++i) { var l = searchList[i]; if ( l && l[this.EL] === oEl && (!sType || sType === l[this.TYPE]) ) { results.push({ type: l[this.TYPE], fn: l[this.FN], obj: l[this.OBJ], adjust: l[this.OVERRIDE], scope: l[this.ADJ_SCOPE], index: i }); } } } } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { var EU = YAHOO.util.Event, i, j, l, len, index; // execute and clear stored unload listeners for (i=0,len=unloadListeners.length; i<len; ++i) { l = unloadListeners[i]; if (l) { var scope = window; if (l[EU.ADJ_SCOPE]) { if (l[EU.ADJ_SCOPE] === true) { scope = l[EU.UNLOAD_OBJ]; } else { scope = l[EU.ADJ_SCOPE]; } } l[EU.FN].call(scope, EU.getEvent(e, l[EU.EL]), l[EU.UNLOAD_OBJ] ); unloadListeners[i] = null; l=null; scope=null; } } unloadListeners = null; // Remove listeners to handle IE memory leaks //if (YAHOO.env.ua.ie && listeners && listeners.length > 0) { // 2.5.0 listeners are removed for all browsers again. FireFox preserves // at least some listeners between page refreshes, potentially causing // errors during page load (mouseover listeners firing before they // should if the user moves the mouse at the correct moment). if (listeners && listeners.length > 0) { j = listeners.length; while (j) { index = j-1; l = listeners[index]; if (l) { EU.removeListener(l[EU.EL], l[EU.TYPE], l[EU.FN], index); } j--; } l=null; } legacyEvents = null; EU._simpleRemove(window, "unload", EU._unload); }, /** * Returns scrollLeft * @method _getScrollLeft * @static * @private */ _getScrollLeft: function() { return this._getScroll()[1]; }, /** * Returns scrollTop * @method _getScrollTop * @static * @private */ _getScrollTop: function() { return this._getScroll()[0]; }, /** * Returns the scrollTop and scrollLeft. Used to calculate the * pageX and pageY in Internet Explorer * @method _getScroll * @static * @private */ _getScroll: function() { var dd = document.documentElement, db = document.body; if (dd && (dd.scrollTop || dd.scrollLeft)) { return [dd.scrollTop, dd.scrollLeft]; } else if (db) { return [db.scrollTop, db.scrollLeft]; } else { return [0, 0]; } }, /** * Used by old versions of CustomEvent, restored for backwards * compatibility * @method regCE * @private * @static * @deprecated still here for backwards compatibility */ regCE: function() { // does nothing }, /** * Adds a DOM event directly without the caching, cleanup, scope adj, etc * * @method _simpleAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} sType the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ _simpleAdd: function () { if (window.addEventListener) { return function(el, sType, fn, capture) { el.addEventListener(sType, fn, (capture)); }; } else if (window.attachEvent) { return function(el, sType, fn, capture) { el.attachEvent("on" + sType, fn); }; } else { return function(){}; } }(), /** * Basic remove listener * * @method _simpleRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} sType the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ _simpleRemove: function() { if (window.removeEventListener) { return function (el, sType, fn, capture) { el.removeEventListener(sType, fn, (capture)); }; } else if (window.detachEvent) { return function (el, sType, fn) { el.detachEvent("on" + sType, fn); }; } else { return function(){}; } }() }; }(); (function() { var EU = YAHOO.util.Event; /** * YAHOO.util.Event.on is an alias for addListener * @method on * @see addListener * @static */ EU.on = EU.addListener; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */ // Internet Explorer: use the readyState of a defered script. // This isolates what appears to be a safe moment to manipulate // the DOM prior to when the document's readyState suggests // it is safe to do so. if (EU.isIE) { // Process onAvailable/onContentReady items when when the // DOM is ready. YAHOO.util.Event.onDOMReady( YAHOO.util.Event._tryPreloadAttach, YAHOO.util.Event, true); EU._dri = setInterval(function() { var n = document.createElement('p'); try { // throws an error if doc is not ready n.doScroll('left'); clearInterval(EU._dri); EU._dri = null; EU._ready(); n = null; } catch (ex) { n = null; } }, EU.POLL_INTERVAL); // The document's readyState in Safari currently will // change to loaded/complete before images are loaded. } else if (EU.webkit && EU.webkit < 525) { EU._dri = setInterval(function() { var rs=document.readyState; if ("loaded" == rs || "complete" == rs) { clearInterval(EU._dri); EU._dri = null; EU._ready(); } }, EU.POLL_INTERVAL); // FireFox and Opera: These browsers provide a event for this // moment. The latest WebKit releases now support this event. } else { EU._simpleAdd(document, "DOMContentLoaded", EU._ready); } ///////////////////////////////////////////////////////////// EU._simpleAdd(window, "load", EU._load); EU._simpleAdd(window, "unload", EU._unload); EU._tryPreloadAttach(); })(); } /** * EventProvider is designed to be used with YAHOO.augment to wrap * CustomEvents in an interface that allows events to be subscribed to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * * @Class EventProvider */ YAHOO.util.EventProvider = function() { }; YAHOO.util.EventProvider.prototype = { /** * Private storage of custom events * @property __yui_events * @type Object[] * @private */ __yui_events: null, /** * Private storage of custom event subscribers * @property __yui_subscribers * @type Object[] * @private */ __yui_subscribers: null, /** * Subscribe to a CustomEvent by event type * * @method subscribe * @param p_type {string} the type, or name of the event * @param p_fn {function} the function to exectute when the event fires * @param p_obj {Object} An object to be passed along when the event * fires * @param p_override {boolean} If true, the obj passed in becomes the * execution scope of the listener */ subscribe: function(p_type, p_fn, p_obj, p_override) { this.__yui_events = this.__yui_events || {}; var ce = this.__yui_events[p_type]; if (ce) { ce.subscribe(p_fn, p_obj, p_override); } else { this.__yui_subscribers = this.__yui_subscribers || {}; var subs = this.__yui_subscribers; if (!subs[p_type]) { subs[p_type] = []; } subs[p_type].push( { fn: p_fn, obj: p_obj, override: p_override } ); } }, /** * Unsubscribes one or more listeners the from the specified event * @method unsubscribe * @param p_type {string} The type, or name of the event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param p_fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param p_obj {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {boolean} true if the subscriber was found and detached. */ unsubscribe: function(p_type, p_fn, p_obj) { this.__yui_events = this.__yui_events || {}; var evts = this.__yui_events; if (p_type) { var ce = evts[p_type]; if (ce) { return ce.unsubscribe(p_fn, p_obj); } } else { var ret = true; for (var i in evts) { if (YAHOO.lang.hasOwnProperty(evts, i)) { ret = ret && evts[i].unsubscribe(p_fn, p_obj); } } return ret; } return false; }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param p_type {string} The type, or name of the event */ unsubscribeAll: function(p_type) { return this.unsubscribe(p_type); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method createEvent * * @param p_type {string} the type, or name of the event * @param p_config {object} optional config params. Valid properties are: * * <ul> * <li> * scope: defines the default execution scope. If not defined * the default scope will be this instance. * </li> * <li> * silent: if true, the custom event will not generate log messages. * This is false by default. * </li> * <li> * onSubscribeCallback: specifies a callback to execute when the * event has a new subscriber. This will fire immediately for * each queued subscriber if any exist prior to the creation of * the event. * </li> * </ul> * * @return {CustomEvent} the custom event * */ createEvent: function(p_type, p_config) { this.__yui_events = this.__yui_events || {}; var opts = p_config || {}; var events = this.__yui_events; if (events[p_type]) { YAHOO.log("EventProvider createEvent skipped: '"+p_type+"' already exists"); } else { var scope = opts.scope || this; var silent = (opts.silent); var ce = new YAHOO.util.CustomEvent(p_type, scope, silent, YAHOO.util.CustomEvent.FLAT); events[p_type] = ce; if (opts.onSubscribeCallback) { ce.subscribeEvent.subscribe(opts.onSubscribeCallback); } this.__yui_subscribers = this.__yui_subscribers || {}; var qs = this.__yui_subscribers[p_type]; if (qs) { for (var i=0; i<qs.length; ++i) { ce.subscribe(qs[i].fn, qs[i].obj, qs[i].override); } } } return events[p_type]; }, /** * Fire a custom event by name. The callback functions will be executed * from the scope specified when the event was created, and with the * following parameters: * <ul> * <li>The first argument fire() was executed with</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * If the custom event has not been explicitly created, it will be * created now with the default config, scoped to the host object * @method fireEvent * @param p_type {string} the type, or name of the event * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. * @return {boolean} the return value from CustomEvent.fire * */ fireEvent: function(p_type, arg1, arg2, etc) { this.__yui_events = this.__yui_events || {}; var ce = this.__yui_events[p_type]; if (!ce) { YAHOO.log(p_type + "event fired before it was created."); return null; } var args = []; for (var i=1; i<arguments.length; ++i) { args.push(arguments[i]); } return ce.fire.apply(ce, args); }, /** * Returns true if the custom event of the provided type has been created * with createEvent. * @method hasEvent * @param type {string} the type, or name of the event */ hasEvent: function(type) { if (this.__yui_events) { if (this.__yui_events[type]) { return true; } } return false; } }; /** * KeyListener is a utility that provides an easy interface for listening for * keydown/keyup events fired against DOM elements. * @namespace YAHOO.util * @class KeyListener * @constructor * @param {HTMLElement} attachTo The element or element ID to which the key * event should be attached * @param {String} attachTo The element or element ID to which the key * event should be attached * @param {Object} keyData The object literal representing the key(s) * to detect. Possible attributes are * shift(boolean), alt(boolean), ctrl(boolean) * and keys(either an int or an array of ints * representing keycodes). * @param {Function} handler The CustomEvent handler to fire when the * key event is detected * @param {Object} handler An object literal representing the handler. * @param {String} event Optional. The event (keydown or keyup) to * listen for. Defaults automatically to keydown. * * @knownissue the "keypress" event is completely broken in Safari 2.x and below. * the workaround is use "keydown" for key listening. However, if * it is desired to prevent the default behavior of the keystroke, * that can only be done on the keypress event. This makes key * handling quite ugly. * @knownissue keydown is also broken in Safari 2.x and below for the ESC key. * There currently is no workaround other than choosing another * key to listen for. */ YAHOO.util.KeyListener = function(attachTo, keyData, handler, event) { if (!attachTo) { YAHOO.log("No attachTo element specified", "error"); } else if (!keyData) { YAHOO.log("No keyData specified", "error"); } else if (!handler) { YAHOO.log("No handler specified", "error"); } if (!event) { event = YAHOO.util.KeyListener.KEYDOWN; } /** * The CustomEvent fired internally when a key is pressed * @event keyEvent * @private * @param {Object} keyData The object literal representing the key(s) to * detect. Possible attributes are shift(boolean), * alt(boolean), ctrl(boolean) and keys(either an * int or an array of ints representing keycodes). */ var keyEvent = new YAHOO.util.CustomEvent("keyPressed"); /** * The CustomEvent fired when the KeyListener is enabled via the enable() * function * @event enabledEvent * @param {Object} keyData The object literal representing the key(s) to * detect. Possible attributes are shift(boolean), * alt(boolean), ctrl(boolean) and keys(either an * int or an array of ints representing keycodes). */ this.enabledEvent = new YAHOO.util.CustomEvent("enabled"); /** * The CustomEvent fired when the KeyListener is disabled via the * disable() function * @event disabledEvent * @param {Object} keyData The object literal representing the key(s) to * detect. Possible attributes are shift(boolean), * alt(boolean), ctrl(boolean) and keys(either an * int or an array of ints representing keycodes). */ this.disabledEvent = new YAHOO.util.CustomEvent("disabled"); if (typeof attachTo == 'string') { attachTo = document.getElementById(attachTo); } if (typeof handler == 'function') { keyEvent.subscribe(handler); } else { keyEvent.subscribe(handler.fn, handler.scope, handler.correctScope); } /** * Handles the key event when a key is pressed. * @method handleKeyPress * @param {DOMEvent} e The keypress DOM event * @param {Object} obj The DOM event scope object * @private */ function handleKeyPress(e, obj) { if (! keyData.shift) { keyData.shift = false; } if (! keyData.alt) { keyData.alt = false; } if (! keyData.ctrl) { keyData.ctrl = false; } // check held down modifying keys first if (e.shiftKey == keyData.shift && e.altKey == keyData.alt && e.ctrlKey == keyData.ctrl) { // if we pass this, all modifiers match var dataItem; if (keyData.keys instanceof Array) { for (var i=0;i<keyData.keys.length;i++) { dataItem = keyData.keys[i]; if (dataItem == e.charCode ) { keyEvent.fire(e.charCode, e); break; } else if (dataItem == e.keyCode) { keyEvent.fire(e.keyCode, e); break; } } } else { dataItem = keyData.keys; if (dataItem == e.charCode ) { keyEvent.fire(e.charCode, e); } else if (dataItem == e.keyCode) { keyEvent.fire(e.keyCode, e); } } } } /** * Enables the KeyListener by attaching the DOM event listeners to the * target DOM element * @method enable */ this.enable = function() { if (! this.enabled) { YAHOO.util.Event.addListener(attachTo, event, handleKeyPress); this.enabledEvent.fire(keyData); } /** * Boolean indicating the enabled/disabled state of the Tooltip * @property enabled * @type Boolean */ this.enabled = true; }; /** * Disables the KeyListener by removing the DOM event listeners from the * target DOM element * @method disable */ this.disable = function() { if (this.enabled) { YAHOO.util.Event.removeListener(attachTo, event, handleKeyPress); this.disabledEvent.fire(keyData); } this.enabled = false; }; /** * Returns a String representation of the object. * @method toString * @return {String} The string representation of the KeyListener */ this.toString = function() { return "KeyListener [" + keyData.keys + "] " + attachTo.tagName + (attachTo.id ? "[" + attachTo.id + "]" : ""); }; }; /** * Constant representing the DOM "keydown" event. * @property YAHOO.util.KeyListener.KEYDOWN * @static * @final * @type String */ YAHOO.util.KeyListener.KEYDOWN = "keydown"; /** * Constant representing the DOM "keyup" event. * @property YAHOO.util.KeyListener.KEYUP * @static * @final * @type String */ YAHOO.util.KeyListener.KEYUP = "keyup"; /** * keycode constants for a subset of the special keys * @property KEY * @static * @final */ YAHOO.util.KeyListener.KEY = { ALT : 18, BACK_SPACE : 8, CAPS_LOCK : 20, CONTROL : 17, DELETE : 46, DOWN : 40, END : 35, ENTER : 13, ESCAPE : 27, HOME : 36, LEFT : 37, META : 224, NUM_LOCK : 144, PAGE_DOWN : 34, PAGE_UP : 33, PAUSE : 19, PRINTSCREEN : 44, RIGHT : 39, SCROLL_LOCK : 145, SHIFT : 16, SPACE : 32, TAB : 9, UP : 38 }; YAHOO.register("event", YAHOO.util.Event, {version: "2.5.0", build: "895"});
alx/blogsfera
wp-includes/js/yui/2.5.0/build/event/event-debug.js
JavaScript
gpl-2.0
83,857
<? /**[N]** * JIBAS Education Community * Jaringan Informasi Bersama Antar Sekolah * * @version: 3.2 (September 03, 2013) * @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.net) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License **[N]**/ ?> <? require_once("../inc/config.php"); require_once("../inc/common.php"); require_once("../inc/db_functions.php"); require_once('siswa.class.php'); OpenDb(); $SP = new CSiswa(); $SP -> dep = $_REQUEST[dep]; $SP->GetTkt(); /* OpenDb(); $sql = "SELECT * FROM tingkat WHERE departemen='$_REQUEST[dep]' AND aktif = 1 ORDER BY tingkat"; $result = QueryDb($sql); $num = @mysql_num_rows($result); if ($num==0){ echo "<option value=''>Tidak ada Data</option>"; } else { while ($row = @mysql_fetch_array($result)){ if ($tkt == "") $tkt = $row[replid]; echo "<option value='$row[replid]' ".StringIsSelected($tkt,$row[replid]).">$row[tingkat]</option>"; } } */ ?>
nurulimamnotes/sistem-informasi-sekolah
jibas/ema/siswa/gettkt.php
PHP
gpl-2.0
1,631
/* * LFDD - Linux Firmware Debug Driver * File: libio.c * * Copyright (C) 2006 - 2010 Merck Hung <merckhung@gmail.com> * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/module.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/miscdevice.h> #include <linux/fcntl.h> #include <linux/proc_fs.h> #include <linux/delay.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/uaccess.h> #include <linux/version.h> #if LINUX_VERSION_CODE < KERNEL_VERSION(3, 4, 0) #include <asm/system.h> #endif #include <linux/highmem.h> #include "lfdd.h" extern spinlock_t lfdd_lock; unsigned char lfdd_io_read_byte( unsigned int addr ) { unsigned long flags; unsigned char value; spin_lock_irqsave( &lfdd_lock, flags ); value = inb( addr ); spin_unlock_irqrestore( &lfdd_lock, flags ); return value; } unsigned short lfdd_io_read_word( unsigned int addr ) { unsigned long flags; unsigned short value; spin_lock_irqsave( &lfdd_lock, flags ); value = inw( addr ); spin_unlock_irqrestore( &lfdd_lock, flags ); return value; } unsigned int lfdd_io_read_dword( unsigned int addr ) { unsigned long flags; unsigned int value; spin_lock_irqsave( &lfdd_lock, flags ); value = inl( addr ); spin_unlock_irqrestore( &lfdd_lock, flags ); return value; } void lfdd_io_write_byte( unsigned char value, unsigned int addr ) { unsigned long flags; spin_lock_irqsave( &lfdd_lock, flags ); outb( value, addr ); spin_unlock_irqrestore( &lfdd_lock, flags ); } void lfdd_io_write_word( unsigned short value, unsigned int addr ) { unsigned long flags; spin_lock_irqsave( &lfdd_lock, flags ); outw( value, addr ); spin_unlock_irqrestore( &lfdd_lock, flags ); } void lfdd_io_write_dword( unsigned int value, unsigned int addr ) { unsigned long flags; spin_lock_irqsave( &lfdd_lock, flags ); outl( value, addr ); spin_unlock_irqrestore( &lfdd_lock, flags ); } void lfdd_io_read_256byte( struct lfdd_io_t *pio ) { int i; unsigned long flags; spin_lock_irqsave( &lfdd_lock, flags ); for( i = 0 ; i < LFDD_MASSBUF_SIZE ; i++ ) { pio->mass_buf[ i ] = inb( pio->addr + i ); } spin_unlock_irqrestore( &lfdd_lock, flags ); }
denir-li/lfdk2
lfdd/libio.c
C
gpl-2.0
2,737
(function() { 'use strict'; angular.module('bonitasoft.ui.filters') .filter('lazyRef',function($log) { return function toLazyRef(bo,rel) { if(bo){ if(bo.links){ var result = bo.links.filter((ref) => ref.rel === rel); if(result[0] && result[0].href){ return '..' + result[0].href; } $log.warn('No lazy relation ',rel,' found'); } } return undefined; }; }); })();
bonitasoft/bonita-ui-designer
backend/artifact-builder/src/main/runtime/js/filters/lazyRef.filter.js
JavaScript
gpl-2.0
462
# # Copyright 2012 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # import tempfile import os import storage.fileUtils as fileUtils import testValidation from testrunner import VdsmTestCase as TestCaseBase class DirectFileTests(TestCaseBase): @classmethod def getConfigTemplate(cls): return {} def testRead(self): data = """Vestibulum. Libero leo nostra, pede nunc eu. Pellentesque platea lacus morbi nisl montes ve. Ac. A, consectetuer erat, justo eu. Elementum et, phasellus fames et rutrum donec magnis eu bibendum. Arcu, ante aliquam ipsum ut facilisis ad.""" srcFd, srcPath = tempfile.mkstemp() f = os.fdopen(srcFd, "wb") f.write(data) f.flush() f.close() with fileUtils.open_ex(srcPath, "dr") as f: self.assertEquals(f.read(), data) os.unlink(srcPath) def testSeekRead(self): data = """ Habitasse ipsum at fusce litora metus, placerat dui purus aenean ante, ve. Pede hymenaeos ut primis cum, rhoncus, lectus, nunc. Vestibulum curabitur vitae etiam magna auctor velit, mi tempus vivamus orci eros. Pellentesque curabitur risus fermentum eget. Elementum curae, donec nisl egestas ve, ut odio eu nunc elit felis primis id. Ridiculus metus morbi nulla erat, amet nisi. Amet ligula nisi, id penatibus risus in. Purus velit duis. Aenean eget, pellentesque eu rhoncus arcu et consectetuer laoreet, augue nisi dictum lacinia urna. Fermentum torquent. Ut interdum vivamus duis. Felis consequat nec pede. Orci sollicitudin parturient orci felis. Enim, diam velit sapien condimentum fames semper nibh. Integer at, egestas pede consectetuer ac augue pharetra dolor non placerat quisque id cursus ultricies. Ligula mi senectus sit. Habitasse. Integer sollicitudin dapibus cum quam. """ self.assertTrue(len(data) > 512) srcFd, srcPath = tempfile.mkstemp() f = os.fdopen(srcFd, "wb") f.write(data) f.flush() f.close() with fileUtils.open_ex(srcPath, "dr") as f: f.seek(512) self.assertEquals(f.read(), data[512:]) os.unlink(srcPath) def testWrite(self): data = """In ut non platea egestas, quisque magnis nunc nostra ac etiam suscipit nec integer sociosqu. Fermentum. Ante orci luctus, ipsum ullamcorper enim arcu class neque inceptos class. Ut, sagittis torquent, commodo facilisi.""" srcFd, srcPath = tempfile.mkstemp() os.close(srcFd) with fileUtils.open_ex(srcPath, "dw") as f: f.write(data) with fileUtils.open_ex(srcPath, "r") as f: self.assertEquals(f.read(len(data)), data) os.unlink(srcPath) def testSmallWrites(self): data = """ Aliquet habitasse tellus. Fringilla faucibus tortor parturient consectetuer sodales, venenatis platea habitant. Hendrerit nostra nunc odio. Primis porttitor consequat enim ridiculus. Taciti nascetur, nibh, convallis sit, cum dis mi. Nonummy justo odio cursus, ac hac curabitur nibh. Tellus. Montes, ut taciti orci ridiculus facilisis nunc. Donec. Risus adipiscing habitant donec vehicula non vitae class, porta vitae senectus. Nascetur felis laoreet integer, tortor ligula. Pellentesque vestibulum cras nostra. Ut sollicitudin posuere, per accumsan curabitur id, nisi fermentum vel, eget netus tristique per, donec, curabitur senectus ut fusce. A. Mauris fringilla senectus et eni facilisis magna inceptos eu, cursus habitant fringilla neque. Nibh. Elit facilisis sed, elit, nostra ve torquent dictumst, aenean sapien quam, habitasse in. Eu tempus aptent, diam, nisi risus pharetra, ac, condimentum orci, consequat mollis. Cras lacus augue ultrices proin fermentum nibh sed urna. Ve ipsum ultrices curae, feugiat faucibus proin et elementum vivamus, lectus. Torquent. Tempus facilisi. Cras suspendisse euismod consectetuer ornare nostra. Fusce amet cum amet diam. """ self.assertTrue(len(data) > 512) srcFd, srcPath = tempfile.mkstemp() os.close(srcFd) with fileUtils.open_ex(srcPath, "dw") as f: f.write(data[:512]) f.write(data[512:]) with fileUtils.open_ex(srcPath, "r") as f: self.assertEquals(f.read(len(data)), data) os.unlink(srcPath) def testUpdateRead(self): data = """ Aliquet. Aliquam eni ac nullam iaculis cras ante, adipiscing. Enim eget egestas pretium. Ultricies. Urna cubilia in, hac. Curabitur. Nibh. Purus ridiculus natoque sed id. Feugiat lacus quam, arcu maecenas nec egestas. Hendrerit duis nunc eget dis lacus porttitor per sodales class diam condimentum quisque condimentum nisi ligula. Dapibus blandit arcu nam non ac feugiat diam, dictumst. Ante eget fames eu penatibus in, porta semper accumsan adipiscing tellus in sagittis. Est parturient parturient mi fermentum commodo, per fermentum. Quis duis velit at quam risus mi. Facilisi id fames. Turpis, conubia rhoncus. Id. Elit eni tellus gravida, ut, erat morbi. Euismod, enim a ante vestibulum nibh. Curae curae primis vulputate adipiscing arcu ipsum suspendisse quam hymenaeos primis accumsan vestibulum. """ self.assertTrue(len(data) > 512) srcFd, srcPath = tempfile.mkstemp() os.close(srcFd) with fileUtils.open_ex(srcPath, "wd") as f: f.write(data[:512]) with fileUtils.open_ex(srcPath, "r+d") as f: f.seek(512) f.write(data[512:]) with fileUtils.open_ex(srcPath, "r") as f: self.assertEquals(f.read(len(data)), data) os.unlink(srcPath) class ChownTests(TestCaseBase): @testValidation.ValidateRunningAsRoot def test(self): targetId = 666 srcFd, srcPath = tempfile.mkstemp() os.close(srcFd) fileUtils.chown(srcPath, targetId, targetId) stat = os.stat(srcPath) self.assertTrue(stat.st_uid == stat.st_gid == targetId) os.unlink(srcPath) @testValidation.ValidateRunningAsRoot def testNames(self): # I convert to some id because I have no # idea what users are defined and what # there IDs are apart from root tmpId = 666 srcFd, srcPath = tempfile.mkstemp() os.close(srcFd) fileUtils.chown(srcPath, tmpId, tmpId) stat = os.stat(srcPath) self.assertTrue(stat.st_uid == stat.st_gid == tmpId) fileUtils.chown(srcPath, "root", "root") stat = os.stat(srcPath) self.assertTrue(stat.st_uid == stat.st_gid == 0) class CopyUserModeToGroupTests(TestCaseBase): MODE_MASK = 0777 # format: initialMode, expectedMode modesList = [ (0770, 0770), (0700, 0770), (0750, 0770), (0650, 0660), ] def testCopyUserModeToGroup(self): fd, path = tempfile.mkstemp() try: os.close(fd) for initialMode, expectedMode in self.modesList: os.chmod(path, initialMode) fileUtils.copyUserModeToGroup(path) self.assertEquals(os.stat(path).st_mode & self.MODE_MASK, expectedMode) finally: os.unlink(path)
edwardbadboy/vdsm-ubuntu
tests/fileUtilTests.py
Python
gpl-2.0
8,296
# dpeges Permet de générer et afficher une étiquette DPE et/ou GES
wilfryed/dpeges
README.md
Markdown
gpl-2.0
70
<?php /** * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; under version 2 * of the License (non-upgradable). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (c) 2013-2020 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT); * * @author Jérôme Bogaerts <jerome@taotesting.com> * @license GPLv2 */ namespace qtism\runtime\tests; use InvalidArgumentException; use qtism\common\collections\AbstractCollection; /** * A collection aiming at storing TimeConstraint objects. */ class TimeConstraintCollection extends AbstractCollection { /** * Checks whether or not $value is an instance of TimeConstraint. * * @param mixed $value * @throws InvalidArgumentException If $value is not an instance of TimeConstraint. */ protected function checkType($value) { if (!$value instanceof TimeConstraint) { $msg = 'TimeConstraintCollection objects only accept to store TimeConstraint objects.'; throw new InvalidArgumentException($msg); } } }
oat-sa/qti-sdk
src/qtism/runtime/tests/TimeConstraintCollection.php
PHP
gpl-2.0
1,611
/* Copyright 2015 Filosoft OÜ This file is part of Estnltk. It is available under the license of GPLv2 found in the top-level directory of this distribution and at http://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html . No part of this file, may be copied, modified, propagated, or distributed except according to the terms contained in the license. This software is distributed on an "AS IS" basis, without warranties or conditions of any kind, either express or implied. */ // (c) 1996-97 // 1999.12.21 TV kohendatud vastavask uuendatud X2TABEL klassile #define STRICT #include <memory.h> #include <string.h> #include <stdlib.h> #include "tmk2tx.h" #include "cxxbs3.h" // {{ (C)2002 bool MKTAc::Start(const long offSet, CPFSFile *in) { assert( EmptyClassInvariant() ); int i; in->Seek(offSet); if(in->ReadUnsigned<UB4,int>(&n)==false) return false; mktc=new MKTc[n]; for(i=0; i < n; i++) { if(mktc[i].Read(in)==false) return false; } assert( ClassInvariant() ); return true; } void MKTAc::Stop(void) { if(mktc) delete [] mktc; InitClassVariables(); assert( EmptyClassInvariant() ); } int MKTc::Compare(const MKTc *mktc, const int sortOrder) { FSUNUSED(sortOrder); assert( ClassInvariant() ); int i, cmp; if((cmp=n - mktc->n)!=0) return cmp; for(i=0; i < n; i++) { if((cmp=mkt1c[i].lgNr - mktc->mkt1c[i].lgNr)!=0) return cmp; if((cmp=mkt1c[i].tyMuut.Compare(mktc->mkt1c[i].tyMuut))!=0) return cmp; } return 0; // v�rdsed } bool MKTc::Read(CPFSFile *in) { if(in->ReadUnsigned<UB4,int>(&n)==false) { return false; } for(int i=0; i< n; i++) { if(in->ReadUnsigned<UB4,int>(&(mkt1c[i].lgNr))==false) { //ASSERT( false ); return false; } if(in->ReadString(&(mkt1c[i].tyMuut))==false) { //ASSERT( false ); return false; } if(mkt1c[i].tyMuut.GetLength()==0) { mkt1c[i].tyMuut=FSxSTR(""); } } assert( ClassInvariant() ); return true; } bool MKTc::Write(CPFSFile *out) { assert( ClassInvariant() ); if(out->WriteUnsigned<UB4,int>(n)==false) { assert( false ); return false; } for(int i=0; i < n; i++) { if(out->WriteUnsigned<UB4,int>(mkt1c[i].lgNr)==false) { assert( false ); return false; } // kirjutada koos '\0'-baidiga if(out->WriteStringB(&(mkt1c[i].tyMuut), true)==false) { assert( false ); return false; } } return true; } bool MKTc::WriteAsText(CPFSFile *out) { assert( ClassInvariant() ); CFSbaseSTRING xStr; int i; for(i=0; i < n; i++) { xStr.Format(FSxSTR("%d,%s "), mkt1c[i].lgNr, (const FSxCHAR *)(mkt1c[i].tyMuut)); if(out->WriteString((const FSxCHAR *)xStr, (int)(xStr.GetLength())-1)==false) // kirjuta ilma '\0'-baidita return false; } out->WriteStringB(FSxSTR("\n")); return true; }
estnltk/estnltk
src/etana/tmk2tx.cpp
C++
gpl-2.0
3,323
/* Webfont: Gentleman900-Heavy */@font-face { font-family: 'Gentleman900'; src: url('Gentleman-900-Heavy.eot'); /* IE9 Compat Modes */ src: url('Gentleman-900-Heavy.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('Gentleman-900-Heavy.woff') format('woff'), /* Modern Browsers */ url('Gentleman-900-Heavy.ttf') format('truetype'), /* Safari, Android, iOS */ url('Gentleman-900-Heavy.svg#Gentleman900-Heavy') format('svg'); /* Legacy iOS */ font-style: normal; font-weight: normal; text-rendering: optimizeLegibility; }
helgatheviking/sazerac
assets/fonts/Gentleman-900/Gentleman-900-Heavy.css
CSS
gpl-2.0
582
/* Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely. */ /* Simple program to test the SDL game controller routines */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "SDL.h" #ifdef __EMSCRIPTEN__ #include <emscripten/emscripten.h> #endif #ifndef SDL_JOYSTICK_DISABLED #ifdef __IPHONEOS__ #define SCREEN_WIDTH 480 #define SCREEN_HEIGHT 320 #else #define SCREEN_WIDTH 512 #define SCREEN_HEIGHT 320 #endif /* This is indexed by SDL_GameControllerButton. */ static const struct { int x; int y; } button_positions[] = { {387, 167}, /* A */ {431, 132}, /* B */ {342, 132}, /* X */ {389, 101}, /* Y */ {174, 132}, /* BACK */ {233, 132}, /* GUIDE */ {289, 132}, /* START */ {75, 154}, /* LEFTSTICK */ {305, 230}, /* RIGHTSTICK */ {77, 40}, /* LEFTSHOULDER */ {396, 36}, /* RIGHTSHOULDER */ {154, 188}, /* DPAD_UP */ {154, 249}, /* DPAD_DOWN */ {116, 217}, /* DPAD_LEFT */ {186, 217}, /* DPAD_RIGHT */ }; /* This is indexed by SDL_GameControllerAxis. */ static const struct { int x; int y; double angle; } axis_positions[] = { {74, 153, 270.0}, /* LEFTX */ {74, 153, 0.0}, /* LEFTY */ {306, 231, 270.0}, /* RIGHTX */ {306, 231, 0.0}, /* RIGHTY */ {91, -20, 0.0}, /* TRIGGERLEFT */ {375, -20, 0.0}, /* TRIGGERRIGHT */ }; SDL_Renderer *screen = NULL; SDL_bool retval = SDL_FALSE; SDL_bool done = SDL_FALSE; SDL_Texture *background, *button, *axis; static SDL_Texture * LoadTexture(SDL_Renderer *renderer, const char *file, SDL_bool transparent) { SDL_Surface *temp = NULL; SDL_Texture *texture = NULL; temp = SDL_LoadBMP(file); if (temp == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError()); } else { /* Set transparent pixel as the pixel at (0,0) */ if (transparent) { if (temp->format->BytesPerPixel == 1) { SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *)temp->pixels); } } texture = SDL_CreateTextureFromSurface(renderer, temp); if (!texture) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError()); } } if (temp) { SDL_FreeSurface(temp); } return texture; } void loop(void *arg) { SDL_Event event; int i; SDL_GameController *gamecontroller = (SDL_GameController *)arg; /* blank screen, set up for drawing this frame. */ SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); SDL_RenderCopy(screen, background, NULL, NULL); while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_CONTROLLERAXISMOTION: SDL_Log("Controller axis %s changed to %d\n", SDL_GameControllerGetStringForAxis((SDL_GameControllerAxis)event.caxis.axis), event.caxis.value); break; case SDL_CONTROLLERBUTTONDOWN: case SDL_CONTROLLERBUTTONUP: SDL_Log("Controller button %s %s\n", SDL_GameControllerGetStringForButton((SDL_GameControllerButton)event.cbutton.button), event.cbutton.state ? "pressed" : "released"); /* First button triggers a 0.5 second full strength rumble */ if (event.type == SDL_CONTROLLERBUTTONDOWN && event.cbutton.button == SDL_CONTROLLER_BUTTON_A) { SDL_GameControllerRumble(gamecontroller, 0xFFFF, 0xFFFF, 500); } break; case SDL_KEYDOWN: if (event.key.keysym.sym != SDLK_ESCAPE) { break; } /* Fall through to signal quit */ case SDL_QUIT: done = SDL_TRUE; break; default: break; } } /* Update visual controller state */ for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i) { if (SDL_GameControllerGetButton(gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) { const SDL_Rect dst = { button_positions[i].x, button_positions[i].y, 50, 50 }; SDL_RenderCopyEx(screen, button, NULL, &dst, 0, NULL, SDL_FLIP_NONE); } } for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; ++i) { const Sint16 deadzone = 8000; /* !!! FIXME: real deadzone */ const Sint16 value = SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i)); if (value < -deadzone) { const SDL_Rect dst = { axis_positions[i].x, axis_positions[i].y, 50, 50 }; const double angle = axis_positions[i].angle; SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, SDL_FLIP_NONE); } else if (value > deadzone) { const SDL_Rect dst = { axis_positions[i].x, axis_positions[i].y, 50, 50 }; const double angle = axis_positions[i].angle + 180.0; SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, SDL_FLIP_NONE); } } SDL_RenderPresent(screen); if (!SDL_GameControllerGetAttached(gamecontroller)) { done = SDL_TRUE; retval = SDL_TRUE; /* keep going, wait for reattach. */ } #ifdef __EMSCRIPTEN__ if (done) { emscripten_cancel_main_loop(); } #endif } SDL_bool WatchGameController(SDL_GameController * gamecontroller) { const char *name = SDL_GameControllerName(gamecontroller); const char *basetitle = "Game Controller Test: "; const size_t titlelen = SDL_strlen(basetitle) + SDL_strlen(name) + 1; char *title = (char *)SDL_malloc(titlelen); SDL_Window *window = NULL; retval = SDL_FALSE; done = SDL_FALSE; if (title) { SDL_snprintf(title, titlelen, "%s%s", basetitle, name); } /* Create a window to display controller state */ window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0); SDL_free(title); title = NULL; if (window == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError()); return SDL_FALSE; } screen = SDL_CreateRenderer(window, -1, 0); if (screen == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError()); SDL_DestroyWindow(window); return SDL_FALSE; } SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE); SDL_RenderClear(screen); SDL_RenderPresent(screen); SDL_RaiseWindow(window); /* scale for platforms that don't give you the window size you asked for. */ SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT); background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE); button = LoadTexture(screen, "button.bmp", SDL_TRUE); axis = LoadTexture(screen, "axis.bmp", SDL_TRUE); if (!background || !button || !axis) { SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); return SDL_FALSE; } SDL_SetTextureColorMod(button, 10, 255, 21); SDL_SetTextureColorMod(axis, 10, 255, 21); /* !!! FIXME: */ /*SDL_RenderSetLogicalSize(screen, background->w, background->h);*/ /* Print info about the controller we are watching */ SDL_Log("Watching controller %s\n", name ? name : "Unknown Controller"); /* Loop, getting controller events! */ #ifdef __EMSCRIPTEN__ emscripten_set_main_loop_arg(loop, gamecontroller, 0, 1); #else while (!done) { loop(gamecontroller); } #endif SDL_DestroyRenderer(screen); screen = NULL; background = NULL; button = NULL; axis = NULL; SDL_DestroyWindow(window); return retval; } int main(int argc, char *argv[]) { int i; int nController = 0; int retcode = 0; char guid[64]; SDL_GameController *gamecontroller; /* Enable standard application logging */ SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); /* Initialize SDL (Note: video is required to start event loop) */ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER ) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError()); return 1; } SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt"); /* Print information about the mappings */ if (!argv[1]) { SDL_Log("Supported mappings:\n"); for (i = 0; i < SDL_GameControllerNumMappings(); ++i) { char *mapping = SDL_GameControllerMappingForIndex(i); if (mapping) { SDL_Log("\t%s\n", mapping); SDL_free(mapping); } } SDL_Log("\n"); } /* Print information about the controller */ for (i = 0; i < SDL_NumJoysticks(); ++i) { const char *name; const char *description; SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(i), guid, sizeof (guid)); if ( SDL_IsGameController(i) ) { nController++; name = SDL_GameControllerNameForIndex(i); description = "Controller"; } else { name = SDL_JoystickNameForIndex(i); description = "Joystick"; } SDL_Log("%s %d: %s (guid %s, VID 0x%.4x, PID 0x%.4x)\n", description, i, name ? name : "Unknown", guid, SDL_JoystickGetDeviceVendor(i), SDL_JoystickGetDeviceProduct(i)); } SDL_Log("There are %d game controller(s) attached (%d joystick(s))\n", nController, SDL_NumJoysticks()); if (argv[1]) { SDL_bool reportederror = SDL_FALSE; SDL_bool keepGoing = SDL_TRUE; SDL_Event event; int device = atoi(argv[1]); if (device >= SDL_NumJoysticks()) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%i is an invalid joystick index.\n", device); retcode = 1; } else { SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(device), guid, sizeof (guid)); SDL_Log("Attempting to open device %i, guid %s\n", device, guid); gamecontroller = SDL_GameControllerOpen(device); if (gamecontroller != NULL) { SDL_assert(SDL_GameControllerFromInstanceID(SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontroller))) == gamecontroller); } while (keepGoing) { if (gamecontroller == NULL) { if (!reportederror) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open gamecontroller %d: %s\n", device, SDL_GetError()); retcode = 1; keepGoing = SDL_FALSE; reportederror = SDL_TRUE; } } else { reportederror = SDL_FALSE; keepGoing = WatchGameController(gamecontroller); SDL_GameControllerClose(gamecontroller); } gamecontroller = NULL; if (keepGoing) { SDL_Log("Waiting for attach\n"); } while (keepGoing) { SDL_WaitEvent(&event); if ((event.type == SDL_QUIT) || (event.type == SDL_FINGERDOWN) || (event.type == SDL_MOUSEBUTTONDOWN)) { keepGoing = SDL_FALSE; } else if (event.type == SDL_CONTROLLERDEVICEADDED) { gamecontroller = SDL_GameControllerOpen(event.cdevice.which); if (gamecontroller != NULL) { SDL_assert(SDL_GameControllerFromInstanceID(SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontroller))) == gamecontroller); } break; } } } } } SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER); return retcode; } #else int main(int argc, char *argv[]) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n"); return 1; } #endif /* vi: set ts=4 sw=4 expandtab: */
h4mu/rott94
android/app/jni/SDL/test/testgamecontroller.c
C
gpl-2.0
12,682
showWord(["","1. a. Ki karesan. Magali se yon fi ki dous anpil. 2. Ki gen gou sikre. Mango sa a dous kou siwo, ou wè se mango miska vre. Ou met twòp sik nan labouyi a, li twò dous, mwen pa kapab manje l. 3. n. Manje ki fèt ak lèt epi sik. Mwen ta manje yon ti dous lèt." ])
georgejhunt/HaitiDictionary.activity
data/words/dous.js
JavaScript
gpl-2.0
279
/************************************************************************* * password functions *************************************************************************/ #include <errno.h> #include <nss.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "exfiles-util-pwd.h" #include "config.h" /* * Utility for allocating memory for items in struct passwd based on string * array from strsplit. */ int exfiles_alloc_passwd_from_pw_entry(struct passwd *pwbuf, char **pw_entry) { /* Allocate storage for each string */ pwbuf->pw_name = malloc(sizeof(char) *(strlen(pw_entry[0])+1)); pwbuf->pw_passwd = malloc(sizeof(char) *(strlen(pw_entry[1])+1)); pwbuf->pw_gecos = malloc(sizeof(char) *(strlen(pw_entry[4])+1)); pwbuf->pw_dir = malloc(sizeof(char) *(strlen(pw_entry[5])+1)); pwbuf->pw_shell = malloc(sizeof(char) *(strlen(pw_entry[6])+1)); if ( pwbuf->pw_name == NULL || pwbuf->pw_passwd == NULL || pwbuf->pw_gecos == NULL || pwbuf->pw_dir == NULL || pwbuf->pw_shell == NULL ) return -1; return 0; } /* * Utility to handle copying items from the pw_entry array into the struct * passwd. Note that it should also be possible to simply update the struct * passwd pointers. Consider that for future optimization. */ int exfiles_copy_passwd_from_pw_entry(struct passwd *pwbuf, char **pw_entry) { int tmplen = 0; /* temp var for length of each string */ /* Copy username */ tmplen = strlen(pw_entry[0]); strncpy(pwbuf->pw_name, pw_entry[0], tmplen+1); /* FIXME Why did I put this in? */ if (tmplen != strlen(pw_entry[0])) return -1; /* Copy password */ tmplen = strlen(pw_entry[1]); strncpy(pwbuf->pw_passwd, pw_entry[1], tmplen+1); if (tmplen != strlen(pw_entry[1])) return -1; /* Copy and convert to int UID and GID */ pwbuf->pw_uid = (uid_t)atoi(pw_entry[2]); pwbuf->pw_gid = (gid_t)atoi(pw_entry[3]); /* Copy GECOS field */ tmplen = strlen(pw_entry[4]); strncpy(pwbuf->pw_gecos, pw_entry[4], tmplen+1); if (tmplen != strlen(pw_entry[4])) return -1; /* Copy home directory */ tmplen = strlen(pw_entry[5]); strncpy(pwbuf->pw_dir, pw_entry[5], tmplen+1); if (tmplen != strlen(pw_entry[5])) return -1; /* Copy Shell */ tmplen = strlen(pw_entry[6]); strncpy(pwbuf->pw_shell, pw_entry[6], tmplen+1); if (tmplen != strlen(pw_entry[6])) return -1; return 0; } /* * Utility for destroying the contents of a struct passwd. */ void exfiles_passwd_destroy(struct passwd *pwbuf) { if ( NULL != pwbuf ) { if ( NULL != pwbuf->pw_shell ) { free(pwbuf->pw_shell); pwbuf->pw_shell = NULL; } if ( NULL != pwbuf->pw_dir ) { free(pwbuf->pw_dir); pwbuf->pw_dir = NULL; } if ( NULL != pwbuf->pw_gecos ) { free(pwbuf->pw_gecos); pwbuf->pw_gecos = NULL; } if ( NULL != pwbuf->pw_passwd ) { free(pwbuf->pw_passwd); pwbuf->pw_passwd = NULL; } if ( NULL != pwbuf->pw_name ) { free(pwbuf->pw_name); pwbuf->pw_name = NULL; } /* This often wraps around and results in a large int that is * usually treated as "nobody"; rather of an arbitrary thing to do, * but it at least is better than defaulting to root's ID (0) */ pwbuf->pw_uid = (uid_t) -1; pwbuf->pw_gid = (gid_t) -1; } } /* * User-friendly print of passwd struct contents. */ int pretty_print_passwd_struct(FILE *outstream, const struct passwd *pwbuf) { return fprintf(outstream, "Username: '%s'\n" "Password: '%s'\n" "UID: '%d'\n" "GID: '%d'\n" "GECOS: '%s'\n" "Home dir: '%s'\n" "Shell: '%s'\n", pwbuf->pw_name, pwbuf->pw_passwd, (int)pwbuf->pw_uid, (int)pwbuf->pw_gid, pwbuf->pw_gecos, pwbuf->pw_dir, pwbuf->pw_shell ); } /* * passwd file-like output */ int print_passwd_struct(FILE *outstream, const struct passwd *pwbuf) { return fprintf(outstream, "%s:%s:%d:%d:%s:%s:%s\n", pwbuf->pw_name, pwbuf->pw_passwd, (int)pwbuf->pw_uid, (int)pwbuf->pw_gid, pwbuf->pw_gecos, pwbuf->pw_dir, pwbuf->pw_shell); } /* * Deep compare of passwd structures. There really isn't a necessarily * logical way to order them and we really need this for tests, so just return * true or false. (erm, 1 or 0) */ int exfiles_passwd_cmp(const struct passwd *pwbuf1, const struct passwd *pwbuf2) { return (0 == strcmp(pwbuf1->pw_name, pwbuf2->pw_name) ) && (0 == strcmp(pwbuf1->pw_passwd, pwbuf2->pw_passwd) ) && (0 == strcmp(pwbuf1->pw_gecos, pwbuf2->pw_gecos) ) && (0 == strcmp(pwbuf1->pw_dir, pwbuf2->pw_dir) ) && (0 == strcmp(pwbuf1->pw_shell, pwbuf2->pw_shell) ) && (pwbuf1->pw_uid == pwbuf2->pw_uid) && (pwbuf1->pw_gid == pwbuf2->pw_gid) ; }
wcooley/nss_exfiles
src/exfiles-util-pwd.c
C
gpl-2.0
5,396
try: from django.conf.urls import url, patterns except ImportError: from django.conf.urls.defaults import url, patterns from actstream import feeds from actstream import views from django.contrib.auth.decorators import login_required urlpatterns = patterns('actstream.views', # Syndication Feeds url(r'^feed/(?P<content_type_id>\d+)/(?P<object_id>\d+)/atom/$', feeds.AtomObjectActivityFeed(), name='actstream_object_feed_atom'), url(r'^feed/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$', feeds.ObjectActivityFeed(), name='actstream_object_feed'), url(r'^feed/(?P<content_type_id>\d+)/atom/$', feeds.AtomModelActivityFeed(), name='actstream_model_feed_atom'), url(r'^feed/(?P<content_type_id>\d+)/(?P<object_id>\d+)/as/$', feeds.ActivityStreamsObjectActivityFeed(), name='actstream_object_feed_as'), url(r'^feed/(?P<content_type_id>\d+)/$', feeds.ModelActivityFeed(), name='actstream_model_feed'), url(r'^feed/$', feeds.UserActivityFeed(), name='actstream_feed'), url(r'^feed/atom/$', feeds.AtomUserActivityFeed(), name='actstream_feed_atom'), # Follow/Unfollow API url(r'^follow/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$', 'follow_unfollow', name='actstream_follow'), url(r'^follow_all/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$', 'follow_unfollow', {'actor_only': False}, name='actstream_follow_all'), url(r'^unfollow/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$', 'follow_unfollow', {'do_follow': False}, name='actstream_unfollow'), # Follower and Actor lists url(r'^followers/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$', 'followers', name='actstream_followers'), url(r'^actors/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$', 'actor', name='actstream_actor'), url(r'^actors/(?P<content_type_id>\d+)/$', 'model', name='actstream_model'), url(r'^new_wall_post/$', view=login_required (views.new_wall_post), name='new_wall_post'), url(r'^detail/(?P<action_id>\d+)/$', view=login_required(views.detail), name='actstream_detail'), url(r'^(?P<username>[-\w]+)/$', view=login_required (views.user), name='actstream_user'), url(r'^$', view=login_required (views.stream), name='actstream'), url(r'^new_group_post', view=login_required (views.new_group_post), name='new_group_post'), )
meletakis/collato
esn/actstream/urls.py
Python
gpl-2.0
2,399
<?php require_once ("./lib/defines.php"); require_once ("./lib/module.access.php"); require_once ("a2blib/Form.inc.php"); require_once ("a2blib/Class.HelpElem.inc.php"); require_once ("a2blib/Form/Class.TimeField.inc.php"); require_once ("a2blib/Form/Class.SqlRefField.inc.php"); require_once ("a2blib/Form/Class.VolField.inc.php"); $menu_section='menu_ratecard'; HelpElem::DoHelp(gettext("Tariff plan is the table of <b>Buying</b> rates, as given by our providers.")); $HD_Form= new FormHandler('cc_tariffplan',_("Tariff Plans"),_("Tariff plan")); $HD_Form->checkRights(ACX_RATECARD); $HD_Form->init(); $PAGE_ELEMS[] = &$HD_Form; $PAGE_ELEMS[] = new AddNewButton($HD_Form); $HD_Form->model[] = new PKeyFieldEH(_("ID"),'id'); $HD_Form->model[] = new TextFieldEH(_("Name"),'tariffname'); $HD_Form->model[] = new TextAreaField(_("Description"),'description'); $HD_Form->model[] = new IntField(_("Metric"),'metric',_("Weight of plan, lower metrics will be preferred at the rate engine.")); end($HD_Form->model)->def_value=10; $HD_Form->model[] = new SqlRefField(_("Trunk"),'trunk','cc_trunk','id','trunkcode', _("Trunk used by these rates")); $HD_Form->model[] = new DateTimeField(_("Start date"), "start_date", _("Date these rates are valid from")); end($HD_Form->model)->def_date='+1 day'; $HD_Form->model[] = new DateTimeField(_("Stop date"), "stop_date", _("Date these rates are valid until.")); end($HD_Form->model)->def_date='+1 month 1 day'; $HD_Form->model[] = dontList(new TimeOWField(_("Period begin"), "starttime", _("Time of week the rate starts to apply"))); end($HD_Form->model)->def_value=0; $HD_Form->model[] = dontList(new TimeOWField(_("Period end"), "endtime", _("Time of week the rate stops apply"))); end($HD_Form->model)->def_value=10079; //$HD_Form->model[] = new TextField(_("xx"),'xx'); $HD_Form->model[] = new SecVolField(_("Seconds used"), "secondusedreal", _("Duration of calls through trunk.")); end($HD_Form->model)->fieldacr=_("Used"); $HD_Form->model[] = dontList(new SqlRefFieldN(_("Negotiation Currency"),'neg_currency','cc_currencies','id','name', _("The currency credit is at. Whenever a call is made, the plan is charged with an amount at that currency."))); $HD_Form->model[] = new FloatVolField(_("Credit"),'credit',_("Money remaining in deal with provider.")); $HD_Form->model[] = new DelBtnField(); require("PP_page.inc.php"); //// *-* if (false) { //TODO: styles ?> <table align="center" border="0" width="65%" cellspacing="1" cellpadding="2"> <tbody> <form name="updateForm" action="tariffplan_export.php" method="post"> <INPUT type="hidden" name="id_tp" value="<?= $id_tp ?>"> <tr> <td>#<?= $id_tp ?> <?= _("Type"); ?>&nbsp;: <select name="export_style" size="1" class="form_input_select"> <option value='peer-full-csv' selected><?= _("Peer Full CSV") ?></option> <option value='peer-full-xml'><?= _("Peer Full XML") ?></option> <option value='client-csv' ><?= _("Client CSV") ?></option> </select> </td> </tr> <tr><td align="right" > <input class="form_input_button" value="<?= _("EXPORT RATECARD");?>" type="submit"> </td> </tr> </form> </table> <?php } ?>
xrg/a2billing
A2Billing_UI/A2B_entity_tariffplan.php
PHP
gpl-2.0
3,152
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>tbb::auto_partitioner Class Reference</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.7 --> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li id="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> </ul></div> <div class="tabs"> <ul> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul></div> <div class="nav"> <a class="el" href="a00428.html">tbb</a>::<a class="el" href="a00269.html">auto_partitioner</a></div> <h1>tbb::auto_partitioner Class Reference<br> <small> [<a class="el" href="a00442.html">Algorithms</a>]</small> </h1><!-- doxytag: class="tbb::auto_partitioner" -->An auto partitioner. <a href="#_details">More...</a> <p> <code>#include &lt;partitioner.h&gt;</code> <p> <a href="a00105.html">List of all members.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Friends</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="5f730f70d21df405adaebfc2018f59cd"></a><!-- doxytag: member="tbb::auto_partitioner::serial::interface6::start_for" ref="5f730f70d21df405adaebfc2018f59cd" args="" --> class&nbsp;</td><td class="memItemRight" valign="bottom"><b>serial::interface6::start_for</b></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="8a4cd0ffed4fad0d9af2c5efdaf586a8"></a><!-- doxytag: member="tbb::auto_partitioner::interface6::internal::start_for" ref="8a4cd0ffed4fad0d9af2c5efdaf586a8" args="" --> class&nbsp;</td><td class="memItemRight" valign="bottom"><b>interface6::internal::start_for</b></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="86f0750233dd6c83b65fb684338fd09f"></a><!-- doxytag: member="tbb::auto_partitioner::interface6::internal::start_reduce" ref="86f0750233dd6c83b65fb684338fd09f" args="" --> class&nbsp;</td><td class="memItemRight" valign="bottom"><b>interface6::internal::start_reduce</b></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="76d97ae6ad98db0acfc8ed8cb7c76705"></a><!-- doxytag: member="tbb::auto_partitioner::internal::start_scan" ref="76d97ae6ad98db0acfc8ed8cb7c76705" args="" --> class&nbsp;</td><td class="memItemRight" valign="bottom"><b>internal::start_scan</b></td></tr> </table> <hr><a name="_details"></a><h2>Detailed Description</h2> An auto partitioner. <p> The range is initial divided into several large chunks. Chunks are further subdivided into smaller pieces if demand detected and they are divisible. <p> <hr>The documentation for this class was generated from the following file:<ul> <li>partitioner.h</ul> <hr> <p></p> Copyright &copy; 2005-2013 Intel Corporation. All Rights Reserved. <p></p> Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are registered trademarks or trademarks of Intel Corporation or its subsidiaries in the United States and other countries. <p></p> * Other names and brands may be claimed as the property of others.
MarkusSR1984/Malloctest
doc/html/a00269.html
HTML
gpl-2.0
3,738
class Song(object): def __init__(self, lyrics): self.lyrics = lyrics def sing_me_a_song(self): for line in self.lyrics: print line happy_bday = Song(["Happy birthday to you", "I don't want to get sued", "So I'll stop right here"]) bulls_on_parade = Song(["They rally around tha family", "With pockets full of shells"]) happy_bday.sing_me_a_song() bulls_on_parade.sing_me_a_song()
mshcruz/LearnPythonTheHardWay
ex40.py
Python
gpl-2.0
484
package generated.test39; import junit.framework.*; import java.util.*; /** * Wrapper test * * @author Vaidas Gasiunas */ public class VCTestCase extends TestCase { public VCTestCase() { super("test"); } public static final String expectedResult = "RoleB<RoleA[RoleA:0(ClassA)]; RoleA:0(ClassA)"; public void test() { System.out.println("-------> VCTest 39: Wrapper test: start"); final ClassB b = new ClassB(); final ModelD d = new ModelD(); d.RoleB db = d.RoleB(b); String result = db.getId() + "; " + db.getA().getId(); System.out.println(result); assertEquals(expectedResult, result); System.out.println("-------> VCTest 39: end"); } } public class ClassA { public String getId() { return "ClassA"; } } public class ClassB { private ClassA a; public ClassB() { a = new ClassA(); } public String getId() { return "ClassB"; } public ClassA getA() { return a; } } public cclass ModelA { public cclass RoleA { public String getId() { return "RoleA"; } } public cclass RoleB extends RoleA { public String getId() { return "RoleB<" + super.getId(); } public ModelA.RoleA getA() { return null; } } } public cclass ModelB extends ModelA { public cclass BindAA extends RoleA wraps ClassA { protected static int sequence = 0; protected int _id; public BindAA() { _id = sequence++; } public String getId() { return super.getId() + ":" + _id + "(" + wrappee.getId() + ")"; } } public cclass RoleB wraps ClassB { public RoleA getA() { return ModelB.this.BindAA(wrappee.getA()); } } } public cclass ModelC extends ModelA { public cclass RoleB { public String getId() { return super.getId() + "[" + getA().getId() + "]"; } } } public cclass ModelD extends ModelB & ModelC { }
tud-stg-lang/caesar-compiler
test/VirtualClassesTests/test39/VCTestCase.java
Java
gpl-2.0
1,843
/* * Copyright (C) 2010, 2012-2014 ARM Limited. All rights reserved. * * This program is free software and is provided to you under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence. * * A copy of the licence is included with the program, and can also be obtained from Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file mali_osk_irq.c * Implementation of the OS abstraction layer for the kernel device driver */ #include <linux/slab.h> /* For memory allocation */ #include <linux/interrupt.h> #include <linux/wait.h> #include <linux/sched.h> #include "mali_osk.h" #include "mali_kernel_common.h" typedef struct _mali_osk_irq_t_struct { u32 irqnum; void *data; _mali_osk_irq_uhandler_t uhandler; } mali_osk_irq_object_t; typedef irqreturn_t (*irq_handler_func_t)(int, void *, struct pt_regs *); static irqreturn_t irq_handler_upper_half (int port_name, void* dev_id ); /* , struct pt_regs *regs*/ #if defined(DEBUG) #if 0 struct test_interrupt_data { _mali_osk_irq_ack_t ack_func; void *probe_data; mali_bool interrupt_received; wait_queue_head_t wq; }; static irqreturn_t test_interrupt_upper_half(int port_name, void *dev_id) { irqreturn_t ret = IRQ_NONE; struct test_interrupt_data *data = (struct test_interrupt_data *)dev_id; if (_MALI_OSK_ERR_OK == data->ack_func(data->probe_data)) { data->interrupt_received = MALI_TRUE; wake_up(&data->wq); ret = IRQ_HANDLED; } return ret; } static _mali_osk_errcode_t test_interrupt(u32 irqnum, _mali_osk_irq_trigger_t trigger_func, _mali_osk_irq_ack_t ack_func, void *probe_data, const char *description) { unsigned long irq_flags = 0; struct test_interrupt_data data = { .ack_func = ack_func, .probe_data = probe_data, .interrupt_received = MALI_FALSE, }; #if defined(CONFIG_MALI_SHARED_INTERRUPTS) irq_flags |= IRQF_SHARED; #endif /* defined(CONFIG_MALI_SHARED_INTERRUPTS) */ if (0 != request_irq(irqnum, test_interrupt_upper_half, irq_flags, description, &data)) { MALI_DEBUG_PRINT(2, ("Unable to install test IRQ handler for core '%s'\n", description)); return _MALI_OSK_ERR_FAULT; } init_waitqueue_head(&data.wq); trigger_func(probe_data); wait_event_timeout(data.wq, data.interrupt_received, 100); free_irq(irqnum, &data); if (data.interrupt_received) { MALI_DEBUG_PRINT(3, ("%s: Interrupt test OK\n", description)); return _MALI_OSK_ERR_OK; } else { MALI_PRINT_ERROR(("%s: Failed interrupt test on %u\n", description, irqnum)); return _MALI_OSK_ERR_FAULT; } } #endif #endif /* defined(DEBUG) */ _mali_osk_irq_t *_mali_osk_irq_init( u32 irqnum, _mali_osk_irq_uhandler_t uhandler, void *int_data, _mali_osk_irq_trigger_t trigger_func, _mali_osk_irq_ack_t ack_func, void *probe_data, const char *description ) { mali_osk_irq_object_t *irq_object; unsigned long irq_flags = 0; #if defined(CONFIG_MALI_SHARED_INTERRUPTS) irq_flags |= IRQF_SHARED; #endif /* defined(CONFIG_MALI_SHARED_INTERRUPTS) */ irq_object = kmalloc(sizeof(mali_osk_irq_object_t), GFP_KERNEL); if (NULL == irq_object) { return NULL; } if (-1 == irqnum) { /* Probe for IRQ */ if ( (NULL != trigger_func) && (NULL != ack_func) ) { unsigned long probe_count = 3; _mali_osk_errcode_t err; int irq; MALI_DEBUG_PRINT(2, ("Probing for irq\n")); do { unsigned long mask; mask = probe_irq_on(); trigger_func(probe_data); _mali_osk_time_ubusydelay(5); irq = probe_irq_off(mask); err = ack_func(probe_data); } while (irq < 0 && (err == _MALI_OSK_ERR_OK) && probe_count--); if (irq < 0 || (_MALI_OSK_ERR_OK != err)) irqnum = -1; else irqnum = irq; } else irqnum = -1; /* no probe functions, fault */ if (-1 != irqnum) { /* found an irq */ MALI_DEBUG_PRINT(2, ("Found irq %d\n", irqnum)); } else { MALI_DEBUG_PRINT(2, ("Probe for irq failed\n")); } } irq_object->irqnum = irqnum; irq_object->uhandler = uhandler; irq_object->data = int_data; if (-1 == irqnum) { MALI_DEBUG_PRINT(2, ("No IRQ for core '%s' found during probe\n", description)); kfree(irq_object); return NULL; } #if defined(DEBUG) #if 0 /* Verify that the configured interrupt settings are working */ if (_MALI_OSK_ERR_OK != test_interrupt(irqnum, trigger_func, ack_func, probe_data, description)) { MALI_DEBUG_PRINT(2, ("Test of IRQ handler for core '%s' failed\n", description)); kfree(irq_object); return NULL; } #endif #endif if (0 != request_irq(irqnum, irq_handler_upper_half, IRQF_TRIGGER_LOW, description, irq_object)) { MALI_DEBUG_PRINT(2, ("Unable to install IRQ handler for core '%s'\n", description)); kfree(irq_object); return NULL; } return irq_object; } void _mali_osk_irq_term( _mali_osk_irq_t *irq ) { mali_osk_irq_object_t *irq_object = (mali_osk_irq_object_t *)irq; free_irq(irq_object->irqnum, irq_object); kfree(irq_object); } /** This function is called directly in interrupt context from the OS just after * the CPU get the hw-irq from mali, or other devices on the same IRQ-channel. * It is registered one of these function for each mali core. When an interrupt * arrives this function will be called equal times as registered mali cores. * That means that we only check one mali core in one function call, and the * core we check for each turn is given by the \a dev_id variable. * If we detect an pending interrupt on the given core, we mask the interrupt * out by settging the core's IRQ_MASK register to zero. * Then we schedule the mali_core_irq_handler_bottom_half to run as high priority * work queue job. */ static irqreturn_t irq_handler_upper_half (int port_name, void* dev_id ) /* , struct pt_regs *regs*/ { irqreturn_t ret = IRQ_NONE; mali_osk_irq_object_t *irq_object = (mali_osk_irq_object_t *)dev_id; if (_MALI_OSK_ERR_OK == irq_object->uhandler(irq_object->data)) { ret = IRQ_HANDLED; } return ret; }
stargo/android_kernel_amazon_ford
drivers/misc/mediatek/gpu/mt8127/mali/mali/linux/mali_osk_irq.c
C
gpl-2.0
6,060
// -*- C++ -*- // Copyright (C) 2005, 2006 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 2, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // As a special exception, you may use this file as part of a free // software library without restriction. Specifically, if other files // instantiate templates or use macros or inline functions from this // file, or you compile this file and link it with other files to // produce an executable, this file does not by itself cause the // resulting executable to be covered by the GNU General Public // License. This exception does not however invalidate any other // reasons why the executable file might be covered by the GNU General // Public License. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file twister_rand_gen.hpp */ #ifndef PB_DS_TWISTER_RAND_GEN_HPP #define PB_DS_TWISTER_RAND_GEN_HPP #include <ctime> #include <limits.h> #include <tr1/random> namespace __gnu_pbds { namespace test { class twister_rand_gen { public: twister_rand_gen(unsigned int seed = static_cast<unsigned int>(std::time(0))); void init(unsigned int seed); static unsigned int get_time_determined_seed() { return(static_cast<unsigned int>(std::time(0))); } unsigned long get_unsigned_long(unsigned long min = 0, unsigned long max = UINT_MAX - 1); double get_prob(); private: typedef std::tr1::mt19937 base_generator_t; private: base_generator_t m_base_generator; }; } // namespace test } // namespace __gnu_pbds #endif // #ifndef PB_DS_TWISTER_RAND_GEN_HPP
epicsdeb/rtems-gcc-newlib
libstdc++-v3/testsuite/util/rng/twister_rand_gen.hpp
C++
gpl-2.0
2,838
Ext.define('ExtJsMVC.model.cursus.RootCursusModel', { extend : 'Ext.data.TreeModel', fields : [ {name: 'itemId'}, {name: 'name'} ], childType : 'ExtJsMVC.model.cursus.CursusModel' });
imie-source/MaCoCo
imieWEB/WebContent/app/model/cursus/RootCursusModel.js
JavaScript
gpl-2.0
231
/*======================================================================== rtl_433.h 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 OR INABILITY TO USE THIS SOFTWARE, EVEN IF THE COPYRIGHT HOLDERS OR CONTRIBUTORS ARE AWARE OF THE POSSIBILITY OF SUCH DAMAGE. ========================================================================*/ #ifndef __RTL_433FM_h #define __RTL_433FM_h // rtl-fm decode is suspended for this many seconds after successfully decoding an // efergy message. This is to reduce cpu load and keep it cooler based on the assumption // that efergy messages are evenly spaced (on elite TPM, 10 seconds by default) #define RTLFM_EFERGY_SLEEP_SECONDS 9 //#define DEFAULT_SAMPLE_RATE 24000 // rtl_fm default rate #define DEFAULT_SAMPLE_RATE 250000 #define DEFAULT_FREQUENCY 433920000 #define DEFAULT_HOP_TIME (60*10) #define DEFAULT_HOP_EVENTS 2 #define DEFAULT_ASYNC_BUF_NUMBER 32 #define R433_DEFAULT_BUF_LENGTH (16 * 16384) #define DEFAULT_LEVEL_LIMIT 10000 #define DEFAULT_DECIMATION_LEVEL 0 #define MINIMAL_R433_BUF_LENGTH 512 //#define MAXIMAL_BUF_LENGTH (256 * 16384) #define MAXIMAL_R433_BUF_LENGTH (16 * 16384) #define FILTER_ORDER 1 #define MAX_PROTOCOLS 10 #define SIGNAL_GRABBER_BUFFER (12 * R433_DEFAULT_BUF_LENGTH) #define BITBUF_COLS 34 #define BITBUF_ROWS 5 /* Supported modulation types */ #define OOK_PWM_D 1 /* Pulses are of the same length, the distance varies */ #define OOK_PWM_P 2 /* The length of the pulses varies */ #define OOK_MANCHESTER 3 /* Manchester code */ typedef struct { unsigned int id; char name[256]; unsigned int modulation; unsigned int short_limit; unsigned int long_limit; unsigned int reset_limit; int (*json_callback)(uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS]) ; } r_device; struct protocol_state { int (*callback)(uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS]); /* bits state */ int bits_col_idx; int bits_row_idx; int bits_bit_col_idx; uint8_t bits_buffer[BITBUF_ROWS][BITBUF_COLS]; int16_t bits_per_row[BITBUF_ROWS]; int bit_rows; unsigned int modulation; /* demod state */ int pulse_length; int pulse_count; int pulse_distance; int sample_counter; int start_c; int packet_present; int pulse_start; int real_bits; int start_bit; /* pwm limits */ int short_limit; int long_limit; int reset_limit; }; struct dm_state { FILE *file; int save_data; int32_t level_limit; int32_t decimation_level; int16_t filter_buffer[MAXIMAL_R433_BUF_LENGTH+FILTER_ORDER]; int16_t* f_buf; int analyze; int debug_mode; /* Signal grabber variables */ int signal_grabber; int8_t* sg_buf; int sg_index; int sg_len; /* Protocol states */ int r_dev_num; struct protocol_state *r_devs[MAX_PROTOCOLS]; }; extern int debug_output; extern int events; extern volatile int rtlsdr_do_exit; extern struct dm_state* rtl_433_demod; extern r_device oregon_scientific; extern int rtl_433_a[]; extern int rtl_433_b[]; extern int rtl_433fm_main(int argc, char **argv); extern void pwm_d_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len); extern void pwm_p_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len); extern void manchester_decode(struct dm_state *demod, struct protocol_state* p, int16_t *buf, uint32_t len); extern void demod_print_bits_packet(struct protocol_state* p); extern void demod_reset_bits_packet(struct protocol_state* p); extern void demod_next_bits_packet(struct protocol_state* p); extern void demod_add_bit(struct protocol_state* p, int bit); extern uint16_t *envelope_detect(unsigned char *buf, uint32_t len, int decimate); extern void low_pass_filter(uint16_t *x_buf, int16_t *y_buf, uint32_t len); extern void calc_squares(); extern void register_protocol(struct dm_state *demod, r_device *t_dev, uint32_t samp_rate); extern int oregon_scientific_decode(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]); extern int acurite_rain_gauge_decode(uint8_t bb[BITBUF_ROWS][BITBUF_COLS]); extern int efergy_energy_sensor_decode(int16_t *buf, int len, int efergy_debug_level); #endif
magellannh/rtl-wx
src/rtl-433fm.h
C
gpl-2.0
5,188
/*********************************************************************** MutInfo.C BOOM : Bioinformatics Object Oriented Modules Copyright (C)2012 William H. Majoros (martiandna@gmail.com). This is OPEN SOURCE SOFTWARE governed by the Gnu General Public License (GPL) version 3, as described at www.opensource.org. ***********************************************************************/ #include <iostream> #include <math.h> #include "MutInfo.H" using namespace std; double BOOM::MutInfo::compute(BOOM::ContingencyTbl &table) { /* Computes mutual information between variables whose joint occurrence counts are tabulated in table */ table.computeTotals(); const int height=table.getSecondDim(); const int width=table.getFirstDim(); const double total=(double) table.getGrandTotal(); BOOM::JointDistr dist(width,height); int x, y; for(x=0 ; x<width ; ++x) for(y=0 ; y<height ; ++y) dist[x][y]=table[x][y]/total; return compute(dist); } double BOOM::MutInfo::compute(const BOOM::JointDistr &dist) { /* Computes mutual information between two variables whose joint distribution is represented in dist */ const int X=dist.getFirstDim(); const int Y=dist.getSecondDim(); double mi=0.0; for(int x=0 ; x<X ; ++x) for(int y=0 ; y<Y ; ++y) { double P_sub_xy=dist[x][y]; double P_sub_x=dist.getMarginalX(x); double P_sub_y=dist.getMarginalY(y); mi+=P_sub_xy * log(P_sub_xy/(P_sub_x*P_sub_y)); } return mi; }
bmajoros/BOOM
MutInfo.C
C++
gpl-2.0
1,505
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>个人中心</title> <link rel="stylesheet" type="text/css" href="__PUBLIC__/css/person.css"> <script type="text/javascript" src="__PUBLIC__/js/jquery-1.11.1.min.js"></script> </head> <body> <div class="content"> <div class="head"> <div class="title"> <div class="title-left"> <span class="title-m"><span class="big">M</span><span class="title-top">AKERWAY</span><span class="title-bottom">一起分享智慧</span></span> <span class="title-main"><a href="{:U(index)}">首页</a></span> <!--<span class="title-squre"><a href="{:U(squre)}">广场</a></span>--> <span class="title-share"><a href="{:U(share)}">共享库</a></span> </div> <div class="div-search"> <form name="search" action="{:U(search)}" method="post"> <input class="search" name="search" type="text" placeholder="书名/分类?" /> <div class="search-a"> <input type="image" src="__PUBLIC__/images/search.png" name="img"> <!--<input type="submit" value="submit"/>--> <!--<img src="__PUBLIC__/images/search.png"/>--> </div> </form> <span>热门搜索:</span> <span class="detail"> <span><a>数据库系统概念</a></span> <span><a>CSS 3实战</a></span> <span><a>操作系统概念</a></span> </span> </div> <!--<span>--> <!--<ul>--> <!--<li>注册</li>--> <!--<li>登录</li>--> <!--</ul>--> <!--</span>--> <!--<span class="username-list">--> <!--&lt;!&ndash;<ul>&ndash;&gt;--> <!--&lt;!&ndash;<li class="register"><a href="{:U(register)}">注册</a></li>&ndash;&gt;--> <!--&lt;!&ndash;<li class="login"><a href="{:U(login)}">登录</a></li>&ndash;&gt;--> <!--&lt;!&ndash;</ul>&ndash;&gt;--> <!--</span>--> <div class="username-c"><span style="margin-left: 0%;">hello</span> <span class="username-d"><a href="{:U(person)}"><?php echo cookie('username')?></a></span></div> </div> <!--<div class="view"></div>--> </div> <div class="main"> <div class="classify"> <div class="classify-title"><a style="cursor: pointer;color:#000;text-decoration: none" href="{:U(index)}">MakerWay</a>>个人中心</div> </div> <div class="main-left"> <div class="main-left-person"> <div class="main-img"> <img /><br/> <span class="username"><?php echo cookie('username')?></span> </div> <div class="main-ul"> <ul> <li>{$integral}<br/><br/>积分</li> <li>分享达人<br/><br/>等级</li> <li>{$booknum}本<br/><br/>分享数</li> </ul> <div class="main-a"><a href="{:U(contribute)}"><input class="sharebtn" type="button" value="我要分享"/></a></div> </div> </div> </div> <div class="main-right"> <div class="navigate"> <ul> <li class="border">动态</li> <li><a href="{:U(message)}">账号信息</a></li> <li><a href="{:U(personshare)}">书架</a></li> <li>笔记</li> <li><a href="{:U(mygroup)}">群组</a></li> <li>好友</li> <li>消息</li> </ul> </div> <div class="subnavigate"> <div style="display: block"> <ul style="height: 10px;clear: both;"></ul> <div class="my-pass"> <div class="book_life_experience_p"> <section id="cd-timeline" class="cd-container"> <div class="cd-timeline-block"> <div class="cd-timeline-img cd-picture"> <img src="__PUBLIC__/images/logo.png" alt="Picture"> </div> <div class="cd-timeline-content"> <h2>哪一本书</h2> <p>会被我青睐呢</p> <span class="cd-date">future</span> </div> </div> <?php if ($booklog): ?> <?php foreach ($booklog as $item): ?> <?php if ($item['status']==2): ?> <div class="cd-timeline-block"> <div class="cd-timeline-img cd-picture"> <img src="__PUBLIC__/images/logo.png" alt="Picture"> </div> <div class="cd-timeline-content"> <h2>借</h2> <p><span class='keeper' >我</span>借走了《{$item['booklog']['title']}》</p> <p>将在<span class="keeper">{$item['end_time']}</span>还书</p> <span class="cd-date">{$item['start_time']}</span> </div> </div> <?php elseif ($item['status']==4): ?> <div class="cd-timeline-block"> <div class="cd-timeline-img cd-picture"> <img src="__PUBLIC__/images/logo.png" alt="Picture"> </div> <div class="cd-timeline-content"> <h2>预</h2> <p><span class='keeper' >我</span>预约了《{$item['booklog']['title']}》</p> <span class="cd-date">{$item['start_time']}</span> </div> </div> <?php elseif ($item['status']==5): ?> <div class="cd-timeline-block"> <div class="cd-timeline-img cd-picture"> <img src="__PUBLIC__/images/logo.png" alt="Picture"> </div> <div class="cd-timeline-content"> <h2>续</h2> <p><span class='keeper' >我</span>续借了《{$item['booklog']['title']}》</p> <p>将在<span class='keeper' >{$item['end_time']}</span>还书</p> <span class="cd-date">{$item['start_time']}</span> </div> </div> <?php elseif ($item['status']==3): ?> <div class="cd-timeline-block"> <div class="cd-timeline-img cd-picture"> <img src="__PUBLIC__/images/logo.png" alt="Picture"> </div> <div class="cd-timeline-content"> <h2>还</h2> <p><span class='keeper' >我</span>归还了《{$item['booklog']['title']}》</p> <span class="cd-date">{$item['end_time']}</span> </div> </div> <?php endif ?> <?php endforeach ?> <?php endif ?> <div class="cd-timeline-block"> <div class="cd-timeline-img cd-picture"> <img src="__PUBLIC__/images/logo.png" alt="Picture"> </div> <div class="cd-timeline-content"> <h2>我</h2> <p>来到了Makerway这个奇幻漂流世界</p> <p>可以尽情畅游书海</p> <span class="cd-date">{$book['contribute_time']}</span> </div> </div> </section> </div> </div> </div> <div class="message" style="display: none;"> <ul> <li class="activecolor">基本资料</li> <li>联系方式</li> <li>密码安全</li> <li>修改头像</li> </ul> <div class="second-navigate"> <div class="second-message" style="display: block;"> <form class="messageform"> <div class="label-m"><label>用户名:</label><span class="username-in"><?php echo cookie('username')?></span></div><br/> <div class="span-s">性&nbsp;&nbsp;&nbsp;&nbsp;别:<input id="secret" type="radio" name="sex"/><label for="secret">保密</label> <input id="male" type="radio" name="sex"/><label for="male">男</label> <input id="female" type="radio" name="sex"/><label for="female">女</label></div><br/> <!--<div class="span-s">生&nbsp;&nbsp;&nbsp;&nbsp;日:<input type="radio"/>保密 <input type="radio"/>男 <input type="radio"/>女</div><br/>--> <input class="savemessage" type="submit" value="保存资料"/> </form> </div> <div style="display: none;"> <div class="messageform2"> <div class="span-s">已存电话:<span class="adress"><?php echo $user['phone']?></span></div><br/> <div class="span-s">已存邮箱:<span class="adress"><?php echo $user['email']?></span></div><br/> <div class="span-s">已存地址:<span class="adress"><?php echo $user['addr']?></span></div><br/> <div class="span-c"><input class="change-message" type="button" value="修&nbsp;&nbsp;&nbsp;&nbsp;改"/></div> </div> <form class="messageform3" action="{:U(usmessage)}" method="post"> <!--<div class="label-m"><label>联系姓名:</label><input class="username-in"/></div><br/>--> <div class="span-s">联系电话:<input name="phonenum" class="username-in"/></div><br/> <div class="span-s">联系邮箱:<input name="email" class="username-in"/></div><br/> <div class="span-s">联系地址:<input name="address" class="username-in"/></div><br/> <!--<div class="span-s">生&nbsp;&nbsp;&nbsp;&nbsp;日:<input type="radio"/>保密 <input type="radio"/>男 <input type="radio"/>女</div><br/>--> <input class="savemessage" type="submit" value="保存资料"/> </form> </div> <div style="display: none;"> <form class="messageform" action="{:U(usemessage)}" method="post" onsubmit="return check()"> <div class="label-m"><label>原密码:&nbsp;&nbsp;&nbsp;&nbsp;</label><input class="username-in" name="fpassword"/></div><br/> <div class="label-m"><label>新密码:&nbsp;&nbsp;&nbsp;&nbsp;</label><input class="username-in" name="password"/></div><br/> <div class="label-m"><label>确认密码:</label><input class="username-in" name="rpassword"/></div><br/> <!--<div class="span-s">生&nbsp;&nbsp;&nbsp;&nbsp;日:<input type="radio"/>保密 <input type="radio"/>男 <input type="radio"/>女</div><br/>--> <input class="savemessage" type="submit" value="保存资料"/> </form> </div> <div style="display: none;"> <form class="messageform1"> <div class="label-m label-float"> <img class="file-img" src="" /> </div><br/> <div class="label-m marginleft"> <div class="choose-img"> <input class="file" type="file" value="选择图片" /> </div> </div><br/> <div class="label-m marginleft"> <label>说明:</label><br/> <label>1、支持JPG、JPEG、GIF、PNG文件格式。</label><br/> <label>2、GIF帧数过高会造成您电脑运行缓慢。</label><br/> </div><br/> <!--<div class="span-s">生&nbsp;&nbsp;&nbsp;&nbsp;日:<input type="radio"/>保密 <input type="radio"/>男 <input type="radio"/>女</div><br/>--> <input class="savemessage" type="button" value="保存资料"/> </form> </div> </div> </div> <div style="display: none;"> <ul class="bookmessage"> <li class="activecolor">共享书籍</li> <li><a href="{:U(myKeeps)}">借阅信息</a></li> <li>我的关注</li> </ul> <!--<div class="mybook" >--> <!--<div class="submybook">--> <!--<ul>--> <!--<foreach name='mybooks' item='item'>--> <!--<li>--> <!--<div class="main-body-li">--> <!--<img src="{$item['bookinfo']['image']}"/>--> <!--<span class="name">书名:<?php echo $s = iconv("UTF-8","GB2312",$item['bookinfo']['title'])?></span>--> <!--<span class="author">类别:</span>--> <!--<span class="favour">创建时间:{$item['contribute_time']}</span>--> <!--<span class="comment">书本状态:</span>--> <!--<input type="button" value="借阅历史" onclick="document.location='{:U(bookInfo,array('bookid'=>$item['book_id']))}'" style="cursor:pointer"/>--> <!--</div>--> <!--</li>--> <!--</foreach>--> <!--<span class="fenpage">{$page}</span>--> <!--</ul>--> <!--</div>--> <div class="submybook" style="display: none;"> <ul class="dosomething"> <li style="cursor: pointer">阅读中</li> <li style="cursor: pointer">预约中</li> </ul> <div class="doing"> <div style="display: block;"> <ul> <li> <div class="main-body-li"> <img src=""/> <span class="name">书名2:<?php echo $item['bookinfo']['title']?></span> <span class="author">类别:</span> <span class="favour">创建时间:</span> <span class="comment">书本状态:</span> <input type="button" value="借阅历史" onclick="document.location='{:U(bookInfo,array('bookid'=>$item['book_id']))}'" style="cursor:pointer"/> </div> </li> </ul> </div> <div style="display: none;"> <ul> <li> <div class="main-body-li"> <img src=""/> <span class="name">书名3:<?php echo $item['bookinfo']['title']?></span> <span class="author">类别:</span> <span class="favour">创建时间:</span> <span class="comment">书本状态:</span> <input type="button" value="借阅历史" onclick="document.location='{:U(bookInfo,array('bookid'=>$item['book_id']))}'" style="cursor:pointer"/> </div> </li> </ul> </div> </div> </div> <div style="display: none"> <ul style="height: 10px;clear: both;"></ul> <div class="my-pass"></div> </div> </div> <div style="display: none;"> <ul style="height: 10px;clear: both;"></ul> <div class="my-pass"></div> <!--<ul>--> <!--<li class="activecolor">我的书签</li>--> <!--<li>朋友的书签</li>--> <!--<li>热门书签</li>--> <!--</ul>--> <!--<div class="tags">--> <!--<div style="display: block">--> <!--<ul style="height: 10px;clear: both;"></ul>--> <!--<div class="my-pass"></div>--> <!--</div>--> <!--<div style="display: none">--> <!--<ul style="height: 10px;clear: both;"></ul>--> <!--<div class="my-pass"></div>--> <!--</div>--> <!--<div style="display: none">--> <!--<ul style="height: 10px;clear: both;"></ul>--> <!--<div class="my-pass"></div>--> <!--</div>--> <!--</div>--> </div> <div class="booktags" style="display: none"> <ul> <li class="activecolor">群组列表</li> <li>群组动态</li> </ul> <div class="tags"> <div style="display: block"> <ul style="height: 10px;clear: both;"></ul> <div class="my-pass"></div> </div> <div style="display: none"> <ul style="height: 10px;clear: both;"></ul> <div class="my-pass"></div> </div> </div> </div> <div class="friend" style="display: none"> <ul> <li class="activecolor">好友列表</li> <li>好友动态</li> </ul> <ul style="height: 10px;clear: both;"></ul> <div class="my-pass"> <div class="tags"> <div class="friend-message" style="display: block"> <div class="friend-member"> <ul> <foreach name="friendresult" item="item"> <li> <img /> <span>{$item['friendname']}</span> </li> </foreach> </ul> </div> </div> <div style="display: none"> <ul style="height: 10px;clear: both;"></ul> <div class="my-pass"></div> </div> </div> </div> </div> <div class="notice-request" style="display: none"> <ul> <li>请求</li> <li class="activecolor">通知</li> </ul> <ul style="height: 10px;clear: both;"></ul> <div class="my-pass"> <div class="message-body"> <ul style="display: none"> <foreach name="friendhandle" item="item"> <li> <div class="person-pass-left"> <img /> <span class="person-pass-name">{$item['friendname']}</span> <span class="person-pass-request">请求加您为好友</span> </div> <div class="person-pass-right"> <input class="agree" type="button" value="同意"/> <a class="disagree">忽略</a> <input style="display: none" value="{$item['friendname']}"/> </div> <div class="person-pass-right" style="display: none"> <input class="agree" type="button" value="已同意"/> </div> <div class="person-pass-right" style="display: none"> <a class="disagree">已忽略</a> </div> </li> </foreach> </ul> <ul> <foreach name="resultmessage" item="item"> <li> <span class="message-img"> <img src="__PUBLIC__/images/administrator.png"/> </span> <span class="message-notice">系统通知</span> <span class="message-notice-details"> <span class="message-color">群组系统通知</span><br/> <span class="message-handle">{$item['groupname']}群主 <?php if ($item['result']==1): ?> 同意 <?php elseif ($item['result']==0):?> 忽略 <?php endif ?> 您的加群申请。 </span> </span> </li> </foreach> <foreach name="friendaddresult" item="item"> <li> <span class="message-img"> <img src="__PUBLIC__/images/administrator.png"/> </span> <span class="message-notice">系统通知</span> <span class="message-notice-details"> <span class="message-color">好友系统通知</span><br/> <span class="message-handle">{$item['username']} <?php if ($item['result']==1): ?> 同意 <?php elseif ($item['result']==0):?> 忽略 <?php endif ?> 您的好友申请。 </span> </span> </li> </foreach> </ul> </div> </div> </div> </div> </div> </div> </div> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-68503572-4', 'auto'); ga('send', 'pageview'); </script> </body> <script type="text/javascript" src="__PUBLIC__/js/person.js"></script> <script type="text/javascript" src="__PUBLIC__/js/labelsearch.js"></script> </html>
huran2014/huran.github.io
makerway/Application/Home/View/Index/person.html
HTML
gpl-2.0
29,221
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ /* * Libparrillada-media * Copyright (C) Philippe Rouquier 2005-2009 <bonfire-app@wanadoo.fr> * * Libparrillada-media is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * The Libparrillada-media authors hereby grant permission for non-GPL compatible * GStreamer plugins to be used and distributed together with GStreamer * and Libparrillada-media. This permission is above and beyond the permissions granted * by the GPL license by which Libparrillada-media is covered. If you modify this code * you may extend this exception to your version of the code, but you are not * obligated to do so. If you do not wish to do so, delete this exception * statement from your version. * * Libparrillada-media is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to: * The Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301, USA. */ #include <glib.h> #include "scsi-base.h" #ifndef _BURN_GET_PERFORMANCE_H #define _BURN_GET_PERFORMANCE_H G_BEGIN_DECLS #if G_BYTE_ORDER == G_LITTLE_ENDIAN struct _ParrilladaScsiGetPerfHdr { uchar len [4]; uchar except :1; uchar wrt :1; uchar reserved0 :6; uchar reserved1 [3]; }; struct _ParrilladaScsiWrtSpdDesc { uchar mrw :1; uchar exact :1; uchar rdd :1; uchar wrc :1; uchar reserved0 :3; uchar reserved1 [3]; uchar capacity [4]; uchar rd_speed [4]; uchar wr_speed [4]; }; #else struct _ParrilladaScsiGetPerfHdr { uchar len [4]; uchar reserved0 :6; uchar wrt :1; uchar except :1; uchar reserved1 [3]; }; struct _ParrilladaScsiWrtSpdDesc { uchar reserved0 :3; uchar wrc :1; uchar rdd :1; uchar exact :1; uchar mrw :1; uchar reserved1 [3]; uchar capacity [4]; uchar rd_speed [4]; uchar wr_speed [4]; }; #endif typedef struct _ParrilladaScsiGetPerfHdr ParrilladaScsiGetPerfHdr; typedef struct _ParrilladaScsiWrtSpdDesc ParrilladaScsiWrtSpdDesc; struct _ParrilladaScsiGetPerfData { ParrilladaScsiGetPerfHdr hdr; gpointer data; /* depends on the request */ }; typedef struct _ParrilladaScsiGetPerfData ParrilladaScsiGetPerfData; G_END_DECLS #endif /* _BURN_GET_PERFORMANCE_H */
darkshram/parrillada
libparrillada-media/scsi-get-performance.h
C
gpl-2.0
2,682
/** * Automatically generated file. DO NOT MODIFY */ package com.dzb.xeonzolt.CM.debian.test; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "com.dzb.xeonzolt.CM.debian.test"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = 8; public static final String VERSION_NAME = "1.7"; }
DZB-themes-CM/Debian
theme/build/generated/source/buildConfig/androidTest/debug/com/dzb/xeonzolt/CM/debian/test/BuildConfig.java
Java
gpl-2.0
469
#ifndef LINTPLUG_GLOBAL_H #define LINTPLUG_GLOBAL_H #include <QtGlobal> #if defined(LINTPLUG_LIBRARY) # define LINTPLUGSHARED_EXPORT Q_DECL_EXPORT #else # define LINTPLUGSHARED_EXPORT Q_DECL_IMPORT #endif #endif // LINTPLUG_GLOBAL_H
R-Typ/LintPlug
lintplug_global.h
C
gpl-2.0
239
open SRC,"pony"; open TAR, "> allpony"; while(<SRC>) { chomp; unless (m/\.png\s*$|^\s*$/i) { while(m~\s*([^/]+)(?:\s*/|\s*$)~ig) { # if (lc($1) != "png" && lc($1) != "jpg") { print "Found: $1\n"; print TAR "$1\n"; # } } } }
JimTheCactus/Gummybot
gummyfun/parse.pl
Perl
gpl-2.0
236
/** ****************************************************************************** * @file stm32f7xx_hal_flash.h * @author MCD Application Team * @version V1.0.3 * @date 13-November-2015 * @brief Header file of FLASH HAL module. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2015 STMicroelectronics</center></h2> * * 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 STMicroelectronics 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F7xx_HAL_FLASH_H #define __STM32F7xx_HAL_FLASH_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f7xx_hal_def.h" /** @addtogroup STM32F7xx_HAL_Driver * @{ */ /** @addtogroup FLASH * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup FLASH_Exported_Types FLASH Exported Types * @{ */ /** * @brief FLASH Procedure structure definition */ typedef enum { FLASH_PROC_NONE = 0, FLASH_PROC_SECTERASE, FLASH_PROC_MASSERASE, FLASH_PROC_PROGRAM } FLASH_ProcedureTypeDef; /** * @brief FLASH handle Structure definition */ typedef struct { __IO FLASH_ProcedureTypeDef ProcedureOnGoing; /* Internal variable to indicate which procedure is ongoing or not in IT context */ __IO uint32_t NbSectorsToErase; /* Internal variable to save the remaining sectors to erase in IT context */ __IO uint8_t VoltageForErase; /* Internal variable to provide voltage range selected by user in IT context */ __IO uint32_t Sector; /* Internal variable to define the current sector which is erasing */ __IO uint32_t Address; /* Internal variable to save address selected for program */ HAL_LockTypeDef Lock; /* FLASH locking object */ __IO uint32_t ErrorCode; /* FLASH error code */ }FLASH_ProcessTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup FLASH_Exported_Constants FLASH Exported Constants * @{ */ /** @defgroup FLASH_Error_Code FLASH Error Code * @brief FLASH Error Code * @{ */ #define HAL_FLASH_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ #define HAL_FLASH_ERROR_ERS ((uint32_t)0x00000002) /*!< Programming Sequence error */ #define HAL_FLASH_ERROR_PGP ((uint32_t)0x00000004) /*!< Programming Parallelism error */ #define HAL_FLASH_ERROR_PGA ((uint32_t)0x00000008) /*!< Programming Alignment error */ #define HAL_FLASH_ERROR_WRP ((uint32_t)0x00000010) /*!< Write protection error */ #define HAL_FLASH_ERROR_OPERATION ((uint32_t)0x00000020) /*!< Operation Error */ /** * @} */ /** @defgroup FLASH_Type_Program FLASH Type Program * @{ */ #define FLASH_TYPEPROGRAM_BYTE ((uint32_t)0x00) /*!< Program byte (8-bit) at a specified address */ #define FLASH_TYPEPROGRAM_HALFWORD ((uint32_t)0x01) /*!< Program a half-word (16-bit) at a specified address */ #define FLASH_TYPEPROGRAM_WORD ((uint32_t)0x02) /*!< Program a word (32-bit) at a specified address */ #define FLASH_TYPEPROGRAM_DOUBLEWORD ((uint32_t)0x03) /*!< Program a double word (64-bit) at a specified address */ /** * @} */ /** @defgroup FLASH_Flag_definition FLASH Flag definition * @brief Flag definition * @{ */ #define FLASH_FLAG_EOP FLASH_SR_EOP /*!< FLASH End of Operation flag */ #define FLASH_FLAG_OPERR FLASH_SR_OPERR /*!< FLASH operation Error flag */ #define FLASH_FLAG_WRPERR FLASH_SR_WRPERR /*!< FLASH Write protected error flag */ #define FLASH_FLAG_PGAERR FLASH_SR_PGAERR /*!< FLASH Programming Alignment error flag */ #define FLASH_FLAG_PGPERR FLASH_SR_PGPERR /*!< FLASH Programming Parallelism error flag */ #define FLASH_FLAG_ERSERR FLASH_SR_ERSERR /*!< FLASH Erasing Sequence error flag */ #define FLASH_FLAG_BSY FLASH_SR_BSY /*!< FLASH Busy flag */ /** * @} */ /** @defgroup FLASH_Interrupt_definition FLASH Interrupt definition * @brief FLASH Interrupt definition * @{ */ #define FLASH_IT_EOP FLASH_CR_EOPIE /*!< End of FLASH Operation Interrupt source */ #define FLASH_IT_ERR ((uint32_t)0x02000000) /*!< Error Interrupt source */ /** * @} */ /** @defgroup FLASH_Program_Parallelism FLASH Program Parallelism * @{ */ #define FLASH_PSIZE_BYTE ((uint32_t)0x00000000) #define FLASH_PSIZE_HALF_WORD ((uint32_t)FLASH_CR_PSIZE_0) #define FLASH_PSIZE_WORD ((uint32_t)FLASH_CR_PSIZE_1) #define FLASH_PSIZE_DOUBLE_WORD ((uint32_t)FLASH_CR_PSIZE) #define CR_PSIZE_MASK ((uint32_t)0xFFFFFCFF) /** * @} */ /** @defgroup FLASH_Keys FLASH Keys * @{ */ #define FLASH_KEY1 ((uint32_t)0x45670123) #define FLASH_KEY2 ((uint32_t)0xCDEF89AB) #define FLASH_OPT_KEY1 ((uint32_t)0x08192A3B) #define FLASH_OPT_KEY2 ((uint32_t)0x4C5D6E7F) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup FLASH_Exported_Macros FLASH Exported Macros * @{ */ /** * @brief Set the FLASH Latency. * @param __LATENCY__: FLASH Latency * The value of this parameter depend on device used within the same series * @retval none */ #define __HAL_FLASH_SET_LATENCY(__LATENCY__) \ MODIFY_REG(FLASH->ACR, FLASH_ACR_LATENCY, (uint32_t)(__LATENCY__)) /** * @brief Get the FLASH Latency. * @retval FLASH Latency * The value of this parameter depend on device used within the same series */ #define __HAL_FLASH_GET_LATENCY() (READ_BIT((FLASH->ACR), FLASH_ACR_LATENCY)) /** * @brief Enable the FLASH prefetch buffer. * @retval none */ #define __HAL_FLASH_PREFETCH_BUFFER_ENABLE() (FLASH->ACR |= FLASH_ACR_PRFTEN) /** * @brief Disable the FLASH prefetch buffer. * @retval none */ #define __HAL_FLASH_PREFETCH_BUFFER_DISABLE() (FLASH->ACR &= (~FLASH_ACR_PRFTEN)) /** * @brief Enable the FLASH Adaptive Real-Time memory accelerator. * @note The ART accelerator is available only for flash access on ITCM interface. * @retval none */ #define __HAL_FLASH_ART_ENABLE() SET_BIT(FLASH->ACR, FLASH_ACR_ARTEN) /** * @brief Disable the FLASH Adaptive Real-Time memory accelerator. * @retval none */ #define __HAL_FLASH_ART_DISABLE() CLEAR_BIT(FLASH->ACR, FLASH_ACR_ARTEN) /** * @brief Resets the FLASH Adaptive Real-Time memory accelerator. * @note This function must be used only when the Adaptive Real-Time memory accelerator * is disabled. * @retval None */ #define __HAL_FLASH_ART_RESET() (FLASH->ACR |= FLASH_ACR_ARTRST) /** * @brief Enable the specified FLASH interrupt. * @param __INTERRUPT__ : FLASH interrupt * This parameter can be any combination of the following values: * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt * @arg FLASH_IT_ERR: Error Interrupt * @retval none */ #define __HAL_FLASH_ENABLE_IT(__INTERRUPT__) (FLASH->CR |= (__INTERRUPT__)) /** * @brief Disable the specified FLASH interrupt. * @param __INTERRUPT__ : FLASH interrupt * This parameter can be any combination of the following values: * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt * @arg FLASH_IT_ERR: Error Interrupt * @retval none */ #define __HAL_FLASH_DISABLE_IT(__INTERRUPT__) (FLASH->CR &= ~(uint32_t)(__INTERRUPT__)) /** * @brief Get the specified FLASH flag status. * @param __FLAG__: specifies the FLASH flag to check. * This parameter can be one of the following values: * @arg FLASH_FLAG_EOP : FLASH End of Operation flag * @arg FLASH_FLAG_OPERR : FLASH operation Error flag * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag * @arg FLASH_FLAG_PGPERR: FLASH Programming Parallelism error flag * @arg FLASH_FLAG_ERSERR : FLASH Erasing Sequence error flag * @arg FLASH_FLAG_BSY : FLASH Busy flag * @retval The new state of __FLAG__ (SET or RESET). */ #define __HAL_FLASH_GET_FLAG(__FLAG__) ((FLASH->SR & (__FLAG__))) /** * @brief Clear the specified FLASH flag. * @param __FLAG__: specifies the FLASH flags to clear. * This parameter can be any combination of the following values: * @arg FLASH_FLAG_EOP : FLASH End of Operation flag * @arg FLASH_FLAG_OPERR : FLASH operation Error flag * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag * @arg FLASH_FLAG_PGPERR: FLASH Programming Parallelism error flag * @arg FLASH_FLAG_ERSERR : FLASH Erasing Sequence error flag * @retval none */ #define __HAL_FLASH_CLEAR_FLAG(__FLAG__) (FLASH->SR = (__FLAG__)) /** * @} */ /* Include FLASH HAL Extension module */ #include "stm32f7xx_hal_flash_ex.h" /* Exported functions --------------------------------------------------------*/ /** @addtogroup FLASH_Exported_Functions * @{ */ /** @addtogroup FLASH_Exported_Functions_Group1 * @{ */ /* Program operation functions ***********************************************/ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data); HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data); /* FLASH IRQ handler method */ void HAL_FLASH_IRQHandler(void); /* Callbacks in non blocking modes */ void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue); void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue); /** * @} */ /** @addtogroup FLASH_Exported_Functions_Group2 * @{ */ /* Peripheral Control functions **********************************************/ HAL_StatusTypeDef HAL_FLASH_Unlock(void); HAL_StatusTypeDef HAL_FLASH_Lock(void); HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void); HAL_StatusTypeDef HAL_FLASH_OB_Lock(void); /* Option bytes control */ HAL_StatusTypeDef HAL_FLASH_OB_Launch(void); /** * @} */ /** @addtogroup FLASH_Exported_Functions_Group3 * @{ */ /* Peripheral State functions ************************************************/ uint32_t HAL_FLASH_GetError(void); HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @defgroup FLASH_Private_Variables FLASH Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup FLASH_Private_Constants FLASH Private Constants * @{ */ /** * @brief OPTCR register byte 1 (Bits[15:8]) base address */ #define OPTCR_BYTE1_ADDRESS ((uint32_t)0x40023C15) /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @defgroup FLASH_Private_Macros FLASH Private Macros * @{ */ /** @defgroup FLASH_IS_FLASH_Definitions FLASH Private macros to check input parameters * @{ */ #define IS_FLASH_TYPEPROGRAM(VALUE)(((VALUE) == FLASH_TYPEPROGRAM_BYTE) || \ ((VALUE) == FLASH_TYPEPROGRAM_HALFWORD) || \ ((VALUE) == FLASH_TYPEPROGRAM_WORD) || \ ((VALUE) == FLASH_TYPEPROGRAM_DOUBLEWORD)) /** * @} */ /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup FLASH_Private_Functions FLASH Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F7xx_HAL_FLASH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
frzolp/StatusDisplay
StatusDisplay/HAL_Driver/Inc/stm32f7xx_hal_flash.h
C
gpl-2.0
14,716
<?php try { $bdd = new PDO("mysql:host=localhost;dbname=intra","root","root"); } catch (Exception $e) { die('Erreur : '.$e->getMessage()); }
fbouynot/intra
core/bdd_connect.php
PHP
gpl-2.0
149
// // DNSTest.cpp // // $Id: //poco/1.4/Net/testsuite/src/DNSTest.cpp#4 $ // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "DNSTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/Net/DNS.h" #include "Poco/Net/HostEntry.h" #include "Poco/Net/NetException.h" using Poco::Net::DNS; using Poco::Net::IPAddress; using Poco::Net::HostEntry; using Poco::Net::InvalidAddressException; using Poco::Net::HostNotFoundException; using Poco::Net::ServiceNotFoundException; using Poco::Net::NoAddressFoundException; DNSTest::DNSTest(const std::string& name): CppUnit::TestCase(name) { } DNSTest::~DNSTest() { } void DNSTest::testHostByName() { HostEntry he1 = DNS::hostByName("aliastest.appinf.com"); // different systems report different canonical names, unfortunately. assert (he1.name() == "dnstest.appinf.com" || he1.name() == "aliastest.appinf.com"); #if !defined(POCO_HAVE_ADDRINFO) // getaddrinfo() does not report any aliases assert (!he1.aliases().empty()); assert (he1.aliases()[0] == "aliastest.appinf.com"); #endif assert (he1.addresses().size() >= 1); assert (he1.addresses()[0].toString() == "1.2.3.4"); try { HostEntry he1 = DNS::hostByName("nohost.appinf.com"); fail("host not found - must throw"); } catch (HostNotFoundException&) { } catch (NoAddressFoundException&) { } } void DNSTest::testHostByAddress() { IPAddress ip1("80.122.195.86"); HostEntry he1 = DNS::hostByAddress(ip1); assert (he1.name() == "mailhost.appinf.com"); assert (he1.aliases().empty()); assert (he1.addresses().size() >= 1); assert (he1.addresses()[0].toString() == "80.122.195.86"); IPAddress ip2("10.0.244.253"); try { HostEntry he2 = DNS::hostByAddress(ip2); fail("host not found - must throw"); } catch (HostNotFoundException&) { } catch (NoAddressFoundException&) { } } void DNSTest::testResolve() { } void DNSTest::setUp() { } void DNSTest::tearDown() { } CppUnit::Test* DNSTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DNSTest"); CppUnit_addTest(pSuite, DNSTest, testHostByName); CppUnit_addTest(pSuite, DNSTest, testHostByAddress); CppUnit_addTest(pSuite, DNSTest, testResolve); return pSuite; }
aleciten/foo_siesta
Poco/Net/testsuite/src/DNSTest.cpp
C++
gpl-2.0
3,753
showWord(["n. "," Nan konstriksyon lari, twou kote dlo desann anba tè. Twou rego sa a bouche." ])
georgejhunt/HaitiDictionary.activity
data/words/rego_egou_.js
JavaScript
gpl-2.0
98
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.34209 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace ClickDummyStudent.Properties { using System; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert. // Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen // mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ClickDummyStudent.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
SE-Beleggruppe/ProgrammStudent
ClickDummyStudent/ClickDummyStudent/Properties/Resources.Designer.cs
C#
gpl-2.0
3,022
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>MC-API</title> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="An explanation and update about the v4 update."> <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/readable/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/style/styles.css"> <link rel="shortcut icon" href="//raw.githubusercontent.com/MC-API/static/master/assets/favicon.ico"/> </head> <body> <div class="container card"> <div class="content"> <h2><i class="fa fa-code"></i> MC-API</h2> <hr> <p><strong>tl;dr: On August 7th 2016 we deprecated our UUID, Name and History APIs, they are no longer accessible. Please update your applications to use an alternative, some are listed below. All of our other APIs will continue to function.</strong></p> <p><em>Note:</em> This post had to be rewritten as the original was lost, the original went into much more detail and was easier to understand.</p> <p class="hello">An update about v4</p> <p>A couple of months ago we started to do a rewrite of the API (v4) which was largely prompted by the fact that most API requests were failing. The solution that was planned was to implement an API key system.</p> <p>This would've required all users of our most intensive APIs (UUID, Username and History) to provide an API key which would be limited to a pre-defined amount.</p> <p>There were a couple of flaws with this:</p> <ul> <li>It would break the developer eco-system for plugins (a server-owner would need an api key for a "random" website, would also break existing plugins)</li> <li>It would lose backwards-compatibility</li> <li>It would be hard for some users to migrate</li> <li>It isn't an elegant or perfect solution to the problem we are facing</li> </ul> <p><em>Side note:</em> v4 is still planned, as a redesign of the main website and a backend rewrite. This will be released in the near future.</p> <p>The problem we have been facing recently is an excessive amount of requests being sent to some of our APIs, a large percentage of these are malicious and are intended to fail and cause our servers to be rate limited by Mojang.</p> <p>At the time of writing &dash; 30th July 2016 &dash; we are receiving in excess of 250 requests per second, 24 hours a day. Our infrastructure is relatively small, and the way Mojang rate limit is very restrictive. You can see an image from NewRelic which monitors our Nginx instances, <a href="http://i.imgur.com/sirKJsl.png">here</a>.</p> <p>Most of the Mojang API rate limits based on IP and allows 600 requests per 10 minutes (about 1 per second) the fact that we are receiving more than 250 per second, means we have no chance of responding correctly to even a small portion.</p> <p>MC-API has always been funded by donations and any excess funded personally by us, the developers. While donations are a rare occurance, we are extremely grateful for all contributions.</p> <p>The fact that donations are so rare means that it is difficult to add more capacity and servers. Generally servers come with 1 IP address, which means we would need over 250 servers to respond to each query.</p> <p class="hello">A sad step we are taking</p> <p>Sadly, we will have deprecated our UUID, Name and History APIs on <strong>August 7th</strong>. This meant that these APIs are no longer accessible, we gave 1 week notice before anything was done, to give users a chance to update their applications. We highly recommend updating your applications, alternatives are listed below.</p> <p>We are doing this for a number of reasons:</p> <ul> <li>The service is becoming hard to sustain, and expensive to add more capacity</li> <li>We are unable to respond to most of these API requests</li> <li>A lot of requests are malicious, are destined to fail and intended to cause our servers to be rate limited.</li> </ul> <p>As mentioned above, a lot of requests are intended to fail, but still end up querying mojangs API, this means our servers are likely to be rate limited, meaning legitimate requests will also fail.</p> <p>This is a classic case of the minority ruining it for the majority.</p> <p>While we may re-add these APIs in the future, it is very unlikely within 2016.</p> <p>We apologise for the inconveniencen this will cause and feel we have let you down.</p> <hr> <p class="hello">Is there an alternative?</p> <p>There are several alternatives, a couple are listed below.</p> <ul> <li><a href="https://api.minepay.net/mapi/index.html">MinePay API</a> &dash; Maintained by <a href="https://twitter.com/minepay_">MinePay</a></li> <li><a href="http://mcapi.ca/">MCAPI.ca</a> &dash; Maintained by <a href="https://twitter.com/itsyive">Yive</a></li> </ul> <p class="hello">Is there no way to raise funds?</p> <p>Our primary income source is donations, which are completely optional and go directly to paying for the servers.</p> <p>We don't get many donations, and can not thank you enough if you have ever donated.</p> <p>Therefore MC-API is paid for personally by us, the developers. It's quite expensive.</p> <p>We have evaluated adding advertising, and have concluded this would not be a solution to this particular problem.</p> <p class="hello">When is this happening?</p> <p>It has already happened! On <strong>August 7th</strong>, these APIs were deprecated and are no longer accessible. Please update your applications using an alternative, some are listed above.</p> <p class="hello">Is there no way to block the malicious requests?</p> <p>Due to the nature of our API, open, anonymous and free, things like this are bound to happen.</p> <p>It is also extremely difficult to detect and block malicious requests, we have implemented some measures, but they are not long term.</p> <p class="hello">Is this the end of MC-API?</p> <p>Nope! All of our other APIs will continue to operate and we have a redesign planned which is coming soon.</p> <p class="hello">I have another question!</p> <p>The easiest and quickest way to contact us is through twitter. You can tweet <a href="//twitter.com/mc_api">@mc_api</a>.</p> </div> <hr> <footer> <ul class="nav nav-pills"> <li class="text-muted disclaimer">MC-API is not affiliated with Mojang AB, Microsoft or Minecraft.net</li> <li class="pull-right"> <a>&copy; 2016 mc-api.net</a> </li> </ul> </footer> </div> <br> </body> </html>
MC-API/static
views/update-v4.html
HTML
gpl-2.0
7,064
//--------------------------------------------------------------------------- // // Project: hCLustering // // Whole-Brain Connectivity-Based Hierarchical Parcellation Project // David Moreno-Dominguez // d.mor.dom@gmail.com // moreno@cbs.mpg.de // www.cbs.mpg.de/~moreno// // // hClustering is free software: you can redistribute it and/or modify // // For more reference on the underlying algorithm and research they have been used for refer to: // - Moreno-Dominguez, D., Anwander, A., & Knösche, T. R. (2014). // A hierarchical method for whole-brain connectivity-based parcellation. // Human Brain Mapping, 35(10), 5000-5025. doi: http://dx.doi.org/10.1002/hbm.22528 // - Moreno-Dominguez, D. (2014). // Whole-brain cortical parcellation: A hierarchical method based on dMRI tractography. // PhD Thesis, Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig. // ISBN 978-3-941504-45-5 // // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // http://creativecommons.org/licenses/by-nc/3.0 // // hCLustering is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // //--------------------------------------------------------------------------- #ifndef RANDCNBTREEBUILDER_H #define RANDCNBTREEBUILDER_H // parallel execution #include <omp.h> // std library #include <vector> #include <list> #include <string> #include <map> #include <fstream> #include <ctime> #include <climits> #include <sstream> // boost library #include <boost/filesystem.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/ref.hpp> // hClustering #include "compactTract.h" #include "WHcoord.h" #include "distBlock.h" #include "roiLoader.h" #include "WHtree.h" #include "protoNode.h" #include "fileManager.h" #include "cnbTreeBuilder.h" #define DEBUG false /** * This class simpler version of cbnTreeBuilder to build a centroid method hierarchical tree from small synthetic tractograms yoielding a random dissimilarity matrix * (no thresholding and no discarding outliers) * reads a seed voxel coordinates list, builds a centroid hierarchical tree from tractography data and writes output files */ class randCnbTreeBuilder { public: /** * Constructor * \param roiFilename file containing the list of seed voxels coordinates (for realistic neighborhood information) * \param verbose the verbose output flag */ explicit randCnbTreeBuilder( std::string roiFilename, bool verbose = true ); //! Destructor ~randCnbTreeBuilder() {} // === IN-LINE MEMBER FUNCTIONS === /** * sets the output file stream for the program log file * \param logfile a pointer to the output log file stream */ inline void log( std::ofstream* const logfile ) { m_logfile = logfile; } /** * sets the input folder * \param inputFolder path to the folder where tractogram files are located */ inline void setInputFolder( const std::string& inputFolder ) { m_inputFolder = inputFolder; } /** * sets the output folder * \param outputFolder folder where to write the created tree files */ inline void setOutputFolder( const std::string& outputFolder ) { m_outputFolder = outputFolder; } /** * sets (or resets) the debug output flag in order to write additional result files with detailed information meant for debug purposes * \param debug the true/false flag to set the m_debug member to */ inline void setDebugOutput( bool debug = true ) { m_debug = debug; } /** * sets (or resets) the verbose output flag in order to wrire progress information on the standard output * \param verbose the true/false flag to set the m_verbose member to */ inline void setVerbose( bool verbose = true ) { m_verbose = verbose; } /** * queries whether the roi file was loaded and therefore the class is ready for tree building * \return the ready flag, if true roi file has been successfully loaded */ inline bool ready() const { return m_roiLoaded; } /** * queriesfor the size of the currently loaded roi (the number of seed voxels from which the tree will be built) * \return the size of the vector containing the seed voxel coordinates */ inline size_t roiSize() const { return m_roi.size(); } // === PUBLIC MEMBER FUNCTIONS === /** * core function of this class, includes all the necessary tree building steps * \param nbLevel the seed voxel neighborhood level restriction to implement, valid values are: 6, 18, 26 (recommended), 32, 92 and 124 * \param memory the amount of RAM memory to be used for tractogram cache to speed up building the tree, in GBs (recommended value around 50% of total machine memory) * \param growType defines the type of limit for the initial homogenoeus merging stage. TC_GROWNUM = # of clusters, TC_GROWSIZE = size of clusters, TC_GROWOFF = skip this stage. * \param baseSize cluster size/number limit to stop the initial homogeneous merging stage. If set to 1 or 0 (default) this stage will be skipped * \param keepDiscarded flag to keep track of discarded voxels in a special field in the tree file, default value true */ void buildRandCentroid( const unsigned int nbLevel, const float memory, const TC_GROWTYPE growType, const size_t baseSize = 0, const bool keepDiscarded = true ); private: // === PRIVATE DATA MEMBERS === dist_t m_maxNbDist; //!< The maximum distance(dissimilarity) value that a certain tractogram can have to its most similar neighbor in order not to be disregarded as an outlier. Taken from input parameter std::string m_inputFolder; //!< The folder path that contains the seed voxel tractograms std::string m_outputFolder; //!< The folder path where to write the output files std::ofstream* m_logfile; //!< A pointer to the output log file stream WHtree m_tree; //!< The class that will hold the built tree WHcoord m_datasetSize; //!< Contains the size in voxels of the dataset where the seed voxel coordinates correspond. Necessary for proper coordinate fam conversion. Taken from file HC_GRID m_datasetGrid; //!< Containes the type of coordinate frame (vista, nifti) the input data was stored in bool m_niftiMode; //!< The Nifti flag. If true, files are coordinates are in vista reference frame, if False, in vista reference frame bool m_roiLoaded; //!< The ready flag. If true, the seed voxel list was successfully read and the class is ready to build the tree bool m_treeReady; //!< The tree building success flag. If true, the hierarchical centroid algorithm was successful and the class is ready to write the output data bool m_debug; //!< The debug output flag. If true, additional detailed outputs meant for debug will be written. bool m_verbose; //!< The verbose output flag. If true, additional and progress information will be shown through the standard output on execution. std::vector< WHcoord > m_roi; //!< A vector where the seed voxel coordinates are stored std::vector<size_t> m_trackids; //!< Stores the ids of the seed tracts correesponding to each leaf size_t m_numComps; //!< A variable to store the total number of tractogram dissimilarity comparisons done while building the tree, for post-analysis and optimizing purposes std::vector< compactTract > m_leafTracts; //!< A vector of all the tractogram objects with loaded data (only feasible if tracts are very small, this program is intended to be used with tractograms with less than 100 datapoints each) // === PRIVATE MEMBER FUNCTIONS === /** * Fetches a proto-node or proto-leaf from the appropiate vector in pointer form provided its ID. This proto-node/-leaf can be modified. * A proto-node/-leaf contains the information of the dissimilarity of a node/leaf to its neighbors during tree construction, before it has been insterted definitively in the hierarchy * \param thisNode the full-ID of the desired proto-node/-leaf * \param protoLeavesPointer a pointer to the vector containing the proto-leaves * \param protoNodesPointer a pointer to the vector containing the proto-nodes * \return a pointer to the desired protonode within the corresponding vector */ protoNode* fetchProtoNode( const nodeID_t& thisNode, std::vector< protoNode >* protoLeavesPointer, std::vector< protoNode >* protoNodesPointer ) const; /** * Fetches a node or leaf from the appropiate vector in pointer form provided its ID. This node/-leaf can be modified. * \param thisNode the full-ID of the desired node/-leaf * \param leavesPointer a pointer to the vector containing the leaves * \param nodesPointer a pointer to the the vector containing the nodes * \return a pointer to the desired node within the corresponding vector */ WHnode* fetchNode( const nodeID_t& thisNode, std::vector< WHnode >* leavesPointer, std::vector< WHnode >* nodesPointer ) const; /** * Loads all tracts into a data member vector */ void loadTracts(); /** * Finds out the neighbroghood relationships between seed voxels and calculates the tractogram dissimilarity between all neighbors, data is saved into the protoLeaves vector * \param nbLevel the neighborhood level to be considered * \param protoLeavesPointer a pointer to the vector of proto-leaves where the neghborhood information and distance to neighbors will be stored * \return a list containing the coordinates of the voxels that were discarded during the initialization process (should be empty) */ std::list< WHcoord > initialize( const unsigned int nbLevel, std::vector< protoNode >* protoLeavesPointer ); /** * Calculates the distance values between a given seed voxel tract and its seed voxel neighbors * \param currentSeedID the ID of the leaf we want to compute the neighbor distances of * \param currentTract the tractogram information corresponding to that seed voxel * \param protoLeaves the vector of proto-leaves where the neghborhood information and distance to neighbors is stored * \param nbIDs a vector with the IDs of the neighbors to the current seed voxel * \param nbLeavesPointer a pointer to a map structure where the distance to the neghbors will be stored with the neighbor ID as key * \return a bit indicating if the seed voxel is to be discarded due to the high dissimilarity to its neighbors (true) or accepted as valid (false) */ bool scanNbs( const size_t currentSeedID, const compactTract* const currentTractPointer, const std::vector< protoNode >& protoLeaves, const std::vector< size_t >& nbIDs, std::map< size_t, dist_t >* nbLeavesPointer ); /** * Writes a file with the base nodes (meta-leaves) obtained at the end of the homgeneous merging initial stage * \param baseNodes a vector with the base node IDs * \param filename the path to the file where the information will be written to */ void writeBases( const std::vector< size_t >& baseNodes, const std::string& filename ) const; /** * Writes the data files from the computed trees to the output folder */ void writeTree() const; }; #endif // RANDCNBTREEBUILDER_H
dmordom/hClustering
src/common/randCnbTreeBuilder.h
C
gpl-2.0
11,848
/* * Copyright (C) 2010,2011 Google, Inc. * * Author: * Colin Cross <ccross@android.com> * Erik Gilling <ccross@android.com> * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/resource.h> #include <linux/platform_device.h> #include <linux/dma-mapping.h> #include <linux/fsl_devices.h> #include <linux/serial_8250.h> #include <linux/i2c-tegra.h> #include <linux/platform_data/tegra_usb.h> #include <asm/pmu.h> #include <mach/irqs.h> #include <mach/iomap.h> #include <mach/dma.h> #include <mach/usb_phy.h> #include <mach/nvhost.h> #include "gpio-names.h" static struct resource i2c_resource1[] = { [0] = { .start = INT_I2C, .end = INT_I2C, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_I2C_BASE, .end = TEGRA_I2C_BASE + TEGRA_I2C_SIZE-1, .flags = IORESOURCE_MEM, }, }; static struct resource i2c_resource2[] = { [0] = { .start = INT_I2C2, .end = INT_I2C2, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_I2C2_BASE, .end = TEGRA_I2C2_BASE + TEGRA_I2C2_SIZE-1, .flags = IORESOURCE_MEM, }, }; static struct resource i2c_resource3[] = { [0] = { .start = INT_I2C3, .end = INT_I2C3, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_I2C3_BASE, .end = TEGRA_I2C3_BASE + TEGRA_I2C3_SIZE-1, .flags = IORESOURCE_MEM, }, }; static struct resource i2c_resource4[] = { [0] = { .start = INT_DVC, .end = INT_DVC, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_DVC_BASE, .end = TEGRA_DVC_BASE + TEGRA_DVC_SIZE-1, .flags = IORESOURCE_MEM, }, }; static struct tegra_i2c_platform_data tegra_i2c1_platform_data = { .bus_clk_rate = { 400000 }, }; static struct tegra_i2c_platform_data tegra_i2c2_platform_data = { .bus_clk_rate = { 400000 }, }; static struct tegra_i2c_platform_data tegra_i2c3_platform_data = { .bus_clk_rate = { 400000 }, }; static struct tegra_i2c_platform_data tegra_dvc_platform_data = { .bus_clk_rate = { 400000 }, }; struct platform_device tegra_i2c_device1 = { .name = "tegra-i2c", .id = 0, .resource = i2c_resource1, .num_resources = ARRAY_SIZE(i2c_resource1), .dev = { .platform_data = &tegra_i2c1_platform_data, }, }; struct platform_device tegra_i2c_device2 = { .name = "tegra-i2c", .id = 1, .resource = i2c_resource2, .num_resources = ARRAY_SIZE(i2c_resource2), .dev = { .platform_data = &tegra_i2c2_platform_data, }, }; struct platform_device tegra_i2c_device3 = { .name = "tegra-i2c", .id = 2, .resource = i2c_resource3, .num_resources = ARRAY_SIZE(i2c_resource3), .dev = { .platform_data = &tegra_i2c3_platform_data, }, }; struct platform_device tegra_i2c_device4 = { .name = "tegra-i2c", .id = 3, .resource = i2c_resource4, .num_resources = ARRAY_SIZE(i2c_resource4), .dev = { .platform_data = &tegra_dvc_platform_data, }, }; static struct resource spi_resource1[] = { [0] = { .start = INT_S_LINK1, .end = INT_S_LINK1, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_SPI1_BASE, .end = TEGRA_SPI1_BASE + TEGRA_SPI1_SIZE-1, .flags = IORESOURCE_MEM, }, }; static struct resource spi_resource2[] = { [0] = { .start = INT_SPI_2, .end = INT_SPI_2, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_SPI2_BASE, .end = TEGRA_SPI2_BASE + TEGRA_SPI2_SIZE-1, .flags = IORESOURCE_MEM, }, }; static struct resource spi_resource3[] = { [0] = { .start = INT_SPI_3, .end = INT_SPI_3, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_SPI3_BASE, .end = TEGRA_SPI3_BASE + TEGRA_SPI3_SIZE-1, .flags = IORESOURCE_MEM, }, }; static struct resource spi_resource4[] = { [0] = { .start = INT_SPI_4, .end = INT_SPI_4, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_SPI4_BASE, .end = TEGRA_SPI4_BASE + TEGRA_SPI4_SIZE-1, .flags = IORESOURCE_MEM, }, }; struct platform_device tegra_spi_device1 = { .name = "spi_tegra", .id = 0, .resource = spi_resource1, .num_resources = ARRAY_SIZE(spi_resource1), .dev = { .coherent_dma_mask = 0xffffffff, }, }; struct platform_device tegra_spi_device2 = { .name = "spi_tegra", .id = 1, .resource = spi_resource2, .num_resources = ARRAY_SIZE(spi_resource2), .dev = { .coherent_dma_mask = 0xffffffff, }, }; struct platform_device tegra_spi_device3 = { .name = "spi_tegra", .id = 2, .resource = spi_resource3, .num_resources = ARRAY_SIZE(spi_resource3), .dev = { .coherent_dma_mask = 0xffffffff, }, }; struct platform_device tegra_spi_device4 = { .name = "spi_tegra", .id = 3, .resource = spi_resource4, .num_resources = ARRAY_SIZE(spi_resource4), .dev = { .coherent_dma_mask = 0xffffffff, }, }; static struct resource sdhci_resource1[] = { [0] = { .start = INT_SDMMC1, .end = INT_SDMMC1, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_SDMMC1_BASE, .end = TEGRA_SDMMC1_BASE + TEGRA_SDMMC1_SIZE-1, .flags = IORESOURCE_MEM, }, }; static struct resource sdhci_resource2[] = { [0] = { .start = INT_SDMMC2, .end = INT_SDMMC2, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_SDMMC2_BASE, .end = TEGRA_SDMMC2_BASE + TEGRA_SDMMC2_SIZE-1, .flags = IORESOURCE_MEM, }, }; static struct resource sdhci_resource3[] = { [0] = { .start = INT_SDMMC3, .end = INT_SDMMC3, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_SDMMC3_BASE, .end = TEGRA_SDMMC3_BASE + TEGRA_SDMMC3_SIZE-1, .flags = IORESOURCE_MEM, }, }; static struct resource sdhci_resource4[] = { [0] = { .start = INT_SDMMC4, .end = INT_SDMMC4, .flags = IORESOURCE_IRQ, }, [1] = { .start = TEGRA_SDMMC4_BASE, .end = TEGRA_SDMMC4_BASE + TEGRA_SDMMC4_SIZE-1, .flags = IORESOURCE_MEM, }, }; /* board files should fill in platform_data register the devices themselvs. * See board-harmony.c for an example */ struct platform_device tegra_sdhci_device1 = { .name = "sdhci-tegra", .id = 0, .resource = sdhci_resource1, .num_resources = ARRAY_SIZE(sdhci_resource1), }; struct platform_device tegra_sdhci_device2 = { .name = "sdhci-tegra", .id = 1, .resource = sdhci_resource2, .num_resources = ARRAY_SIZE(sdhci_resource2), }; struct platform_device tegra_sdhci_device3 = { .name = "sdhci-tegra", .id = 2, .resource = sdhci_resource3, .num_resources = ARRAY_SIZE(sdhci_resource3), }; struct platform_device tegra_sdhci_device4 = { .name = "sdhci-tegra", .id = 3, .resource = sdhci_resource4, .num_resources = ARRAY_SIZE(sdhci_resource4), }; static struct resource tegra_usb1_resources[] = { [0] = { .start = TEGRA_USB_BASE, .end = TEGRA_USB_BASE + TEGRA_USB_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = INT_USB, .end = INT_USB, .flags = IORESOURCE_IRQ, }, }; static struct resource tegra_usb2_resources[] = { [0] = { .start = TEGRA_USB2_BASE, .end = TEGRA_USB2_BASE + TEGRA_USB2_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = INT_USB2, .end = INT_USB2, .flags = IORESOURCE_IRQ, }, }; static struct resource tegra_usb3_resources[] = { [0] = { .start = TEGRA_USB3_BASE, .end = TEGRA_USB3_BASE + TEGRA_USB3_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = INT_USB3, .end = INT_USB3, .flags = IORESOURCE_IRQ, }, }; static struct tegra_ulpi_config tegra_ehci2_ulpi_phy_config = { /* All existing boards use GPIO PV0 for phy reset */ .reset_gpio = TEGRA_GPIO_PV0, .clk = "cdev2", }; static struct tegra_ehci_platform_data tegra_ehci1_pdata = { .operating_mode = TEGRA_USB_OTG, .power_down_on_bus_suspend = 1, }; static struct tegra_ehci_platform_data tegra_ehci2_pdata = { .phy_config = &tegra_ehci2_ulpi_phy_config, .operating_mode = TEGRA_USB_HOST, .power_down_on_bus_suspend = 1, }; static struct tegra_ehci_platform_data tegra_ehci3_pdata = { .operating_mode = TEGRA_USB_HOST, .power_down_on_bus_suspend = 1, }; static u64 tegra_ehci_dmamask = DMA_BIT_MASK(32); struct platform_device tegra_ehci1_device = { .name = "tegra-ehci", .id = 0, .dev = { .dma_mask = &tegra_ehci_dmamask, .coherent_dma_mask = DMA_BIT_MASK(32), .platform_data = &tegra_ehci1_pdata, }, .resource = tegra_usb1_resources, .num_resources = ARRAY_SIZE(tegra_usb1_resources), }; struct platform_device tegra_ehci2_device = { .name = "tegra-ehci", .id = 1, .dev = { .dma_mask = &tegra_ehci_dmamask, .coherent_dma_mask = DMA_BIT_MASK(32), .platform_data = &tegra_ehci2_pdata, }, .resource = tegra_usb2_resources, .num_resources = ARRAY_SIZE(tegra_usb2_resources), }; struct platform_device tegra_ehci3_device = { .name = "tegra-ehci", .id = 2, .dev = { .dma_mask = &tegra_ehci_dmamask, .coherent_dma_mask = DMA_BIT_MASK(32), .platform_data = &tegra_ehci3_pdata, }, .resource = tegra_usb3_resources, .num_resources = ARRAY_SIZE(tegra_usb3_resources), }; static struct resource tegra_pmu_resources[] = { [0] = { .start = INT_CPU0_PMU_INTR, .end = INT_CPU0_PMU_INTR, .flags = IORESOURCE_IRQ, }, [1] = { .start = INT_CPU1_PMU_INTR, .end = INT_CPU1_PMU_INTR, .flags = IORESOURCE_IRQ, }, }; struct platform_device tegra_pmu_device = { .name = "arm-pmu", .id = ARM_PMU_DEVICE_CPU, .num_resources = ARRAY_SIZE(tegra_pmu_resources), .resource = tegra_pmu_resources, }; static struct resource tegra_uarta_resources[] = { [0] = { .start = TEGRA_UARTA_BASE, .end = TEGRA_UARTA_BASE + TEGRA_UARTA_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = INT_UARTA, .end = INT_UARTA, .flags = IORESOURCE_IRQ, }, }; static struct resource tegra_uartb_resources[] = { [0] = { .start = TEGRA_UARTB_BASE, .end = TEGRA_UARTB_BASE + TEGRA_UARTB_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = INT_UARTB, .end = INT_UARTB, .flags = IORESOURCE_IRQ, }, }; static struct resource tegra_uartc_resources[] = { [0] = { .start = TEGRA_UARTC_BASE, .end = TEGRA_UARTC_BASE + TEGRA_UARTC_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = INT_UARTC, .end = INT_UARTC, .flags = IORESOURCE_IRQ, }, }; static struct resource tegra_uartd_resources[] = { [0] = { .start = TEGRA_UARTD_BASE, .end = TEGRA_UARTD_BASE + TEGRA_UARTD_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = INT_UARTD, .end = INT_UARTD, .flags = IORESOURCE_IRQ, }, }; static struct resource tegra_uarte_resources[] = { [0] = { .start = TEGRA_UARTE_BASE, .end = TEGRA_UARTE_BASE + TEGRA_UARTE_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = INT_UARTE, .end = INT_UARTE, .flags = IORESOURCE_IRQ, }, }; struct platform_device tegra_uarta_device = { .name = "tegra_uart", .id = 0, .num_resources = ARRAY_SIZE(tegra_uarta_resources), .resource = tegra_uarta_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), }, }; struct platform_device tegra_uartb_device = { .name = "tegra_uart", .id = 1, .num_resources = ARRAY_SIZE(tegra_uartb_resources), .resource = tegra_uartb_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), }, }; struct platform_device tegra_uartc_device = { .name = "tegra_uart", .id = 2, .num_resources = ARRAY_SIZE(tegra_uartc_resources), .resource = tegra_uartc_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), }, }; struct platform_device tegra_uartd_device = { .name = "tegra_uart", .id = 3, .num_resources = ARRAY_SIZE(tegra_uartd_resources), .resource = tegra_uartd_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), }, }; struct platform_device tegra_uarte_device = { .name = "tegra_uart", .id = 4, .num_resources = ARRAY_SIZE(tegra_uarte_resources), .resource = tegra_uarte_resources, .dev = { .coherent_dma_mask = DMA_BIT_MASK(32), }, }; static struct resource i2s_resource1[] = { [0] = { .start = INT_I2S1, .end = INT_I2S1, .flags = IORESOURCE_IRQ }, [1] = { .start = TEGRA_DMA_REQ_SEL_I2S_1, .end = TEGRA_DMA_REQ_SEL_I2S_1, .flags = IORESOURCE_DMA }, [2] = { .start = TEGRA_I2S1_BASE, .end = TEGRA_I2S1_BASE + TEGRA_I2S1_SIZE - 1, .flags = IORESOURCE_MEM } }; static struct resource i2s_resource2[] = { [0] = { .start = INT_I2S2, .end = INT_I2S2, .flags = IORESOURCE_IRQ }, [1] = { .start = TEGRA_DMA_REQ_SEL_I2S2_1, .end = TEGRA_DMA_REQ_SEL_I2S2_1, .flags = IORESOURCE_DMA }, [2] = { .start = TEGRA_I2S2_BASE, .end = TEGRA_I2S2_BASE + TEGRA_I2S2_SIZE - 1, .flags = IORESOURCE_MEM } }; struct platform_device tegra_i2s_device1 = { .name = "tegra-i2s", .id = 0, .resource = i2s_resource1, .num_resources = ARRAY_SIZE(i2s_resource1), }; struct platform_device tegra_i2s_device2 = { .name = "tegra-i2s", .id = 1, .resource = i2s_resource2, .num_resources = ARRAY_SIZE(i2s_resource2), }; static struct resource tegra_das_resources[] = { [0] = { .start = TEGRA_APB_MISC_DAS_BASE, .end = TEGRA_APB_MISC_DAS_BASE + TEGRA_APB_MISC_DAS_SIZE - 1, .flags = IORESOURCE_MEM, }, }; struct platform_device tegra_das_device = { .name = "tegra-das", .id = -1, .num_resources = ARRAY_SIZE(tegra_das_resources), .resource = tegra_das_resources, }; static struct resource spdif_resource[] = { [0] = { .start = INT_SPDIF, .end = INT_SPDIF, .flags = IORESOURCE_IRQ }, [1] = { .start = TEGRA_DMA_REQ_SEL_SPD_I, .end = TEGRA_DMA_REQ_SEL_SPD_I, .flags = IORESOURCE_DMA }, [2] = { .start = TEGRA_SPDIF_BASE, .end = TEGRA_SPDIF_BASE + TEGRA_SPDIF_SIZE - 1, .flags = IORESOURCE_MEM } }; struct platform_device tegra_spdif_device = { .name = "tegra-spdif", .id = -1, .resource = spdif_resource, .num_resources = ARRAY_SIZE(spdif_resource), }; struct platform_device tegra_pcm_device = { .name = "tegra-pcm-audio", .id = -1, }; static struct resource tegra_kbc_resources[] = { [0] = { .start = TEGRA_KBC_BASE, .end = TEGRA_KBC_BASE + TEGRA_KBC_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = INT_KBC, .end = INT_KBC, .flags = IORESOURCE_IRQ, }, }; struct platform_device tegra_kbc_device = { .name = "tegra-kbc", .id = -1, .resource = tegra_kbc_resources, .num_resources = ARRAY_SIZE(tegra_kbc_resources), }; static struct resource tegra_rtc_resources[] = { [0] = { .start = TEGRA_RTC_BASE, .end = TEGRA_RTC_BASE + TEGRA_RTC_SIZE - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = INT_RTC, .end = INT_RTC, .flags = IORESOURCE_IRQ, }, }; struct platform_device tegra_rtc_device = { .name = "tegra_rtc", .id = -1, .resource = tegra_rtc_resources, .num_resources = ARRAY_SIZE(tegra_rtc_resources), }; static struct resource tegra_grhost_resources[] = { { .start = TEGRA_HOST1X_BASE, .end = TEGRA_HOST1X_BASE + TEGRA_HOST1X_SIZE - 1, .flags = IORESOURCE_MEM, }, { .start = TEGRA_DISPLAY_BASE, .end = TEGRA_DISPLAY_BASE + TEGRA_DISPLAY_SIZE - 1, .flags = IORESOURCE_MEM, }, { .start = TEGRA_DISPLAY2_BASE, .end = TEGRA_DISPLAY2_BASE + TEGRA_DISPLAY2_SIZE - 1, .flags = IORESOURCE_MEM, }, { .start = TEGRA_VI_BASE, .end = TEGRA_VI_BASE + TEGRA_VI_SIZE - 1, .flags = IORESOURCE_MEM, }, { .start = TEGRA_ISP_BASE, .end = TEGRA_ISP_BASE + TEGRA_ISP_SIZE - 1, .flags = IORESOURCE_MEM, }, { .start = TEGRA_MPE_BASE, .end = TEGRA_MPE_BASE + TEGRA_MPE_SIZE - 1, .flags = IORESOURCE_MEM, }, { .start = INT_SYNCPT_THRESH_BASE, .end = INT_SYNCPT_THRESH_BASE + INT_SYNCPT_THRESH_NR - 1, .flags = IORESOURCE_IRQ, }, { .start = INT_HOST1X_MPCORE_GENERAL, .end = INT_HOST1X_MPCORE_GENERAL, .flags = IORESOURCE_IRQ, }, }; struct platform_device tegra_grhost_device = { .name = "tegra_grhost", .id = -1, .resource = tegra_grhost_resources, .num_resources = ARRAY_SIZE(tegra_grhost_resources), }; static struct resource tegra_pwfm0_resource = { .start = TEGRA_PWFM0_BASE, .end = TEGRA_PWFM0_BASE + TEGRA_PWFM0_SIZE - 1, .flags = IORESOURCE_MEM, }; static struct resource tegra_pwfm1_resource = { .start = TEGRA_PWFM1_BASE, .end = TEGRA_PWFM1_BASE + TEGRA_PWFM1_SIZE - 1, .flags = IORESOURCE_MEM, }; static struct resource tegra_pwfm2_resource = { .start = TEGRA_PWFM2_BASE, .end = TEGRA_PWFM2_BASE + TEGRA_PWFM2_SIZE - 1, .flags = IORESOURCE_MEM, }; static struct resource tegra_pwfm3_resource = { .start = TEGRA_PWFM3_BASE, .end = TEGRA_PWFM3_BASE + TEGRA_PWFM3_SIZE - 1, .flags = IORESOURCE_MEM, }; struct platform_device tegra_pwfm0_device = { .name = "tegra_pwm", .id = 0, .num_resources = 1, .resource = &tegra_pwfm0_resource, }; struct platform_device tegra_pwfm1_device = { .name = "tegra_pwm", .id = 1, .num_resources = 1, .resource = &tegra_pwfm1_resource, }; struct platform_device tegra_pwfm2_device = { .name = "tegra_pwm", .id = 2, .num_resources = 1, .resource = &tegra_pwfm2_resource, }; struct platform_device tegra_pwfm3_device = { .name = "tegra_pwm", .id = 3, .num_resources = 1, .resource = &tegra_pwfm3_resource, }; static struct resource tegra_gart_resources[] = { [0] = { .name = "mc", .flags = IORESOURCE_MEM, .start = TEGRA_MC_BASE, .end = TEGRA_MC_BASE + TEGRA_MC_SIZE - 1, }, [1] = { .name = "gart", .flags = IORESOURCE_MEM, .start = TEGRA_GART_BASE, .end = TEGRA_GART_BASE + TEGRA_GART_SIZE - 1, } }; struct platform_device tegra_gart_device = { .name = "tegra_gart", .id = -1, .num_resources = ARRAY_SIZE(tegra_gart_resources), .resource = tegra_gart_resources }; static struct resource tegra_camera_resources[] = { { .name = "regs", .start = TEGRA_VI_BASE, .end = TEGRA_VI_BASE + TEGRA_VI_SIZE - 1, .flags = IORESOURCE_MEM, }, }; static u64 tegra_camera_dma_mask = DMA_BIT_MASK(32); struct nvhost_device tegra_camera_device = { .name = "tegra-camera", .id = 0, .dev = { .dma_mask = &tegra_camera_dma_mask, .coherent_dma_mask = 0xffffffff, }, .num_resources = ARRAY_SIZE(tegra_camera_resources), .resource = tegra_camera_resources, }; static struct resource tegra_avp_resources[] = { [0] = { .start = INT_SHR_SEM_INBOX_IBF, .end = INT_SHR_SEM_INBOX_IBF, .flags = IORESOURCE_IRQ, .name = "mbox_from_avp_pending", }, }; struct platform_device tegra_avp_device = { .name = "tegra-avp", .id = -1, .num_resources = ARRAY_SIZE(tegra_avp_resources), .resource = tegra_avp_resources, .dev = { .coherent_dma_mask = 0xffffffffULL, }, }; static struct resource tegra_aes_resources[] = { { .start = TEGRA_VDE_BASE, .end = TEGRA_VDE_BASE + TEGRA_VDE_SIZE - 1, .flags = IORESOURCE_MEM, }, { .start = INT_VDE_BSE_V, .end = INT_VDE_BSE_V, .flags = IORESOURCE_IRQ, }, }; static u64 tegra_aes_dma_mask = DMA_BIT_MASK(32); struct platform_device tegra_aes_device = { .name = "tegra-aes", .id = -1, .resource = tegra_aes_resources, .num_resources = ARRAY_SIZE(tegra_aes_resources), .dev = { .dma_mask = &tegra_aes_dma_mask, .coherent_dma_mask = DMA_BIT_MASK(32), }, };
vSlipenchuk/ac100hd
arch/arm/mach-tegra/devices.c
C
gpl-2.0
19,164
<?php require '../../class.rest.php'; require '../../config.php'; $rest = new FmRestAPI(); $rest->setApiKey( FM_API_KEY ); $rest->setApiSecret( FM_API_SECRET ); $data = array( 'name' => 'Example list name', 'description' => 'Not required', 'custom_fields' => array( array( 'name' => 'custom_field_1' ) ) ); //testing transactional mail request try { $response = $rest->doRequest('subscribers_list/create', $data); echo 'List created, received data: '; var_dump($response); echo PHP_EOL; } catch (Exception $e) { echo 'Error message: '.$e->getMessage().', Error code: '.$e->getCode().', HTTP code: '.$rest->getHttpCode().PHP_EOL; }
qunabu/drupal-freshmail
api/samples/list/list.php
PHP
gpl-2.0
712
from __future__ import absolute_import import os import sys import shutil import unittest import xml.dom.minidom parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, parentdir) from pcs_test_functions import pcs,ac import rule empty_cib = "empty.xml" temp_cib = "temp.xml" class DateValueTest(unittest.TestCase): def testParse(self): for value, item in enumerate(rule.DateCommonValue.allowed_items, 1): self.assertEquals( str(value), rule.DateCommonValue("%s=%s" % (item, value)).parts[item] ) value = rule.DateCommonValue( "hours=1 monthdays=2 weekdays=3 yeardays=4 months=5 weeks=6 " "years=7 weekyears=8 moon=9" ) self.assertEquals("1", value.parts["hours"]) self.assertEquals("2", value.parts["monthdays"]) self.assertEquals("3", value.parts["weekdays"]) self.assertEquals("4", value.parts["yeardays"]) self.assertEquals("5", value.parts["months"]) self.assertEquals("6", value.parts["weeks"]) self.assertEquals("7", value.parts["years"]) self.assertEquals("8", value.parts["weekyears"]) self.assertEquals("9", value.parts["moon"]) value = rule.DateCommonValue("hours=1 monthdays=2 hours=3") self.assertEquals("2", value.parts["monthdays"]) self.assertEquals("3", value.parts["hours"]) value = rule.DateCommonValue(" hours=1 monthdays=2 hours=3 ") self.assertEquals("2", value.parts["monthdays"]) self.assertEquals("3", value.parts["hours"]) self.assertSyntaxError( "missing one of 'hours=', 'monthdays=', 'weekdays=', 'yeardays=', " "'months=', 'weeks=', 'years=', 'weekyears=', 'moon=' in date-spec", "", rule.DateSpecValue ) self.assertSyntaxError( "missing value after 'hours=' in date-spec", "hours=", rule.DateSpecValue ) self.assertSyntaxError( "missing =value after 'hours' in date-spec", "hours", rule.DateSpecValue ) self.assertSyntaxError( "unexpected 'foo=bar' in date-spec", "foo=bar", rule.DateSpecValue ) self.assertSyntaxError( "unexpected 'foo=bar' in date-spec", "hours=1 foo=bar", rule.DateSpecValue ) def testDurationValidate(self): for value, item in enumerate(rule.DateCommonValue.allowed_items, 1): self.assertEquals( str(value), rule.DateDurationValue("%s=%s" % (item, value)).parts[item] ) for item in rule.DateCommonValue.allowed_items: self.assertSyntaxError( "invalid %s '%s' in 'duration'" % (item, "foo"), "%s=foo" % item, rule.DateDurationValue ) self.assertSyntaxError( "invalid %s '%s' in 'duration'" % (item, "-1"), "%s=-1" % item, rule.DateDurationValue ) self.assertSyntaxError( "invalid %s '%s' in 'duration'" % (item, "2foo"), "%s=2foo" % item, rule.DateDurationValue ) def testDateSpecValidation(self): for item in rule.DateCommonValue.allowed_items: value = 1 self.assertEquals( str(value), rule.DateSpecValue("%s=%s" % (item, value)).parts[item] ) self.assertEquals( "%s-%s" % (value, value + 1), rule.DateSpecValue( "%s=%s-%s" % (item, value, value + 1) ).parts[item] ) self.assertEquals( "hours=9-16 weekdays=1-5", str(rule.DateSpecValue("hours=9-16 weekdays=1-5")) ) for item in rule.DateCommonValue.allowed_items: self.assertSyntaxError( "invalid %s '%s' in 'date-spec'" % (item, "foo"), "%s=foo" % item, rule.DateSpecValue ) self.assertSyntaxError( "invalid %s '%s' in 'date-spec'" % (item, "1-foo"), "%s=1-foo" % item, rule.DateSpecValue ) self.assertSyntaxError( "invalid %s '%s' in 'date-spec'" % (item, "foo-1"), "%s=foo-1" % item, rule.DateSpecValue ) self.assertSyntaxError( "invalid %s '%s' in 'date-spec'" % (item, "1-2-3"), "%s=1-2-3" % item, rule.DateSpecValue ) self.assertSyntaxError( "invalid %s '%s' in 'date-spec'" % (item, "2-1"), "%s=2-1" % item, rule.DateSpecValue ) self.assertSyntaxError( "invalid hours '24' in 'date-spec'", "hours=24", rule.DateSpecValue ) self.assertSyntaxError( "invalid monthdays '32' in 'date-spec'", "monthdays=32", rule.DateSpecValue ) self.assertSyntaxError( "invalid weekdays '8' in 'date-spec'", "weekdays=8", rule.DateSpecValue ) self.assertSyntaxError( "invalid yeardays '367' in 'date-spec'", "yeardays=367", rule.DateSpecValue ) self.assertSyntaxError( "invalid months '13' in 'date-spec'", "months=13", rule.DateSpecValue ) self.assertSyntaxError( "invalid weeks '54' in 'date-spec'", "weeks=54", rule.DateSpecValue ) self.assertSyntaxError( "invalid weekyears '54' in 'date-spec'", "weekyears=54", rule.DateSpecValue ) self.assertSyntaxError( "invalid moon '8' in 'date-spec'", "moon=8", rule.DateSpecValue ) self.assertSyntaxError( "invalid hours '12-8' in 'date-spec'", "hours=12-8", rule.DateSpecValue ) def assertSyntaxError(self, syntax_error, parts_string, value_class=None): value_class = value_class if value_class else rule.DateCommonValue self.assertRaises(rule.SyntaxError, value_class, parts_string) try: value_class(parts_string) except rule.SyntaxError as e: self.assertEquals(syntax_error, str(e)) class ParserTest(unittest.TestCase): def setUp(self): self.parser = rule.RuleParser() def testEmptyInput(self): self.assertRaises(rule.UnexpectedEndOfInput, self.parser.parse, []) def testSingleLiteral(self): self.assertSyntaxError( "missing one of 'eq', 'ne', 'lt', 'gt', 'lte', 'gte', 'in_range', " "'defined', 'not_defined', 'date-spec'", ["#uname"] ) self.assertSyntaxError( "missing one of 'eq', 'ne', 'lt', 'gt', 'lte', 'gte', 'in_range', " "'defined', 'not_defined', 'date-spec'", ["string", "node1"] ) def testSingleLiteralDatespec(self): self.assertEquals( "(date-spec (literal hours=1))", str(self.parser.parse(["date-spec", "hours=1"])) ) self.assertEquals( "(date-spec (literal hours=1-14 months=1 monthdays=20-30))", str(self.parser.parse([ "date-spec", "hours=1-14 months=1 monthdays=20-30" ])) ) self.assertUnexpectedEndOfInput(["date-spec"]) def testSimpleExpression(self): self.assertEquals( "(eq (literal #uname) (literal node1))", str(self.parser.parse(["#uname", "eq", "node1"])) ) self.assertEquals( "(ne (literal #uname) (literal node2))", str(self.parser.parse(["#uname", "ne", "node2"])) ) self.assertEquals( "(gt (literal int) (literal 123))", str(self.parser.parse(["int", "gt", "123"])) ) self.assertEquals( "(gte (literal int) (literal 123))", str(self.parser.parse(["int", "gte", "123"])) ) self.assertEquals( "(lt (literal int) (literal 123))", str(self.parser.parse(["int", "lt", "123"])) ) self.assertEquals( "(lte (literal int) (literal 123))", str(self.parser.parse(["int", "lte", "123"])) ) def testSimpleExpressionBad(self): self.assertSyntaxError( "unexpected 'eq'", ["eq"] ) self.assertUnexpectedEndOfInput(["#uname", "eq"]) self.assertSyntaxError( "unexpected 'node1'", ["#uname", "node1"] ) self.assertSyntaxError( "unexpected 'eq'", ["eq", "#uname"] ) self.assertSyntaxError( "unexpected 'eq'", ["eq", "lt"] ) self.assertSyntaxError( "unexpected 'string' before 'eq'", ["string", "#uname", "eq", "node1"] ) self.assertSyntaxError( "unexpected 'date-spec' before 'eq'", ["date-spec", "hours=1", "eq", "node1"] ) self.assertSyntaxError( "unexpected 'date-spec' after 'eq'", ["#uname", "eq", "date-spec", "hours=1"] ) self.assertSyntaxError( "unexpected 'duration' before 'eq'", ["duration", "hours=1", "eq", "node1"] ) self.assertSyntaxError( "unexpected 'duration' after 'eq'", ["#uname", "eq", "duration", "hours=1"] ) def testDefinedExpression(self): self.assertEquals( "(defined (literal pingd))", str(self.parser.parse(["defined", "pingd"])) ) self.assertEquals( "(not_defined (literal pingd))", str(self.parser.parse(["not_defined", "pingd"])) ) def testDefinedExpressionBad(self): self.assertUnexpectedEndOfInput(["defined"]) self.assertUnexpectedEndOfInput(["not_defined"]) self.assertSyntaxError( "unexpected 'eq'", ["defined", "eq"] ) self.assertSyntaxError( "unexpected 'and'", ["defined", "and"] ) self.assertSyntaxError( "unexpected 'string' after 'defined'", ["defined", "string", "pingd"] ) self.assertSyntaxError( "unexpected 'date-spec' after 'defined'", ["defined", "date-spec", "hours=1"] ) self.assertSyntaxError( "unexpected 'duration' after 'defined'", ["defined", "duration", "hours=1"] ) def testTypeExpression(self): self.assertEquals( "(eq (literal #uname) (string (literal node1)))", str(self.parser.parse(["#uname", "eq", "string", "node1"])) ) self.assertEquals( "(eq (literal #uname) (integer (literal 12345)))", str(self.parser.parse(["#uname", "eq", "integer", "12345"])) ) self.assertEquals( "(eq (literal #uname) (integer (literal -12345)))", str(self.parser.parse(["#uname", "eq", "integer", "-12345"])) ) self.assertEquals( "(eq (literal #uname) (version (literal 1)))", str(self.parser.parse(["#uname", "eq", "version", "1"])) ) self.assertEquals( "(eq (literal #uname) (version (literal 1.2.3)))", str(self.parser.parse(["#uname", "eq", "version", "1.2.3"])) ) self.assertEquals( "(eq (literal #uname) (string (literal string)))", str(self.parser.parse(["#uname", "eq", "string", "string"])) ) self.assertEquals( "(eq (literal #uname) (string (literal and)))", str(self.parser.parse(["#uname", "eq", "string", "and"])) ) self.assertEquals( "(and " "(ne (literal #uname) (string (literal integer))) " "(ne (literal #uname) (string (literal version)))" ")", str(self.parser.parse([ "#uname", "ne", "string", "integer", "and", "#uname", "ne", "string", "version" ])) ) def testTypeExpressionBad(self): self.assertUnexpectedEndOfInput(["string"]) self.assertUnexpectedEndOfInput(["#uname", "eq", "string"]) self.assertSyntaxError( "unexpected 'string' before 'eq'", ["string", "#uname", "eq", "node1"] ) self.assertSyntaxError( "invalid integer value 'node1'", ["#uname", "eq", "integer", "node1"] ) self.assertSyntaxError( "invalid version value 'node1'", ["#uname", "eq", "version", "node1"] ) def testDateExpression(self): self.assertEquals( "(gt (literal date) (literal 2014-06-26))", str(self.parser.parse(["date", "gt", "2014-06-26"])) ) self.assertEquals( "(lt (literal date) (literal 2014-06-26))", str(self.parser.parse(["date", "lt", "2014-06-26"])) ) self.assertEquals( "(in_range " "(literal date) (literal 2014-06-26) (literal 2014-07-26)" ")", str(self.parser.parse([ "date", "in_range", "2014-06-26", "to", "2014-07-26" ])) ) self.assertEquals( "(in_range " "(literal date) " "(literal 2014-06-26) (duration (literal years=1))" ")", str(self.parser.parse([ "date", "in_range", "2014-06-26", "to", "duration", "years=1" ])) ) def testDateExpressionBad(self): self.assertUnexpectedEndOfInput( ["date", "in_range"] ) self.assertSyntaxError( "missing 'to'", ["date", "in_range", '2014-06-26'] ) self.assertUnexpectedEndOfInput( ["date", "in_range", "2014-06-26", "to"] ) self.assertSyntaxError( "unexpected 'in_range'", ["in_range", '2014-06-26', "to", "2014-07-26"] ) self.assertSyntaxError( "expecting 'to', got 'eq'", ["date", "in_range", '#uname', "eq", "node1", "to", "2014-07-26"] ) self.assertSyntaxError( "invalid date '#uname' in 'in_range ... to'", ["date", "in_range", "2014-06-26", "to", '#uname', "eq", "node1"] ) self.assertSyntaxError( "unexpected 'defined' after 'in_range'", ["date", "in_range", "defined", "pingd", "to", "2014-07-26"] ) self.assertSyntaxError( "unexpected 'defined' after 'in_range ... to'", ["date", "in_range", "2014-06-26", "to", "defined", "pingd"] ) self.assertSyntaxError( "unexpected 'string' before 'in_range'", ["string", "date", "in_range", '2014-06-26', "to", "2014-07-26"] ) self.assertSyntaxError( "unexpected 'string' after 'in_range'", ["date", "in_range", "string", '2014-06-26', "to", "2014-07-26"] ) self.assertSyntaxError( "unexpected 'string' after 'in_range ... to'", ["date", "in_range", '2014-06-26', "to", "string", "2014-07-26"] ) self.assertSyntaxError( "unexpected 'string' after '2014-06-26'", ["date", "in_range", '2014-06-26', "string", "to", "2014-07-26"] ) self.assertSyntaxError( "unexpected '#uname' before 'in_range'", ["#uname", "in_range", '2014-06-26', "to", "2014-07-26"] ) self.assertSyntaxError( "invalid date '2014-13-26' in 'in_range ... to'", ["date", "in_range", '2014-13-26', "to", "2014-07-26"] ) self.assertSyntaxError( "invalid date '2014-13-26' in 'in_range ... to'", ["date", "in_range", '2014-06-26', "to", "2014-13-26"] ) def testAndOrExpression(self): self.assertEquals( "(and " "(ne (literal #uname) (literal node1)) " "(ne (literal #uname) (literal node2))" ")", str(self.parser.parse([ "#uname", "ne", "node1", "and", "#uname", "ne", "node2" ])) ) self.assertEquals( "(or " "(eq (literal #uname) (literal node1)) " "(eq (literal #uname) (literal node2))" ")", str(self.parser.parse([ "#uname", "eq", "node1", "or", "#uname", "eq", "node2" ])) ) self.assertEquals( "(and " "(and " "(ne (literal #uname) (literal node1)) " "(ne (literal #uname) (literal node2))" ") " "(ne (literal #uname) (literal node3))" ")", str(self.parser.parse([ "#uname", "ne", "node1", "and", "#uname", "ne", "node2", "and", "#uname", "ne", "node3" ])) ) self.assertEquals( "(or " "(and " "(ne (literal #uname) (literal node1)) " "(ne (literal #uname) (literal node2))" ") " "(eq (literal #uname) (literal node3))" ")", str(self.parser.parse([ "#uname", "ne", "node1", "and", "#uname", "ne", "node2", "or", "#uname", "eq", "node3" ])) ) self.assertEquals( "(and " "(or " "(eq (literal #uname) (literal node1)) " "(eq (literal #uname) (literal node2))" ") " "(ne (literal #uname) (literal node3))" ")", str(self.parser.parse([ "#uname", "eq", "node1", "or", "#uname", "eq", "node2", "and", "#uname", "ne", "node3" ])) ) self.assertEquals( "(and " "(defined (literal pingd)) " "(lte (literal pingd) (literal 1))" ")", str(self.parser.parse([ "defined", "pingd", "and", "pingd", "lte", "1" ])) ) self.assertEquals( "(or " "(gt (literal pingd) (literal 1)) " "(not_defined (literal pingd))" ")", str(self.parser.parse([ "pingd", "gt", "1", "or", "not_defined", "pingd" ])) ) def testAndOrExpressionDateSpec(self): self.assertEquals( "(and " "(ne (literal #uname) (literal node1)) " "(date-spec (literal hours=1-12))" ")", str(self.parser.parse([ "#uname", "ne", "node1", "and", "date-spec", "hours=1-12" ])) ) self.assertEquals( "(or " "(date-spec (literal monthdays=1-12)) " "(ne (literal #uname) (literal node1))" ")", str(self.parser.parse([ "date-spec", "monthdays=1-12", "or", "#uname", "ne", "node1" ])) ) self.assertEquals( "(or " "(date-spec (literal monthdays=1-10)) " "(date-spec (literal monthdays=11-20))" ")", str(self.parser.parse([ "date-spec", "monthdays=1-10", "or", "date-spec", "monthdays=11-20" ])) ) def testAndOrExpressionDate(self): self.assertEquals( "(and " "(ne (literal #uname) (literal node1)) " "(in_range " "(literal date) (literal 2014-06-26) (literal 2014-07-26)" ")" ")", str(self.parser.parse([ "#uname", "ne", "node1", "and", "date", "in_range", "2014-06-26", "to", "2014-07-26" ])) ) self.assertEquals( "(and " "(in_range " "(literal date) (literal 2014-06-26) (literal 2014-07-26)" ") " "(ne (literal #uname) (literal node1))" ")", str(self.parser.parse([ "date", "in_range", "2014-06-26", "to", "2014-07-26", "and", "#uname", "ne", "node1" ])) ) def testAndOrExpressionBad(self): self.assertSyntaxError( "unexpected 'and'", ["and"] ) self.assertSyntaxError( "unexpected 'or'", ["or"] ) self.assertSyntaxError( "unexpected '#uname' before 'and'", ["#uname", "and", "node1"] ) self.assertSyntaxError( "unexpected '#uname' before 'or'", ["#uname", "or", "node1"] ) self.assertSyntaxError( "unexpected '#uname' before 'or'", ["#uname", "or", "eq"] ) self.assertSyntaxError( "unexpected 'node2' after 'and'", ["#uname", "eq", "node1", "and", "node2"] ) self.assertUnexpectedEndOfInput(["#uname", "eq", "node1", "and"]) self.assertUnexpectedEndOfInput( ["#uname", "eq", "node1", "and", "#uname", "eq"] ) self.assertSyntaxError( "unexpected 'and'", ["and", "#uname", "eq", "node1"] ) self.assertSyntaxError( "unexpected 'duration' after 'and'", ["#uname", "ne", "node1", "and", "duration", "hours=1"] ) self.assertSyntaxError( "unexpected 'duration' before 'or'", ["duration", "monthdays=1", "or", "#uname", "ne", "node1"] ) def testParenthesizedExpression(self): self.assertSyntaxError( "missing one of 'eq', 'ne', 'lt', 'gt', 'lte', 'gte', 'in_range', " "'defined', 'not_defined', 'date-spec'", ["(", "#uname", ")"] ) self.assertEquals( "(date-spec (literal hours=1))", str(self.parser.parse(["(", "date-spec", "hours=1", ")"])) ) self.assertEquals( "(eq (literal #uname) (literal node1))", str(self.parser.parse(["(", "#uname", "eq", "node1", ")"])) ) self.assertEquals( "(defined (literal pingd))", str(self.parser.parse(["(", "defined", "pingd", ")"])) ) self.assertEquals( "(and " "(ne (literal #uname) (literal node1)) " "(ne (literal #uname) (literal node2))" ")", str(self.parser.parse([ "(", "#uname", "ne", "node1", "and", "#uname", "ne", "node2", ")" ])) ) self.assertEquals( "(and " "(ne (literal #uname) (literal node1)) " "(ne (literal #uname) (literal node2))" ")", str(self.parser.parse([ "(", "#uname", "ne", "node1", ")", "and", "(", "#uname", "ne", "node2", ")" ])) ) self.assertEquals( "(or " "(and " "(ne (literal #uname) (literal node1)) " "(ne (literal #uname) (literal node2))" ") " "(eq (literal #uname) (literal node3))" ")", str(self.parser.parse([ "(", "#uname", "ne", "node1", "and", "#uname", "ne", "node2", ")", "or", "#uname", "eq", "node3" ])) ) self.assertEquals( "(and " "(ne (literal #uname) (literal node1)) " "(or " "(ne (literal #uname) (literal node2)) " "(eq (literal #uname) (literal node3))" ")" ")", str(self.parser.parse([ "#uname", "ne", "node1", "and", "(", "#uname", "ne", "node2", "or", "#uname", "eq", "node3", ")" ])) ) self.assertEquals( "(and " "(ne (literal #uname) (literal node1)) " "(or " "(ne (literal #uname) (literal node2)) " "(eq (literal #uname) (literal node3))" ")" ")", str(self.parser.parse([ "(", "(", "(", "#uname", "ne", "node1", ")", "and", "(", "(", "(", "#uname", "ne", "node2", ")", "or", "(", "#uname", "eq", "node3", ")", ")", ")", ")", ")" ])) ) self.assertEquals( "(in_range " "(literal date) (literal 2014-06-26) (literal 2014-07-26)" ")", str(self.parser.parse([ "(", "date", "in_range", "2014-06-26", "to", "2014-07-26", ")" ])) ) def testParenthesizedExpressionBad(self): self.assertUnexpectedEndOfInput(["("]) self.assertSyntaxError( "unexpected ')'", ["(", ")"] ) self.assertSyntaxError( "missing ')'", ["(", "#uname"] ) self.assertUnexpectedEndOfInput(["(", "#uname", "eq"]) self.assertSyntaxError( "missing ')'", ["(", "#uname", "eq", "node1"] ) def assertUnexpectedEndOfInput(self, program): self.assertRaises(rule.UnexpectedEndOfInput, self.parser.parse, program) def assertSyntaxError(self, syntax_error, program): self.assertRaises( rule.SyntaxError, self.parser.parse, program ) try: self.parser.parse(program) except rule.SyntaxError as e: self.assertEquals(syntax_error, str(e)) class CibBuilderTest(unittest.TestCase): def setUp(self): self.parser = rule.RuleParser() self.builder = rule.CibBuilder() def testSingleLiteralDatespec(self): self.assertExpressionXml( ["date-spec", "hours=1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <date_expression id="location-dummy-rule-expr" operation="date_spec"> <date_spec hours="1" id="location-dummy-rule-expr-datespec"/> </date_expression> </rule> </rsc_location> """ ) self.assertExpressionXml( ["date-spec", "hours=1-14 monthdays=20-30 months=1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <date_expression id="location-dummy-rule-expr" operation="date_spec"> <date_spec hours="1-14" id="location-dummy-rule-expr-datespec" monthdays="20-30" months="1"/> </date_expression> </rule> </rsc_location> """ ) def testSimpleExpression(self): self.assertExpressionXml( ["#uname", "eq", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["#uname", "ne", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="ne" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["#uname", "gt", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="gt" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["#uname", "gte", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="gte" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["#uname", "lt", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="lt" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["#uname", "lte", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="lte" value="node1"/> </rule> </rsc_location> """ ) def testTypeExpression(self): self.assertExpressionXml( ["#uname", "eq", "string", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" type="string" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["#uname", "eq", "integer", "12345"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" type="number" value="12345"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["#uname", "eq", "version", "1.2.3"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" type="version" value="1.2.3"/> </rule> </rsc_location> """ ) def testDefinedExpression(self): self.assertExpressionXml( ["defined", "pingd"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="pingd" id="location-dummy-rule-expr" operation="defined"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["not_defined", "pingd"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="pingd" id="location-dummy-rule-expr" operation="not_defined"/> </rule> </rsc_location> """ ) def testDateExpression(self): self.assertExpressionXml( ["date", "gt", "2014-06-26"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <date_expression id="location-dummy-rule-expr" operation="gt" start="2014-06-26"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["date", "lt", "2014-06-26"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <date_expression end="2014-06-26" id="location-dummy-rule-expr" operation="lt"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["date", "in_range", "2014-06-26", "to", "2014-07-26"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <date_expression end="2014-07-26" id="location-dummy-rule-expr" operation="in_range" start="2014-06-26"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["date", "in_range", "2014-06-26", "to", "duration", "years=1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <date_expression id="location-dummy-rule-expr" operation="in_range" start="2014-06-26"> <duration id="location-dummy-rule-expr-duration" years="1"/> </date_expression> </rule> </rsc_location> """ ) def testNotDateExpression(self): self.assertExpressionXml( ["date", "eq", "2014-06-26"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="date" id="location-dummy-rule-expr" operation="eq" value="2014-06-26"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["date", "gt", "string", "2014-06-26"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="date" id="location-dummy-rule-expr" operation="gt" type="string" value="2014-06-26"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["date", "gt", "integer", "12345"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="date" id="location-dummy-rule-expr" operation="gt" type="number" value="12345"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["date", "gt", "version", "1.2.3"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule"> <expression attribute="date" id="location-dummy-rule-expr" operation="gt" type="version" value="1.2.3"/> </rule> </rsc_location> """ ) def testAndOrExpression(self): self.assertExpressionXml( ["#uname", "ne", "node1", "and", "#uname", "ne", "node2"], """ <rsc_location id="location-dummy"> <rule boolean-op="and" id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="ne" value="node1"/> <expression attribute="#uname" id="location-dummy-rule-expr-1" operation="ne" value="node2"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["#uname", "eq", "node1", "or", "#uname", "eq", "node2"], """ <rsc_location id="location-dummy"> <rule boolean-op="or" id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node1"/> <expression attribute="#uname" id="location-dummy-rule-expr-1" operation="eq" value="node2"/> </rule> </rsc_location> """ ) self.assertExpressionXml( [ "#uname", "ne", "node1", "and", "#uname", "ne", "node2", "and", "#uname", "ne", "node3" ], """ <rsc_location id="location-dummy"> <rule boolean-op="and" id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="ne" value="node1"/> <expression attribute="#uname" id="location-dummy-rule-expr-1" operation="ne" value="node2"/> <expression attribute="#uname" id="location-dummy-rule-expr-2" operation="ne" value="node3"/> </rule> </rsc_location> """ ) self.assertExpressionXml( [ "#uname", "ne", "node1", "and", "#uname", "ne", "node2", "or", "#uname", "eq", "node3" ], """ <rsc_location id="location-dummy"> <rule boolean-op="or" id="location-dummy-rule"> <rule boolean-op="and" id="location-dummy-rule-rule"> <expression attribute="#uname" id="location-dummy-rule-rule-expr" operation="ne" value="node1"/> <expression attribute="#uname" id="location-dummy-rule-rule-expr-1" operation="ne" value="node2"/> </rule> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node3"/> </rule> </rsc_location> """ ) self.assertExpressionXml( [ "#uname", "eq", "node1", "or", "#uname", "eq", "node2", "and", "#uname", "ne", "node3" ], """ <rsc_location id="location-dummy"> <rule boolean-op="and" id="location-dummy-rule"> <rule boolean-op="or" id="location-dummy-rule-rule"> <expression attribute="#uname" id="location-dummy-rule-rule-expr" operation="eq" value="node1"/> <expression attribute="#uname" id="location-dummy-rule-rule-expr-1" operation="eq" value="node2"/> </rule> <expression attribute="#uname" id="location-dummy-rule-expr" operation="ne" value="node3"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["defined", "pingd", "and", "pingd", "lte", "1"], """ <rsc_location id="location-dummy"> <rule boolean-op="and" id="location-dummy-rule"> <expression attribute="pingd" id="location-dummy-rule-expr" operation="defined"/> <expression attribute="pingd" id="location-dummy-rule-expr-1" operation="lte" value="1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["pingd", "gt", "1", "or", "not_defined", "pingd"], """ <rsc_location id="location-dummy"> <rule boolean-op="or" id="location-dummy-rule"> <expression attribute="pingd" id="location-dummy-rule-expr" operation="gt" value="1"/> <expression attribute="pingd" id="location-dummy-rule-expr-1" operation="not_defined"/> </rule> </rsc_location> """ ) def testAndOrExpressionDateSpec(self): self.assertExpressionXml( ["#uname", "ne", "node1", "and", "date-spec", "hours=1-12"], """ <rsc_location id="location-dummy"> <rule boolean-op="and" id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="ne" value="node1"/> <date_expression id="location-dummy-rule-expr-1" operation="date_spec"> <date_spec hours="1-12" id="location-dummy-rule-expr-1-datespec"/> </date_expression> </rule> </rsc_location> """ ) self.assertExpressionXml( ["date-spec", "monthdays=1-12", "or", "#uname", "ne", "node1"], """ <rsc_location id="location-dummy"> <rule boolean-op="or" id="location-dummy-rule"> <date_expression id="location-dummy-rule-expr" operation="date_spec"> <date_spec id="location-dummy-rule-expr-datespec" monthdays="1-12"/> </date_expression> <expression attribute="#uname" id="location-dummy-rule-expr-1" operation="ne" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["date-spec", "monthdays=1-10", "or", "date-spec", "monthdays=11-20"], """ <rsc_location id="location-dummy"> <rule boolean-op="or" id="location-dummy-rule"> <date_expression id="location-dummy-rule-expr" operation="date_spec"> <date_spec id="location-dummy-rule-expr-datespec" monthdays="1-10"/> </date_expression> <date_expression id="location-dummy-rule-expr-1" operation="date_spec"> <date_spec id="location-dummy-rule-expr-1-datespec" monthdays="11-20"/> </date_expression> </rule> </rsc_location> """ ) def testParenthesizedExpression(self): self.assertExpressionXml( [ "(", "#uname", "ne", "node1", "and", "#uname", "ne", "node2", ")", "or", "#uname", "eq", "node3" ], """ <rsc_location id="location-dummy"> <rule boolean-op="or" id="location-dummy-rule"> <rule boolean-op="and" id="location-dummy-rule-rule"> <expression attribute="#uname" id="location-dummy-rule-rule-expr" operation="ne" value="node1"/> <expression attribute="#uname" id="location-dummy-rule-rule-expr-1" operation="ne" value="node2"/> </rule> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node3"/> </rule> </rsc_location> """ ) self.assertExpressionXml( [ "#uname", "ne", "node1", "and", "(", "#uname", "ne", "node2", "or", "#uname", "eq", "node3", ")" ], """ <rsc_location id="location-dummy"> <rule boolean-op="and" id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="ne" value="node1"/> <rule boolean-op="or" id="location-dummy-rule-rule"> <expression attribute="#uname" id="location-dummy-rule-rule-expr" operation="ne" value="node2"/> <expression attribute="#uname" id="location-dummy-rule-rule-expr-1" operation="eq" value="node3"/> </rule> </rule> </rsc_location> """ ) self.assertExpressionXml( [ "(", "#uname", "ne", "node1", "and", "#uname", "ne", "node2", ")", "or", "(", "#uname", "ne", "node3", "and", "#uname", "ne", "node4", ")", ], """ <rsc_location id="location-dummy"> <rule boolean-op="or" id="location-dummy-rule"> <rule boolean-op="and" id="location-dummy-rule-rule"> <expression attribute="#uname" id="location-dummy-rule-rule-expr" operation="ne" value="node1"/> <expression attribute="#uname" id="location-dummy-rule-rule-expr-1" operation="ne" value="node2"/> </rule> <rule boolean-op="and" id="location-dummy-rule-rule-1"> <expression attribute="#uname" id="location-dummy-rule-rule-1-expr" operation="ne" value="node3"/> <expression attribute="#uname" id="location-dummy-rule-rule-1-expr-1" operation="ne" value="node4"/> </rule> </rule> </rsc_location> """ ) self.assertExpressionXml( [ "(", "#uname", "ne", "node1", "and", "#uname", "ne", "node2", ")", "and", "(", "#uname", "ne", "node3", "and", "#uname", "ne", "node4", ")", ], """ <rsc_location id="location-dummy"> <rule boolean-op="and" id="location-dummy-rule"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="ne" value="node1"/> <expression attribute="#uname" id="location-dummy-rule-expr-1" operation="ne" value="node2"/> <expression attribute="#uname" id="location-dummy-rule-expr-2" operation="ne" value="node3"/> <expression attribute="#uname" id="location-dummy-rule-expr-3" operation="ne" value="node4"/> </rule> </rsc_location> """ ) def assertExpressionXml(self, rule_expression, rule_xml): cib_dom = xml.dom.minidom.parse("empty.xml") constraints = cib_dom.getElementsByTagName("constraints")[0] constraint_el = constraints.appendChild( cib_dom.createElement("rsc_location") ) constraint_el.setAttribute("id", "location-dummy") ac( self.builder.build( constraint_el, self.parser.parse(rule_expression) ).parentNode.toprettyxml(indent=" "), rule_xml.lstrip().rstrip(" ") ) class TokenPreprocessorTest(unittest.TestCase): def setUp(self): self.preprocessor = rule.TokenPreprocessor() def testNoChanges(self): self.assertEquals([], self.preprocessor.run([])) self.assertEquals( ["#uname", "eq", "node1"], self.preprocessor.run(["#uname", "eq", "node1"]) ) def testDateSpec(self): self.assertEquals( ["date-spec"], self.preprocessor.run(["date-spec"]) ) self.assertEquals( ["date-spec", "hours=14"], self.preprocessor.run(["date-spec", "hours=14"]) ) self.assertEquals( ["date-spec", "hours weeks=6 months= moon=1"], self.preprocessor.run( ["date-spec", "hours", "weeks=6", "months=", "moon=1"] ) ) self.assertEquals( ["date-spec", "foo", "hours=14"], self.preprocessor.run(["date-spec", "foo", "hours=14"]) ) self.assertEquals( ["date-spec", "hours=14", "foo", "hours=14"], self.preprocessor.run(["date-spec", "hours=14", "foo", "hours=14"]) ) self.assertEquals( [ "date-spec", "hours=1 monthdays=2 weekdays=3 yeardays=4 months=5 " "weeks=6 years=7 weekyears=8 moon=9" ], self.preprocessor.run([ "date-spec", "hours=1", "monthdays=2", "weekdays=3", "yeardays=4", "months=5","weeks=6", "years=7", "weekyears=8", "moon=9" ]) ) self.assertEquals( ["#uname", "eq", "node1", "or", "date-spec", "hours=14"], self.preprocessor.run([ "#uname", "eq", "node1", "or", "date-spec", "hours=14" ]) ) self.assertEquals( ["date-spec", "hours=14", "or", "#uname", "eq", "node1"], self.preprocessor.run([ "date-spec", "hours=14", "or", "#uname", "eq", "node1", ]) ) def testDuration(self): self.assertEquals( ["duration"], self.preprocessor.run(["duration"]) ) self.assertEquals( ["duration", "hours=14"], self.preprocessor.run(["duration", "hours=14"]) ) self.assertEquals( ["duration", "hours weeks=6 months= moon=1"], self.preprocessor.run( ["duration", "hours", "weeks=6", "months=", "moon=1"] ) ) self.assertEquals( ["duration", "foo", "hours=14"], self.preprocessor.run(["duration", "foo", "hours=14"]) ) self.assertEquals( ["duration", "hours=14", "foo", "hours=14"], self.preprocessor.run(["duration", "hours=14", "foo", "hours=14"]) ) self.assertEquals( [ "duration", "hours=1 monthdays=2 weekdays=3 yeardays=4 months=5 " "weeks=6 years=7 weekyears=8 moon=9" ], self.preprocessor.run([ "duration", "hours=1", "monthdays=2", "weekdays=3", "yeardays=4", "months=5","weeks=6", "years=7", "weekyears=8", "moon=9" ]) ) self.assertEquals( ["#uname", "eq", "node1", "or", "duration", "hours=14"], self.preprocessor.run([ "#uname", "eq", "node1", "or", "duration", "hours=14" ]) ) self.assertEquals( ["duration", "hours=14", "or", "#uname", "eq", "node1"], self.preprocessor.run([ "duration", "hours=14", "or", "#uname", "eq", "node1", ]) ) def testOperationDatespec(self): self.assertEquals( ["date-spec", "weeks=6 moon=1"], self.preprocessor.run( ["date-spec", "operation=date_spec", "weeks=6", "moon=1"] ) ) self.assertEquals( ["date-spec", "weeks=6 moon=1"], self.preprocessor.run( ["date-spec", "weeks=6", "operation=date_spec", "moon=1"] ) ) self.assertEquals( ["date-spec", "weeks=6", "foo", "moon=1"], self.preprocessor.run( ["date-spec", "weeks=6", "operation=date_spec", "foo", "moon=1"] ) ) self.assertEquals( ["date-spec", "weeks=6", "foo", "operation=date_spec", "moon=1"], self.preprocessor.run( ["date-spec", "weeks=6", "foo", "operation=date_spec", "moon=1"] ) ) self.assertEquals( ["date-spec", "weeks=6 moon=1"], self.preprocessor.run( ["date-spec", "weeks=6", "moon=1", "operation=date_spec"] ) ) self.assertEquals( ["date-spec", "weeks=6 moon=1", "foo"], self.preprocessor.run( ["date-spec", "weeks=6", "moon=1", "operation=date_spec", "foo"] ) ) self.assertEquals( ["date-spec"], self.preprocessor.run( ["date-spec", "operation=date_spec"] ) ) self.assertEquals( ["date-spec", "weeks=6", "operation=foo", "moon=1"], self.preprocessor.run( ["date-spec", "weeks=6", "operation=foo", "moon=1"] ) ) def testDateLegacySyntax(self): # valid syntax self.assertEquals( ["date", "gt", "2014-06-26"], self.preprocessor.run([ "date", "start=2014-06-26", "gt" ]) ) self.assertEquals( ["date", "lt", "2014-06-26"], self.preprocessor.run([ "date", "end=2014-06-26", "lt" ]) ) self.assertEquals( ["date", "in_range", "2014-06-26", "to", "2014-07-26"], self.preprocessor.run([ "date", "start=2014-06-26", "end=2014-07-26", "in_range" ]) ) self.assertEquals( ["date", "in_range", "2014-06-26", "to", "2014-07-26"], self.preprocessor.run([ "date", "end=2014-07-26", "start=2014-06-26", "in_range" ]) ) self.assertEquals( ["date", "gt", "2014-06-26", "foo"], self.preprocessor.run([ "date", "start=2014-06-26", "gt", "foo" ]) ) self.assertEquals( ["date", "lt", "2014-06-26", "foo"], self.preprocessor.run([ "date", "end=2014-06-26", "lt", "foo" ]) ) self.assertEquals( ["date", "in_range", "2014-06-26", "to", "2014-07-26", "foo"], self.preprocessor.run([ "date", "start=2014-06-26", "end=2014-07-26", "in_range", "foo" ]) ) self.assertEquals( ["date", "in_range", "2014-06-26", "to", "2014-07-26", "foo"], self.preprocessor.run([ "date", "end=2014-07-26", "start=2014-06-26", "in_range", "foo" ]) ) # invalid syntax - no change self.assertEquals( ["date"], self.preprocessor.run([ "date" ]) ) self.assertEquals( ["date", "start=2014-06-26"], self.preprocessor.run([ "date", "start=2014-06-26" ]) ) self.assertEquals( ["date", "end=2014-06-26"], self.preprocessor.run([ "date", "end=2014-06-26" ]) ) self.assertEquals( ["date", "start=2014-06-26", "end=2014-07-26"], self.preprocessor.run([ "date", "start=2014-06-26", "end=2014-07-26" ]) ) self.assertEquals( ["date", "start=2014-06-26", "end=2014-07-26", "lt"], self.preprocessor.run([ "date", "start=2014-06-26", "end=2014-07-26", "lt" ]) ) self.assertEquals( ["date", "start=2014-06-26", "lt", "foo"], self.preprocessor.run([ "date", "start=2014-06-26", "lt", "foo" ]) ) self.assertEquals( ["date", "start=2014-06-26", "end=2014-07-26", "gt", "foo"], self.preprocessor.run([ "date", "start=2014-06-26", "end=2014-07-26", "gt", "foo" ]) ) self.assertEquals( ["date", "end=2014-06-26", "gt"], self.preprocessor.run([ "date", "end=2014-06-26", "gt" ]) ) self.assertEquals( ["date", "start=2014-06-26", "in_range", "foo"], self.preprocessor.run([ "date", "start=2014-06-26", "in_range", "foo" ]) ) self.assertEquals( ["date", "end=2014-07-26", "in_range"], self.preprocessor.run([ "date", "end=2014-07-26", "in_range" ]) ) self.assertEquals( ["foo", "start=2014-06-26", "gt"], self.preprocessor.run([ "foo", "start=2014-06-26", "gt" ]) ) self.assertEquals( ["foo", "end=2014-06-26", "lt"], self.preprocessor.run([ "foo", "end=2014-06-26", "lt" ]) ) def testParenthesis(self): self.assertEquals( ["("], self.preprocessor.run(["("]) ) self.assertEquals( [")"], self.preprocessor.run([")"]) ) self.assertEquals( ["(", "(", ")", ")"], self.preprocessor.run(["(", "(", ")", ")"]) ) self.assertEquals( ["(", "(", ")", ")"], self.preprocessor.run(["(())"]) ) self.assertEquals( ["a", "(", "b", ")", "c"], self.preprocessor.run(["a", "(", "b", ")", "c"]) ) self.assertEquals( ["a", "(", "b", "c", ")", "d"], self.preprocessor.run(["a", "(", "b", "c", ")", "d"]) ) self.assertEquals( ["a", ")", "b", "(", "c"], self.preprocessor.run(["a", ")", "b", "(", "c"]) ) self.assertEquals( ["a", "(", "b", ")", "c"], self.preprocessor.run(["a", "(b)", "c"]) ) self.assertEquals( ["a", "(", "b", ")", "c"], self.preprocessor.run(["a(", "b", ")c"]) ) self.assertEquals( ["a", "(", "b", ")", "c"], self.preprocessor.run(["a(b)c"]) ) self.assertEquals( ["aA", "(", "bB", ")", "cC"], self.preprocessor.run(["aA(bB)cC"]) ) self.assertEquals( ["(", "aA", "(", "bB", ")", "cC", ")"], self.preprocessor.run(["(aA(bB)cC)"]) ) self.assertEquals( ["(", "aA", "(", "(", "bB", ")", "cC", ")"], self.preprocessor.run(["(aA(", "(bB)cC)"]) ) self.assertEquals( ["(", "aA", "(", "(", "(", "bB", ")", "cC", ")"], self.preprocessor.run(["(aA(", "(", "(bB)cC)"]) ) class ExportAsExpressionTest(unittest.TestCase): def test_success(self): self.assertXmlExport( """ <rule id="location-dummy-rule" score="INFINITY"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node1"/> </rule> """, "#uname eq node1", "#uname eq string node1" ) self.assertXmlExport( """ <rule id="location-dummy-rule" score="INFINITY"> <expression attribute="foo" id="location-dummy-rule-expr" operation="gt" type="version" value="1.2.3"/> </rule> """, "foo gt version 1.2.3", "foo gt version 1.2.3" ) self.assertXmlExport( """ <rule boolean-op="or" id="complexRule" score="INFINITY"> <rule boolean-op="and" id="complexRule-rule-1" score="0"> <date_expression id="complexRule-rule-1-expr" operation="date_spec"> <date_spec id="complexRule-rule-1-expr-datespec" weekdays="1-5" hours="12-23"/> </date_expression> <date_expression id="complexRule-rule-1-expr-1" operation="in_range" start="2014-07-26"> <duration id="complexRule-rule-1-expr-1-duration" months="1"/> </date_expression> </rule> <rule boolean-op="and" id="complexRule-rule" score="0"> <expression attribute="foo" id="complexRule-rule-expr-1" operation="gt" type="version" value="1.2"/> <expression attribute="#uname" id="complexRule-rule-expr" operation="eq" value="node3 4"/> </rule> </rule> """, "(date-spec hours=12-23 weekdays=1-5 and date in_range 2014-07-26 to duration months=1) or (foo gt version 1.2 and #uname eq \"node3 4\")", "(#uname eq string \"node3 4\" and foo gt version 1.2) or (date in_range 2014-07-26 to duration months=1 and date-spec hours=12-23 weekdays=1-5)" ) def assertXmlExport(self, rule_xml, export, export_normalized): ac( export + "\n", rule.ExportAsExpression().get_string( xml.dom.minidom.parseString(rule_xml).documentElement, normalize=False ) + "\n" ) ac( export_normalized + "\n", rule.ExportAsExpression().get_string( xml.dom.minidom.parseString(rule_xml).documentElement, normalize=True ) + "\n" ) class DomRuleAddTest(unittest.TestCase): def setUp(self): shutil.copy(empty_cib, temp_cib) output, returnVal = pcs(temp_cib, "resource create dummy1 Dummy") assert returnVal == 0 and output == "" def test_success_xml(self): self.assertExpressionXml( ["#uname", "eq", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule" score="INFINITY"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["id=myRule", "#uname", "eq", "node1"], """ <rsc_location id="location-dummy"> <rule id="myRule" score="INFINITY"> <expression attribute="#uname" id="myRule-expr" operation="eq" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["score=INFINITY", "#uname", "eq", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule" score="INFINITY"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["score=100", "#uname", "eq", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule" score="100"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["score-attribute=pingd", "#uname", "eq", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule" score-attribute="pingd"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["role=master", "#uname", "eq", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule" role="master" score="INFINITY"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["role=slave", "#uname", "eq", "node1"], """ <rsc_location id="location-dummy"> <rule id="location-dummy-rule" role="slave" score="INFINITY"> <expression attribute="#uname" id="location-dummy-rule-expr" operation="eq" value="node1"/> </rule> </rsc_location> """ ) self.assertExpressionXml( ["score=100", "id=myRule", "role=master", "#uname", "eq", "node1"], """ <rsc_location id="location-dummy"> <rule id="myRule" role="master" score="100"> <expression attribute="#uname" id="myRule-expr" operation="eq" value="node1"/> </rule> </rsc_location> """ ) def test_success(self): output, returnVal = pcs( temp_cib, "constraint location dummy1 rule #uname eq node1" ) ac(output, "") self.assertEquals(0, returnVal) output, returnVal = pcs( temp_cib, "constraint location dummy1 rule id=MyRule score=100 role=master #uname eq node2" ) ac(output, "") self.assertEquals(0, returnVal) output, returnVal = pcs( temp_cib, "constraint location dummy1 rule id=complexRule (#uname eq node3 and foo gt version 1.2) or (date-spec hours=12-23 weekdays=1-5 and date in_range 2014-07-26 to duration months=1)" ) ac(output, "") self.assertEquals(0, returnVal) output, returnVal = pcs(temp_cib, "constraint location show --full") ac(output, """\ Location Constraints: Resource: dummy1 Constraint: location-dummy1 Rule: score=INFINITY (id:location-dummy1-rule) Expression: #uname eq node1 (id:location-dummy1-rule-expr) Constraint: location-dummy1-1 Rule: score=100 role=master (id:MyRule) Expression: #uname eq node2 (id:MyRule-expr) Constraint: location-dummy1-2 Rule: score=INFINITY boolean-op=or (id:complexRule) Rule: score=0 boolean-op=and (id:complexRule-rule) Expression: #uname eq node3 (id:complexRule-rule-expr) Expression: foo gt version 1.2 (id:complexRule-rule-expr-1) Rule: score=0 boolean-op=and (id:complexRule-rule-1) Expression: (id:complexRule-rule-1-expr) Date Spec: hours=12-23 weekdays=1-5 (id:complexRule-rule-1-expr-datespec) Expression: date in_range 2014-07-26 to duration (id:complexRule-rule-1-expr-1) Duration: months=1 (id:complexRule-rule-1-expr-1-duration) """) self.assertEquals(0, returnVal) output, returnVal = pcs(temp_cib, "constraint location show") ac(output, """\ Location Constraints: Resource: dummy1 Constraint: location-dummy1 Rule: score=INFINITY Expression: #uname eq node1 Constraint: location-dummy1-1 Rule: score=100 role=master Expression: #uname eq node2 Constraint: location-dummy1-2 Rule: score=INFINITY boolean-op=or Rule: score=0 boolean-op=and Expression: #uname eq node3 Expression: foo gt version 1.2 Rule: score=0 boolean-op=and Expression: Date Spec: hours=12-23 weekdays=1-5 Expression: date in_range 2014-07-26 to duration Duration: months=1 """) self.assertEquals(0, returnVal) def test_invalid_score(self): output, returnVal = pcs( temp_cib, "constraint location dummy1 rule score=pingd defined pingd" ) ac( output, "Warning: invalid score 'pingd', setting score-attribute=pingd " "instead\n" ) self.assertEquals(0, returnVal) output, returnVal = pcs(temp_cib, "constraint location show --full") ac(output, """\ Location Constraints: Resource: dummy1 Constraint: location-dummy1 Rule: score-attribute=pingd (id:location-dummy1-rule) Expression: defined pingd (id:location-dummy1-rule-expr) """) self.assertEquals(0, returnVal) def test_invalid_rule(self): output, returnVal = pcs( temp_cib, "constraint location dummy1 rule score=100" ) ac(output, "Error: no rule expression was specified\n") self.assertEquals(1, returnVal) output, returnVal = pcs( temp_cib, "constraint location dummy1 rule #uname eq" ) ac( output, "Error: '#uname eq' is not a valid rule expression: unexpected end " "of rule\n" ) self.assertEquals(1, returnVal) output, returnVal = pcs( temp_cib, "constraint location dummy1 rule string #uname eq node1" ) ac( output, "Error: 'string #uname eq node1' is not a valid rule expression: " "unexpected 'string' before 'eq'\n" ) self.assertEquals(1, returnVal) def test_ivalid_options(self): output, returnVal = pcs( temp_cib, "constraint location dummy1 rule role=foo #uname eq node1" ) ac(output, "Error: invalid role 'foo', use 'master' or 'slave'\n") self.assertEquals(1, returnVal) output, returnVal = pcs( temp_cib, "constraint location dummy1 rule score=100 score-attribute=pingd #uname eq node1" ) ac(output, "Error: can not specify both score and score-attribute\n") self.assertEquals(1, returnVal) output, returnVal = pcs( temp_cib, "constraint location dummy1 rule id=1foo #uname eq node1" ) ac( output, "Error: invalid rule id '1foo', '1' is not a valid first character " "for a rule id\n" ) self.assertEquals(1, returnVal) output, returnVal = pcs(temp_cib, "constraint location show --full") ac(output, "Location Constraints:\n") self.assertEquals(0, returnVal) output, returnVal = pcs( temp_cib, "constraint location dummy1 rule id=MyRule #uname eq node1" ) ac(output, "") self.assertEquals(0, returnVal) output, returnVal = pcs(temp_cib, "constraint location show --full") ac(output, """\ Location Constraints: Resource: dummy1 Constraint: location-dummy1 Rule: score=INFINITY (id:MyRule) Expression: #uname eq node1 (id:MyRule-expr) """) self.assertEquals(0, returnVal) output, returnVal = pcs( temp_cib, "constraint location dummy1 rule id=MyRule #uname eq node1" ) ac( output, "Error: id 'MyRule' is already in use, please specify another one\n" ) self.assertEquals(1, returnVal) def assertExpressionXml(self, rule_expression, rule_xml): cib_dom = xml.dom.minidom.parse("empty.xml") constraints = cib_dom.getElementsByTagName("constraints")[0] constraint_el = constraints.appendChild( cib_dom.createElement("rsc_location") ) constraint_el.setAttribute("id", "location-dummy") options, rule_argv = rule.parse_argv(rule_expression) rule.dom_rule_add(constraint_el, options, rule_argv) ac( constraint_el.toprettyxml(indent=" "), rule_xml.lstrip().rstrip(" ") ) if __name__ == "__main__": unittest.main()
tradej/pcs
pcs/test/test_rule.py
Python
gpl-2.0
67,998
<?php class Database { private static $connection = FALSE; //connection to be opened private static $mysqli = NULL; //Database Information private static $db_host = NULL; private static $db_name = NULL; private static $db_user = NULL; private static $db_pass = NULL; private static $db_table_prefix = NULL; public static function init($db_host, $db_name, $db_user, $db_pass, $prefix) { self::$db_table_prefix = $prefix; self::$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name); } public static function query($query_string) { //performs query over alerady opened connection, if not open, it opens connection 1st } public static function get() { return self::$mysqli; } public static function prefix() { return self::$db_table_prefix; } public static function create($table = NULL, $query = NULL) { if($table == NULL || $query == NULL) return; $sql = "CREATE TABLE IF NOT EXISTS ".self::$db_table_prefix."$table ($query)"; if(self::$mysqli->prepare($sql)->execute()) return TRUE; else return FALSE; } public static function delete($table = NULL, $statement = NULL, $values = NULL) { if($table == NULL || $statement == NULL || $values == NULL ) return; if(!is_array($values)) $values = (array)($values); $succ = TRUE; $stmt = self::$mysqli->prepare("DELETE FROM ".self::$db_table_prefix.$table." WHERE $statement"); foreach($values as $value) { $type = "s"; if(is_int($value)) $type = "i"; $stmt->bind_param($type, $value); $succ &= $stmt->execute(); } $stmt->close(); return $succ; } public static function join($table = NULL, $attrs = NULL, $joins = NULL/*$condition = NULL, $values = NULL*/) { if($table == NULL || $attrs == NULL) return array(); $result = array(); if(!is_array($attrs)) $attrs = (array)($attrs); if(!is_array($joins)) $joins = (array)($joins); $key = NULL; foreach($attrs as $k => $value) { $search = strtr($value, array('[' => '', ']' => '')); if($search != $value) { $key = $search; $attrs[$k] = $search; } $attrs[$k]=str_replace("{prefix}", self::$db_table_prefix, $value); } $sql = "SELECT DISTINCT ".implode(", ", $attrs)." FROM ".self::$db_table_prefix.$table; foreach($joins as $from => $data) { $on = $data[0]; $values = $data[1]; if(!is_array($values)) $values = (array)($values); $condition_string = str_replace(array("?","="," "), "", $on)." = "; $finds = array_filter(explode('\?', $on)); $values = array_unique($values); asort($values); $values = array_map ( function ($el) { $strict = strtr($el, array('!' => '', '!' => '')); if($strict != $el) return "{$strict}"; else return "'{$el}'"; } , $values ); if (count($finds) == 1) $finds[1] = implode(" OR $condition_string", $values); foreach($finds as $k => $find) { if($find == "''") $finds[$k]=""; else $finds[$k] = str_replace("{prefix}", self::$db_table_prefix, $find); } $finds = str_replace("?", "", implode('', $finds)); $sql.=" INNER JOIN ".str_replace("{prefix}", self::$db_table_prefix, $from)." ON $finds"; } //echo "<pre style='font-weight: bold;'>$sql</pre>"; $stmt = self::$mysqli->prepare($sql); $stmt->execute(); $stmt->store_result(); $variables = array(); $data = array(); $meta = $stmt->result_metadata(); while($field = $meta->fetch_field()) $variables[] = &$data[$field->name]; call_user_func_array(array($stmt, 'bind_result'), $variables); if($key==NULL) { $i = 0; while($stmt->fetch()) { $result[$i] = array(); foreach($data as $k=>$v) $result[$i][$k] = $v; $i++; } } else { $pointer = 0; while($stmt->fetch()) { $temp = array(); foreach($data as $k=>$v) { if($key==$k) $pointer=$v; $temp[$k] = $v; } $result[$pointer]=$temp; } } $stmt->close(); return $result; } public static function entryExists($table = NULL, $condition = NULL, $values = NULL) { if($table == NULL || $condition == NULL || $values == NULL) return FALSE; if(!is_array($values)) $values = (array)($values); // echo "<pre>SELECT * FROM ".self::$db_table_prefix.$table." WHERE $condition LIMIT 1</pre>"; $stmt = self::$mysqli->prepare("SELECT * FROM ".self::$db_table_prefix.$table." WHERE $condition LIMIT 1"); foreach($values as $value) { $type = "s"; if(is_int($value)) $type = "i"; $stmt->bind_param($type, $value); } $stmt->execute(); $stmt->store_result(); $count=$stmt->num_rows; $stmt->close(); return $count>0; } public static function select($table = NULL, $attrs = NULL, $condition = NULL, $values = NULL) { $heal_check = ($values == NULL || (is_array($values) && count($values)<1)); if($table == NULL || $attrs == NULL) return array(); if($condition != NULL && ($heal_check)) return array(); $result = array(); if(!is_array($attrs)) { if($attrs==NULL) $arrts = array(); else $attrs = (array)($attrs); } if(!is_array($values)) { if($values==NULL) $values = array(); else $values = (array)($values); } $key = NULL; foreach($attrs as $k => $value) { $search = strtr($value, array('[' => '', ']' => '')); if($search != $value) { $key=$search; $attrs[$k]=$search; } } if($condition == NULL || $heal_check == TRUE) { $stmt = self::$mysqli->prepare("SELECT ".implode(", ", $attrs)." FROM ".self::$db_table_prefix.$table); // echo "<pre>YYY SELECT ".implode(", ", $attrs)." FROM ".self::$db_table_prefix.$table."</pre>"; } else { $condition_string = str_replace(array("?","="," "), "", $condition)." = "; $finds = explode('\?', $condition); $values = array_unique($values); asort($values); $values = array_map(function ($el) { return "'{$el}'"; }, $values); if (count($finds) == 1) $finds[1] = implode(" OR $condition_string", $values); $finds = str_replace("?", "", implode('', $finds)); $stmt = self::$mysqli->prepare("SELECT ".implode(", ", $attrs)." FROM ".self::$db_table_prefix.$table." WHERE $finds"); // echo "<pre>XXX SELECT ".implode(", ", $attrs)." FROM ".self::$db_table_prefix.$table." WHERE $finds"."</pre>"; } $stmt->execute(); $variables = array(); $data = array(); $meta = $stmt->result_metadata(); while($field = $meta->fetch_field()) $variables[] = &$data[$field->name]; call_user_func_array(array($stmt, 'bind_result'), $variables); if($key==NULL) { $i = 0; while($stmt->fetch()) { $result[$i] = array(); foreach($data as $k=>$v) $result[$i][$k] = $v; $i++; } } else { $pointer = 0; while($stmt->fetch()) { $temp = array(); foreach($data as $k=>$v) { if($key==$k) $pointer=$v; $temp[$k] = $v; } $result[$pointer]=$temp; } } $stmt->close(); return $result; } public static function insert($table = NULL, $values = NULL) { if($table == NULL || $values == NULL || !is_array($values) || count($values) < 1) return; $succ = TRUE; if(count($values) != count($values, COUNT_RECURSIVE)) { $stmt = self::$mysqli->prepare("INSERT INTO ".self::$db_table_prefix.$table." (" . implode(", ", array_keys($values[0])) . ") VALUES (" . implode(", ", array_map(function($value) { return "?"; }, $values[0])) . ")"); foreach($values as $value) { $bind = new Param(); $qArray = array(); foreach($value as $key => $line) { $qArray[] = "$key = ?"; $type = "s"; if(is_int($line)) $type = "i"; $bind->add($type, $line); } call_user_func_array( array($stmt, 'bind_param'), $bind->get()); $succ &= $stmt->execute(); } $stmt->close(); } else { $stmt = self::$mysqli->prepare("INSERT INTO ".self::$db_table_prefix.$table." (" . implode(", ", array_keys($values)) . ") VALUES (" . implode(", ", array_map(function($value) { return "?"; }, $values)) . ")"); $bind = new Param(); $qArray = array(); foreach($values as $key => $line) { $qArray[] = "$key = ?"; $type = "s"; if(is_int($line)) $type = "i"; $bind->add($type, $line); } call_user_func_array( array($stmt, 'bind_param'), $bind->get()); $succ &= $stmt->execute(); $stmt->close(); } return $succ; } public static function update($table = NULL, $where_statement = NULL, $where_values = NULL, $update_statement = NULL, $update_value = NULL) { // echo "0"; if($table == NULL || $where_statement == NULL || $update_statement == NULL || $update_value == NULL || $where_values == NULL ) { // echo "1"; // echo ($table==NULL)?"<pre>table is null</pre>":""; // echo ($where_statement==NULL)?"<pre>where statement is null</pre>":""; // echo ($update_statement==NULL)?"<pre>update statement is null</pre>":""; // echo ($update_value==NULL)?"<pre>update value is null</pre>":""; // echo ($where_values==NULL)?"<pre>where values is null</pre>":""; return false; } // echo "A"; if(!is_array($where_values)) $where_values = (array)($where_values); // echo "B"; $succ = TRUE; // echo "C"; // echo "<pre>UPDATE ".self::$db_table_prefix.$table." SET ".$update_statement." WHERE $where_statement</pre>"; $stmt = self::$mysqli->prepare("UPDATE ".self::$db_table_prefix.$table." SET ".$update_statement." WHERE $where_statement"); $bind = new Param(); $qArray = array(); $update_type = "s"; if(is_int($update_value)) $update_type = "i"; foreach($where_values as $key => $line) { $qArray[] = "$key = ?"; $type = "s"; if(is_int($line)) $type = "i"; $bind->add($update_type, $update_value); $bind->add($type, $line); } call_user_func_array(array($stmt, 'bind_param'), $bind->get()); $succ &= $stmt->execute(); $stmt->close(); return $succ; } public static function alter($table = NULL, $alters = NULL) { if($table == NULL || $alters == NULL) return; $succ = TRUE; foreach($alters as $key => $value) { $succ &= self::$mysqli->query("ALTER TABLE ".self::$db_table_prefix."$table $key = $value"); } return $succ; } } class Param { private $values = array(), $types = ''; public function add( $type, &$value ) { $this->values[] = $value; $this->types .= $type; } public function get() { $arr = array_merge(array($this->types), $this->values); $refs = array(); foreach ($arr as $key => $value) { $refs[$key] = &$arr[$key]; } return $refs; } } ?>
jancajthaml/pureDatabase
Database.php
PHP
gpl-2.0
11,288
<?php defined('_JEXEC') or die(); ?> <div class="jshop"> <h1><?php echo $this->vendor->shop_name?></h1> <?php if ($this->display_list_products){ ?> <div class="jshop_list_product"> <?php include(dirname(__FILE__)."/../".$this->template_block_form_filter); if (count($this->rows)){ include(dirname(__FILE__)."/../".$this->template_block_list_product); }else{ include(dirname(__FILE__)."/../".$this->template_no_list_product); } if ($this->display_pagination){ include(dirname(__FILE__)."/../".$this->template_block_pagination); } ?> </div> <?php }?> </div>
Zhurakovsky/happystore
components/com_jshopping/templates/default_div/vendor/products.php
PHP
gpl-2.0
623
showWord(["n. ","Fo cheve. Madan Benwa mete perik.<br>"])
georgejhunt/HaitiDictionary.activity
data/words/perik.js
JavaScript
gpl-2.0
57
# # Makefile for reconinstruments. # obj-$(CONFIG_JET_PROXMUX) += proxmux.o proxmux-objs := jet_proxmux.o \ mux_queue.o obj-$(CONFIG_JET_SENSORS) += sensors.o sensors-objs := i2c_transfer.o \ jet_lsm9ds0.o \ jet_lps25h.o \ jet_sensors.o obj-$(CONFIG_JET_TMP103_FLEX) +=jet_tmp103_flex.o obj-$(CONFIG_MFI) += mfi.o obj-$(CONFIG_APDS9900) += apds9900.o obj-$(CONFIG_TFA98xx) += tfa98xx.o obj-$(CONFIG_JET_CAMERA_MT9M114) += jet_mt9m114.o
ReconInstruments/jet_kernel
drivers/misc/recon/Makefile
Makefile
gpl-2.0
478
/* * Copyright (c) 2011 - 2012 Samsung Electronics Co., Ltd. * http://www.samsung.com * * Samsung EXYNOS5 SoC series G-Scaler driver * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 2 of the License, * or (at your option) any later version. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/bug.h> #include <linux/interrupt.h> #include <linux/workqueue.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/list.h> #include <linux/io.h> #include <linux/slab.h> #include <linux/clk.h> #include <linux/of.h> #include <media/v4l2-ioctl.h> #include "gsc-core.h" #define GSC_CLOCK_GATE_NAME "gscl" static const struct gsc_fmt gsc_formats[] = { { .name = "RGB565", .pixelformat = V4L2_PIX_FMT_RGB565X, .depth = { 16 }, .color = GSC_RGB, .num_planes = 1, .num_comp = 1, }, { .name = "XRGB-8-8-8-8, 32 bpp", .pixelformat = V4L2_PIX_FMT_RGB32, .depth = { 32 }, .color = GSC_RGB, .num_planes = 1, .num_comp = 1, }, { .name = "YUV 4:2:2 packed, YCbYCr", .pixelformat = V4L2_PIX_FMT_YUYV, .depth = { 16 }, .color = GSC_YUV422, .yorder = GSC_LSB_Y, .corder = GSC_CBCR, .num_planes = 1, .num_comp = 1, .mbus_code = MEDIA_BUS_FMT_YUYV8_2X8, }, { .name = "YUV 4:2:2 packed, CbYCrY", .pixelformat = V4L2_PIX_FMT_UYVY, .depth = { 16 }, .color = GSC_YUV422, .yorder = GSC_LSB_C, .corder = GSC_CBCR, .num_planes = 1, .num_comp = 1, .mbus_code = MEDIA_BUS_FMT_UYVY8_2X8, }, { .name = "YUV 4:2:2 packed, CrYCbY", .pixelformat = V4L2_PIX_FMT_VYUY, .depth = { 16 }, .color = GSC_YUV422, .yorder = GSC_LSB_C, .corder = GSC_CRCB, .num_planes = 1, .num_comp = 1, .mbus_code = MEDIA_BUS_FMT_VYUY8_2X8, }, { .name = "YUV 4:2:2 packed, YCrYCb", .pixelformat = V4L2_PIX_FMT_YVYU, .depth = { 16 }, .color = GSC_YUV422, .yorder = GSC_LSB_Y, .corder = GSC_CRCB, .num_planes = 1, .num_comp = 1, .mbus_code = MEDIA_BUS_FMT_YVYU8_2X8, }, { .name = "YUV 4:4:4 planar, YCbYCr", .pixelformat = V4L2_PIX_FMT_YUV32, .depth = { 32 }, .color = GSC_YUV444, .yorder = GSC_LSB_Y, .corder = GSC_CBCR, .num_planes = 1, .num_comp = 1, }, { .name = "YUV 4:2:2 planar, Y/Cb/Cr", .pixelformat = V4L2_PIX_FMT_YUV422P, .depth = { 16 }, .color = GSC_YUV422, .yorder = GSC_LSB_Y, .corder = GSC_CBCR, .num_planes = 1, .num_comp = 3, }, { .name = "YUV 4:2:2 planar, Y/CbCr", .pixelformat = V4L2_PIX_FMT_NV16, .depth = { 16 }, .color = GSC_YUV422, .yorder = GSC_LSB_Y, .corder = GSC_CBCR, .num_planes = 1, .num_comp = 2, }, { .name = "YUV 4:2:2 planar, Y/CrCb", .pixelformat = V4L2_PIX_FMT_NV61, .depth = { 16 }, .color = GSC_YUV422, .yorder = GSC_LSB_Y, .corder = GSC_CRCB, .num_planes = 1, .num_comp = 2, }, { .name = "YUV 4:2:0 planar, YCbCr", .pixelformat = V4L2_PIX_FMT_YUV420, .depth = { 12 }, .color = GSC_YUV420, .yorder = GSC_LSB_Y, .corder = GSC_CBCR, .num_planes = 1, .num_comp = 3, }, { .name = "YUV 4:2:0 planar, YCrCb", .pixelformat = V4L2_PIX_FMT_YVU420, .depth = { 12 }, .color = GSC_YUV420, .yorder = GSC_LSB_Y, .corder = GSC_CRCB, .num_planes = 1, .num_comp = 3, }, { .name = "YUV 4:2:0 planar, Y/CbCr", .pixelformat = V4L2_PIX_FMT_NV12, .depth = { 12 }, .color = GSC_YUV420, .yorder = GSC_LSB_Y, .corder = GSC_CBCR, .num_planes = 1, .num_comp = 2, }, { .name = "YUV 4:2:0 planar, Y/CrCb", .pixelformat = V4L2_PIX_FMT_NV21, .depth = { 12 }, .color = GSC_YUV420, .yorder = GSC_LSB_Y, .corder = GSC_CRCB, .num_planes = 1, .num_comp = 2, }, { .name = "YUV 4:2:0 non-contig. 2p, Y/CbCr", .pixelformat = V4L2_PIX_FMT_NV12M, .depth = { 8, 4 }, .color = GSC_YUV420, .yorder = GSC_LSB_Y, .corder = GSC_CBCR, .num_planes = 2, .num_comp = 2, }, { .name = "YUV 4:2:0 non-contig. 3p, Y/Cb/Cr", .pixelformat = V4L2_PIX_FMT_YUV420M, .depth = { 8, 2, 2 }, .color = GSC_YUV420, .yorder = GSC_LSB_Y, .corder = GSC_CBCR, .num_planes = 3, .num_comp = 3, }, { .name = "YUV 4:2:0 non-contig. 3p, Y/Cr/Cb", .pixelformat = V4L2_PIX_FMT_YVU420M, .depth = { 8, 2, 2 }, .color = GSC_YUV420, .yorder = GSC_LSB_Y, .corder = GSC_CRCB, .num_planes = 3, .num_comp = 3, }, { .name = "YUV 4:2:0 n.c. 2p, Y/CbCr tiled", .pixelformat = V4L2_PIX_FMT_NV12MT_16X16, .depth = { 8, 4 }, .color = GSC_YUV420, .yorder = GSC_LSB_Y, .corder = GSC_CBCR, .num_planes = 2, .num_comp = 2, } }; const struct gsc_fmt *get_format(int index) { if (index >= ARRAY_SIZE(gsc_formats)) return NULL; return (struct gsc_fmt *)&gsc_formats[index]; } const struct gsc_fmt *find_fmt(u32 *pixelformat, u32 *mbus_code, u32 index) { const struct gsc_fmt *fmt, *def_fmt = NULL; unsigned int i; if (index >= ARRAY_SIZE(gsc_formats)) return NULL; for (i = 0; i < ARRAY_SIZE(gsc_formats); ++i) { fmt = get_format(i); if (pixelformat && fmt->pixelformat == *pixelformat) return fmt; if (mbus_code && fmt->mbus_code == *mbus_code) return fmt; if (index == i) def_fmt = fmt; } return def_fmt; } void gsc_set_frame_size(struct gsc_frame *frame, int width, int height) { frame->f_width = width; frame->f_height = height; frame->crop.width = width; frame->crop.height = height; frame->crop.left = 0; frame->crop.top = 0; } int gsc_cal_prescaler_ratio(struct gsc_variant *var, u32 src, u32 dst, u32 *ratio) { if ((dst > src) || (dst >= src / var->poly_sc_down_max)) { *ratio = 1; return 0; } if ((src / var->poly_sc_down_max / var->pre_sc_down_max) > dst) { pr_err("Exceeded maximum downscaling ratio (1/16))"); return -EINVAL; } *ratio = (dst > (src / 8)) ? 2 : 4; return 0; } void gsc_get_prescaler_shfactor(u32 hratio, u32 vratio, u32 *sh) { if (hratio == 4 && vratio == 4) *sh = 4; else if ((hratio == 4 && vratio == 2) || (hratio == 2 && vratio == 4)) *sh = 3; else if ((hratio == 4 && vratio == 1) || (hratio == 1 && vratio == 4) || (hratio == 2 && vratio == 2)) *sh = 2; else if (hratio == 1 && vratio == 1) *sh = 0; else *sh = 1; } void gsc_check_src_scale_info(struct gsc_variant *var, struct gsc_frame *s_frame, u32 *wratio, u32 tx, u32 ty, u32 *hratio) { int remainder = 0, walign, halign; if (is_yuv420(s_frame->fmt->color)) { walign = GSC_SC_ALIGN_4; halign = GSC_SC_ALIGN_4; } else if (is_yuv422(s_frame->fmt->color)) { walign = GSC_SC_ALIGN_4; halign = GSC_SC_ALIGN_2; } else { walign = GSC_SC_ALIGN_2; halign = GSC_SC_ALIGN_2; } remainder = s_frame->crop.width % (*wratio * walign); if (remainder) { s_frame->crop.width -= remainder; gsc_cal_prescaler_ratio(var, s_frame->crop.width, tx, wratio); pr_info("cropped src width size is recalculated from %d to %d", s_frame->crop.width + remainder, s_frame->crop.width); } remainder = s_frame->crop.height % (*hratio * halign); if (remainder) { s_frame->crop.height -= remainder; gsc_cal_prescaler_ratio(var, s_frame->crop.height, ty, hratio); pr_info("cropped src height size is recalculated from %d to %d", s_frame->crop.height + remainder, s_frame->crop.height); } } int gsc_enum_fmt_mplane(struct v4l2_fmtdesc *f) { const struct gsc_fmt *fmt; fmt = find_fmt(NULL, NULL, f->index); if (!fmt) return -EINVAL; strlcpy(f->description, fmt->name, sizeof(f->description)); f->pixelformat = fmt->pixelformat; return 0; } static int get_plane_info(struct gsc_frame *frm, u32 addr, u32 *index, u32 *ret_addr) { if (frm->addr.y == addr) { *index = 0; *ret_addr = frm->addr.y; } else if (frm->addr.cb == addr) { *index = 1; *ret_addr = frm->addr.cb; } else if (frm->addr.cr == addr) { *index = 2; *ret_addr = frm->addr.cr; } else { pr_err("Plane address is wrong"); return -EINVAL; } return 0; } void gsc_set_prefbuf(struct gsc_dev *gsc, struct gsc_frame *frm) { u32 f_chk_addr, f_chk_len, s_chk_addr, s_chk_len; f_chk_addr = f_chk_len = s_chk_addr = s_chk_len = 0; f_chk_addr = frm->addr.y; f_chk_len = frm->payload[0]; if (frm->fmt->num_planes == 2) { s_chk_addr = frm->addr.cb; s_chk_len = frm->payload[1]; } else if (frm->fmt->num_planes == 3) { u32 low_addr, low_plane, mid_addr, mid_plane; u32 high_addr, high_plane; u32 t_min, t_max; t_min = min3(frm->addr.y, frm->addr.cb, frm->addr.cr); if (get_plane_info(frm, t_min, &low_plane, &low_addr)) return; t_max = max3(frm->addr.y, frm->addr.cb, frm->addr.cr); if (get_plane_info(frm, t_max, &high_plane, &high_addr)) return; mid_plane = 3 - (low_plane + high_plane); if (mid_plane == 0) mid_addr = frm->addr.y; else if (mid_plane == 1) mid_addr = frm->addr.cb; else if (mid_plane == 2) mid_addr = frm->addr.cr; else return; f_chk_addr = low_addr; if (mid_addr + frm->payload[mid_plane] - low_addr > high_addr + frm->payload[high_plane] - mid_addr) { f_chk_len = frm->payload[low_plane]; s_chk_addr = mid_addr; s_chk_len = high_addr + frm->payload[high_plane] - mid_addr; } else { f_chk_len = mid_addr + frm->payload[mid_plane] - low_addr; s_chk_addr = high_addr; s_chk_len = frm->payload[high_plane]; } } pr_debug("f_addr = 0x%08x, f_len = %d, s_addr = 0x%08x, s_len = %d\n", f_chk_addr, f_chk_len, s_chk_addr, s_chk_len); } int gsc_try_fmt_mplane(struct gsc_ctx *ctx, struct v4l2_format *f) { struct gsc_dev *gsc = ctx->gsc_dev; struct gsc_variant *variant = gsc->variant; struct v4l2_pix_format_mplane *pix_mp = &f->fmt.pix_mp; const struct gsc_fmt *fmt; u32 max_w, max_h, mod_x, mod_y; u32 min_w, min_h, tmp_w, tmp_h; int i; pr_debug("user put w: %d, h: %d", pix_mp->width, pix_mp->height); fmt = find_fmt(&pix_mp->pixelformat, NULL, 0); if (!fmt) { pr_err("pixelformat format (0x%X) invalid\n", pix_mp->pixelformat); return -EINVAL; } if (pix_mp->field == V4L2_FIELD_ANY) pix_mp->field = V4L2_FIELD_NONE; else if (pix_mp->field != V4L2_FIELD_NONE) { pr_err("Not supported field order(%d)\n", pix_mp->field); return -EINVAL; } max_w = variant->pix_max->target_rot_dis_w; max_h = variant->pix_max->target_rot_dis_h; mod_x = ffs(variant->pix_align->org_w) - 1; if (is_yuv420(fmt->color)) mod_y = ffs(variant->pix_align->org_h) - 1; else mod_y = ffs(variant->pix_align->org_h) - 2; if (V4L2_TYPE_IS_OUTPUT(f->type)) { min_w = variant->pix_min->org_w; min_h = variant->pix_min->org_h; } else { min_w = variant->pix_min->target_rot_dis_w; min_h = variant->pix_min->target_rot_dis_h; } pr_debug("mod_x: %d, mod_y: %d, max_w: %d, max_h = %d", mod_x, mod_y, max_w, max_h); /* To check if image size is modified to adjust parameter against hardware abilities */ tmp_w = pix_mp->width; tmp_h = pix_mp->height; v4l_bound_align_image(&pix_mp->width, min_w, max_w, mod_x, &pix_mp->height, min_h, max_h, mod_y, 0); if (tmp_w != pix_mp->width || tmp_h != pix_mp->height) pr_info("Image size has been modified from %dx%d to %dx%d", tmp_w, tmp_h, pix_mp->width, pix_mp->height); pix_mp->num_planes = fmt->num_planes; if (pix_mp->width >= 1280) /* HD */ pix_mp->colorspace = V4L2_COLORSPACE_REC709; else /* SD */ pix_mp->colorspace = V4L2_COLORSPACE_SMPTE170M; for (i = 0; i < pix_mp->num_planes; ++i) { int bpl = (pix_mp->width * fmt->depth[i]) >> 3; pix_mp->plane_fmt[i].bytesperline = bpl; pix_mp->plane_fmt[i].sizeimage = bpl * pix_mp->height; pr_debug("[%d]: bpl: %d, sizeimage: %d", i, bpl, pix_mp->plane_fmt[i].sizeimage); } return 0; } int gsc_g_fmt_mplane(struct gsc_ctx *ctx, struct v4l2_format *f) { struct gsc_frame *frame; struct v4l2_pix_format_mplane *pix_mp; int i; frame = ctx_get_frame(ctx, f->type); if (IS_ERR(frame)) return PTR_ERR(frame); pix_mp = &f->fmt.pix_mp; pix_mp->width = frame->f_width; pix_mp->height = frame->f_height; pix_mp->field = V4L2_FIELD_NONE; pix_mp->pixelformat = frame->fmt->pixelformat; pix_mp->colorspace = V4L2_COLORSPACE_REC709; pix_mp->num_planes = frame->fmt->num_planes; for (i = 0; i < pix_mp->num_planes; ++i) { pix_mp->plane_fmt[i].bytesperline = (frame->f_width * frame->fmt->depth[i]) / 8; pix_mp->plane_fmt[i].sizeimage = pix_mp->plane_fmt[i].bytesperline * frame->f_height; } return 0; } void gsc_check_crop_change(u32 tmp_w, u32 tmp_h, u32 *w, u32 *h) { if (tmp_w != *w || tmp_h != *h) { pr_info("Cropped size has been modified from %dx%d to %dx%d", *w, *h, tmp_w, tmp_h); *w = tmp_w; *h = tmp_h; } } int gsc_g_crop(struct gsc_ctx *ctx, struct v4l2_crop *cr) { struct gsc_frame *frame; frame = ctx_get_frame(ctx, cr->type); if (IS_ERR(frame)) return PTR_ERR(frame); cr->c = frame->crop; return 0; } int gsc_try_crop(struct gsc_ctx *ctx, struct v4l2_crop *cr) { struct gsc_frame *f; struct gsc_dev *gsc = ctx->gsc_dev; struct gsc_variant *variant = gsc->variant; u32 mod_x = 0, mod_y = 0, tmp_w, tmp_h; u32 min_w, min_h, max_w, max_h; if (cr->c.top < 0 || cr->c.left < 0) { pr_err("doesn't support negative values for top & left\n"); return -EINVAL; } pr_debug("user put w: %d, h: %d", cr->c.width, cr->c.height); if (cr->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) f = &ctx->d_frame; else if (cr->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) f = &ctx->s_frame; else return -EINVAL; max_w = f->f_width; max_h = f->f_height; tmp_w = cr->c.width; tmp_h = cr->c.height; if (V4L2_TYPE_IS_OUTPUT(cr->type)) { if ((is_yuv422(f->fmt->color) && f->fmt->num_comp == 1) || is_rgb(f->fmt->color)) min_w = 32; else min_w = 64; if ((is_yuv422(f->fmt->color) && f->fmt->num_comp == 3) || is_yuv420(f->fmt->color)) min_h = 32; else min_h = 16; } else { if (is_yuv420(f->fmt->color) || is_yuv422(f->fmt->color)) mod_x = ffs(variant->pix_align->target_w) - 1; if (is_yuv420(f->fmt->color)) mod_y = ffs(variant->pix_align->target_h) - 1; if (ctx->gsc_ctrls.rotate->val == 90 || ctx->gsc_ctrls.rotate->val == 270) { max_w = f->f_height; max_h = f->f_width; min_w = variant->pix_min->target_rot_en_w; min_h = variant->pix_min->target_rot_en_h; tmp_w = cr->c.height; tmp_h = cr->c.width; } else { min_w = variant->pix_min->target_rot_dis_w; min_h = variant->pix_min->target_rot_dis_h; } } pr_debug("mod_x: %d, mod_y: %d, min_w: %d, min_h = %d", mod_x, mod_y, min_w, min_h); pr_debug("tmp_w : %d, tmp_h : %d", tmp_w, tmp_h); v4l_bound_align_image(&tmp_w, min_w, max_w, mod_x, &tmp_h, min_h, max_h, mod_y, 0); if (!V4L2_TYPE_IS_OUTPUT(cr->type) && (ctx->gsc_ctrls.rotate->val == 90 || ctx->gsc_ctrls.rotate->val == 270)) gsc_check_crop_change(tmp_h, tmp_w, &cr->c.width, &cr->c.height); else gsc_check_crop_change(tmp_w, tmp_h, &cr->c.width, &cr->c.height); /* adjust left/top if cropping rectangle is out of bounds */ /* Need to add code to algin left value with 2's multiple */ if (cr->c.left + tmp_w > max_w) cr->c.left = max_w - tmp_w; if (cr->c.top + tmp_h > max_h) cr->c.top = max_h - tmp_h; if ((is_yuv420(f->fmt->color) || is_yuv422(f->fmt->color)) && cr->c.left & 1) cr->c.left -= 1; pr_debug("Aligned l:%d, t:%d, w:%d, h:%d, f_w: %d, f_h: %d", cr->c.left, cr->c.top, cr->c.width, cr->c.height, max_w, max_h); return 0; } int gsc_check_scaler_ratio(struct gsc_variant *var, int sw, int sh, int dw, int dh, int rot, int out_path) { int tmp_w, tmp_h, sc_down_max; if (out_path == GSC_DMA) sc_down_max = var->sc_down_max; else sc_down_max = var->local_sc_down; if (rot == 90 || rot == 270) { tmp_w = dh; tmp_h = dw; } else { tmp_w = dw; tmp_h = dh; } if ((sw / tmp_w) > sc_down_max || (sh / tmp_h) > sc_down_max || (tmp_w / sw) > var->sc_up_max || (tmp_h / sh) > var->sc_up_max) return -EINVAL; return 0; } int gsc_set_scaler_info(struct gsc_ctx *ctx) { struct gsc_scaler *sc = &ctx->scaler; struct gsc_frame *s_frame = &ctx->s_frame; struct gsc_frame *d_frame = &ctx->d_frame; struct gsc_variant *variant = ctx->gsc_dev->variant; struct device *dev = &ctx->gsc_dev->pdev->dev; int tx, ty; int ret; ret = gsc_check_scaler_ratio(variant, s_frame->crop.width, s_frame->crop.height, d_frame->crop.width, d_frame->crop.height, ctx->gsc_ctrls.rotate->val, ctx->out_path); if (ret) { pr_err("out of scaler range"); return ret; } if (ctx->gsc_ctrls.rotate->val == 90 || ctx->gsc_ctrls.rotate->val == 270) { ty = d_frame->crop.width; tx = d_frame->crop.height; } else { tx = d_frame->crop.width; ty = d_frame->crop.height; } if (tx <= 0 || ty <= 0) { dev_err(dev, "Invalid target size: %dx%d", tx, ty); return -EINVAL; } ret = gsc_cal_prescaler_ratio(variant, s_frame->crop.width, tx, &sc->pre_hratio); if (ret) { pr_err("Horizontal scale ratio is out of range"); return ret; } ret = gsc_cal_prescaler_ratio(variant, s_frame->crop.height, ty, &sc->pre_vratio); if (ret) { pr_err("Vertical scale ratio is out of range"); return ret; } gsc_check_src_scale_info(variant, s_frame, &sc->pre_hratio, tx, ty, &sc->pre_vratio); gsc_get_prescaler_shfactor(sc->pre_hratio, sc->pre_vratio, &sc->pre_shfactor); sc->main_hratio = (s_frame->crop.width << 16) / tx; sc->main_vratio = (s_frame->crop.height << 16) / ty; pr_debug("scaler input/output size : sx = %d, sy = %d, tx = %d, ty = %d", s_frame->crop.width, s_frame->crop.height, tx, ty); pr_debug("scaler ratio info : pre_shfactor : %d, pre_h : %d", sc->pre_shfactor, sc->pre_hratio); pr_debug("pre_v :%d, main_h : %d, main_v : %d", sc->pre_vratio, sc->main_hratio, sc->main_vratio); return 0; } static int __gsc_s_ctrl(struct gsc_ctx *ctx, struct v4l2_ctrl *ctrl) { struct gsc_dev *gsc = ctx->gsc_dev; struct gsc_variant *variant = gsc->variant; unsigned int flags = GSC_DST_FMT | GSC_SRC_FMT; int ret = 0; if (ctrl->flags & V4L2_CTRL_FLAG_INACTIVE) return 0; switch (ctrl->id) { case V4L2_CID_HFLIP: ctx->hflip = ctrl->val; break; case V4L2_CID_VFLIP: ctx->vflip = ctrl->val; break; case V4L2_CID_ROTATE: if ((ctx->state & flags) == flags) { ret = gsc_check_scaler_ratio(variant, ctx->s_frame.crop.width, ctx->s_frame.crop.height, ctx->d_frame.crop.width, ctx->d_frame.crop.height, ctx->gsc_ctrls.rotate->val, ctx->out_path); if (ret) return -EINVAL; } ctx->rotation = ctrl->val; break; case V4L2_CID_ALPHA_COMPONENT: ctx->d_frame.alpha = ctrl->val; break; } ctx->state |= GSC_PARAMS; return 0; } static int gsc_s_ctrl(struct v4l2_ctrl *ctrl) { struct gsc_ctx *ctx = ctrl_to_ctx(ctrl); unsigned long flags; int ret; spin_lock_irqsave(&ctx->gsc_dev->slock, flags); ret = __gsc_s_ctrl(ctx, ctrl); spin_unlock_irqrestore(&ctx->gsc_dev->slock, flags); return ret; } static const struct v4l2_ctrl_ops gsc_ctrl_ops = { .s_ctrl = gsc_s_ctrl, }; int gsc_ctrls_create(struct gsc_ctx *ctx) { if (ctx->ctrls_rdy) { pr_err("Control handler of this context was created already"); return 0; } v4l2_ctrl_handler_init(&ctx->ctrl_handler, GSC_MAX_CTRL_NUM); ctx->gsc_ctrls.rotate = v4l2_ctrl_new_std(&ctx->ctrl_handler, &gsc_ctrl_ops, V4L2_CID_ROTATE, 0, 270, 90, 0); ctx->gsc_ctrls.hflip = v4l2_ctrl_new_std(&ctx->ctrl_handler, &gsc_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); ctx->gsc_ctrls.vflip = v4l2_ctrl_new_std(&ctx->ctrl_handler, &gsc_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); ctx->gsc_ctrls.global_alpha = v4l2_ctrl_new_std(&ctx->ctrl_handler, &gsc_ctrl_ops, V4L2_CID_ALPHA_COMPONENT, 0, 255, 1, 0); ctx->ctrls_rdy = ctx->ctrl_handler.error == 0; if (ctx->ctrl_handler.error) { int err = ctx->ctrl_handler.error; v4l2_ctrl_handler_free(&ctx->ctrl_handler); pr_err("Failed to create G-Scaler control handlers"); return err; } return 0; } void gsc_ctrls_delete(struct gsc_ctx *ctx) { if (ctx->ctrls_rdy) { v4l2_ctrl_handler_free(&ctx->ctrl_handler); ctx->ctrls_rdy = false; } } /* The color format (num_comp, num_planes) must be already configured. */ int gsc_prepare_addr(struct gsc_ctx *ctx, struct vb2_buffer *vb, struct gsc_frame *frame, struct gsc_addr *addr) { int ret = 0; u32 pix_size; if ((vb == NULL) || (frame == NULL)) return -EINVAL; pix_size = frame->f_width * frame->f_height; pr_debug("num_planes= %d, num_comp= %d, pix_size= %d", frame->fmt->num_planes, frame->fmt->num_comp, pix_size); addr->y = vb2_dma_contig_plane_dma_addr(vb, 0); if (frame->fmt->num_planes == 1) { switch (frame->fmt->num_comp) { case 1: addr->cb = 0; addr->cr = 0; break; case 2: /* decompose Y into Y/Cb */ addr->cb = (dma_addr_t)(addr->y + pix_size); addr->cr = 0; break; case 3: /* decompose Y into Y/Cb/Cr */ addr->cb = (dma_addr_t)(addr->y + pix_size); if (GSC_YUV420 == frame->fmt->color) addr->cr = (dma_addr_t)(addr->cb + (pix_size >> 2)); else /* 422 */ addr->cr = (dma_addr_t)(addr->cb + (pix_size >> 1)); break; default: pr_err("Invalid the number of color planes"); return -EINVAL; } } else { if (frame->fmt->num_planes >= 2) addr->cb = vb2_dma_contig_plane_dma_addr(vb, 1); if (frame->fmt->num_planes == 3) addr->cr = vb2_dma_contig_plane_dma_addr(vb, 2); } if ((frame->fmt->pixelformat == V4L2_PIX_FMT_VYUY) || (frame->fmt->pixelformat == V4L2_PIX_FMT_YVYU) || (frame->fmt->pixelformat == V4L2_PIX_FMT_NV61) || (frame->fmt->pixelformat == V4L2_PIX_FMT_YVU420) || (frame->fmt->pixelformat == V4L2_PIX_FMT_NV21) || (frame->fmt->pixelformat == V4L2_PIX_FMT_YVU420M)) swap(addr->cb, addr->cr); pr_debug("ADDR: y= %pad cb= %pad cr= %pad ret= %d", &addr->y, &addr->cb, &addr->cr, ret); return ret; } static irqreturn_t gsc_irq_handler(int irq, void *priv) { struct gsc_dev *gsc = priv; struct gsc_ctx *ctx; int gsc_irq; gsc_irq = gsc_hw_get_irq_status(gsc); gsc_hw_clear_irq(gsc, gsc_irq); if (gsc_irq == GSC_IRQ_OVERRUN) { pr_err("Local path input over-run interrupt has occurred!\n"); return IRQ_HANDLED; } spin_lock(&gsc->slock); if (test_and_clear_bit(ST_M2M_PEND, &gsc->state)) { gsc_hw_enable_control(gsc, false); if (test_and_clear_bit(ST_M2M_SUSPENDING, &gsc->state)) { set_bit(ST_M2M_SUSPENDED, &gsc->state); wake_up(&gsc->irq_queue); goto isr_unlock; } ctx = v4l2_m2m_get_curr_priv(gsc->m2m.m2m_dev); if (!ctx || !ctx->m2m_ctx) goto isr_unlock; spin_unlock(&gsc->slock); gsc_m2m_job_finish(ctx, VB2_BUF_STATE_DONE); /* wake_up job_abort, stop_streaming */ if (ctx->state & GSC_CTX_STOP_REQ) { ctx->state &= ~GSC_CTX_STOP_REQ; wake_up(&gsc->irq_queue); } return IRQ_HANDLED; } isr_unlock: spin_unlock(&gsc->slock); return IRQ_HANDLED; } static struct gsc_pix_max gsc_v_100_max = { .org_scaler_bypass_w = 8192, .org_scaler_bypass_h = 8192, .org_scaler_input_w = 4800, .org_scaler_input_h = 3344, .real_rot_dis_w = 4800, .real_rot_dis_h = 3344, .real_rot_en_w = 2047, .real_rot_en_h = 2047, .target_rot_dis_w = 4800, .target_rot_dis_h = 3344, .target_rot_en_w = 2016, .target_rot_en_h = 2016, }; static struct gsc_pix_min gsc_v_100_min = { .org_w = 64, .org_h = 32, .real_w = 64, .real_h = 32, .target_rot_dis_w = 64, .target_rot_dis_h = 32, .target_rot_en_w = 32, .target_rot_en_h = 16, }; static struct gsc_pix_align gsc_v_100_align = { .org_h = 16, .org_w = 16, /* yuv420 : 16, others : 8 */ .offset_h = 2, /* yuv420/422 : 2, others : 1 */ .real_w = 16, /* yuv420/422 : 4~16, others : 2~8 */ .real_h = 16, /* yuv420 : 4~16, others : 1 */ .target_w = 2, /* yuv420/422 : 2, others : 1 */ .target_h = 2, /* yuv420 : 2, others : 1 */ }; static struct gsc_variant gsc_v_100_variant = { .pix_max = &gsc_v_100_max, .pix_min = &gsc_v_100_min, .pix_align = &gsc_v_100_align, .in_buf_cnt = 32, .out_buf_cnt = 32, .sc_up_max = 8, .sc_down_max = 16, .poly_sc_down_max = 4, .pre_sc_down_max = 4, .local_sc_down = 2, }; static struct gsc_driverdata gsc_v_100_drvdata = { .variant = { [0] = &gsc_v_100_variant, [1] = &gsc_v_100_variant, [2] = &gsc_v_100_variant, [3] = &gsc_v_100_variant, }, .num_entities = 4, .lclk_frequency = 266000000UL, }; static struct platform_device_id gsc_driver_ids[] = { { .name = "exynos-gsc", .driver_data = (unsigned long)&gsc_v_100_drvdata, }, {}, }; MODULE_DEVICE_TABLE(platform, gsc_driver_ids); static const struct of_device_id exynos_gsc_match[] = { { .compatible = "samsung,exynos5-gsc", .data = &gsc_v_100_drvdata, }, {}, }; MODULE_DEVICE_TABLE(of, exynos_gsc_match); static void *gsc_get_drv_data(struct platform_device *pdev) { struct gsc_driverdata *driver_data = NULL; if (pdev->dev.of_node) { const struct of_device_id *match; match = of_match_node(exynos_gsc_match, pdev->dev.of_node); if (match) driver_data = (struct gsc_driverdata *)match->data; } else { driver_data = (struct gsc_driverdata *) platform_get_device_id(pdev)->driver_data; } return driver_data; } static void gsc_clk_put(struct gsc_dev *gsc) { if (!IS_ERR(gsc->clock)) clk_unprepare(gsc->clock); } static int gsc_clk_get(struct gsc_dev *gsc) { int ret; dev_dbg(&gsc->pdev->dev, "gsc_clk_get Called\n"); gsc->clock = devm_clk_get(&gsc->pdev->dev, GSC_CLOCK_GATE_NAME); if (IS_ERR(gsc->clock)) { dev_err(&gsc->pdev->dev, "failed to get clock~~~: %s\n", GSC_CLOCK_GATE_NAME); return PTR_ERR(gsc->clock); } ret = clk_prepare(gsc->clock); if (ret < 0) { dev_err(&gsc->pdev->dev, "clock prepare failed for clock: %s\n", GSC_CLOCK_GATE_NAME); gsc->clock = ERR_PTR(-EINVAL); return ret; } return 0; } static int gsc_m2m_suspend(struct gsc_dev *gsc) { unsigned long flags; int timeout; spin_lock_irqsave(&gsc->slock, flags); if (!gsc_m2m_pending(gsc)) { spin_unlock_irqrestore(&gsc->slock, flags); return 0; } clear_bit(ST_M2M_SUSPENDED, &gsc->state); set_bit(ST_M2M_SUSPENDING, &gsc->state); spin_unlock_irqrestore(&gsc->slock, flags); timeout = wait_event_timeout(gsc->irq_queue, test_bit(ST_M2M_SUSPENDED, &gsc->state), GSC_SHUTDOWN_TIMEOUT); clear_bit(ST_M2M_SUSPENDING, &gsc->state); return timeout == 0 ? -EAGAIN : 0; } static int gsc_m2m_resume(struct gsc_dev *gsc) { struct gsc_ctx *ctx; unsigned long flags; spin_lock_irqsave(&gsc->slock, flags); /* Clear for full H/W setup in first run after resume */ ctx = gsc->m2m.ctx; gsc->m2m.ctx = NULL; spin_unlock_irqrestore(&gsc->slock, flags); if (test_and_clear_bit(ST_M2M_SUSPENDED, &gsc->state)) gsc_m2m_job_finish(ctx, VB2_BUF_STATE_ERROR); return 0; } static int gsc_probe(struct platform_device *pdev) { struct gsc_dev *gsc; struct resource *res; struct gsc_driverdata *drv_data = gsc_get_drv_data(pdev); struct device *dev = &pdev->dev; int ret = 0; gsc = devm_kzalloc(dev, sizeof(struct gsc_dev), GFP_KERNEL); if (!gsc) return -ENOMEM; if (dev->of_node) gsc->id = of_alias_get_id(pdev->dev.of_node, "gsc"); else gsc->id = pdev->id; if (gsc->id >= drv_data->num_entities) { dev_err(dev, "Invalid platform device id: %d\n", gsc->id); return -EINVAL; } gsc->variant = drv_data->variant[gsc->id]; gsc->pdev = pdev; gsc->pdata = dev->platform_data; init_waitqueue_head(&gsc->irq_queue); spin_lock_init(&gsc->slock); mutex_init(&gsc->lock); gsc->clock = ERR_PTR(-EINVAL); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); gsc->regs = devm_ioremap_resource(dev, res); if (IS_ERR(gsc->regs)) return PTR_ERR(gsc->regs); res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (!res) { dev_err(dev, "failed to get IRQ resource\n"); return -ENXIO; } ret = gsc_clk_get(gsc); if (ret) return ret; ret = devm_request_irq(dev, res->start, gsc_irq_handler, 0, pdev->name, gsc); if (ret) { dev_err(dev, "failed to install irq (%d)\n", ret); goto err_clk; } ret = v4l2_device_register(dev, &gsc->v4l2_dev); if (ret) goto err_clk; ret = gsc_register_m2m_device(gsc); if (ret) goto err_v4l2; platform_set_drvdata(pdev, gsc); pm_runtime_enable(dev); ret = pm_runtime_get_sync(&pdev->dev); if (ret < 0) goto err_m2m; /* Initialize continious memory allocator */ gsc->alloc_ctx = vb2_dma_contig_init_ctx(dev); if (IS_ERR(gsc->alloc_ctx)) { ret = PTR_ERR(gsc->alloc_ctx); goto err_pm; } dev_dbg(dev, "gsc-%d registered successfully\n", gsc->id); pm_runtime_put(dev); return 0; err_pm: pm_runtime_put(dev); err_m2m: gsc_unregister_m2m_device(gsc); err_v4l2: v4l2_device_unregister(&gsc->v4l2_dev); err_clk: gsc_clk_put(gsc); return ret; } static int gsc_remove(struct platform_device *pdev) { struct gsc_dev *gsc = platform_get_drvdata(pdev); gsc_unregister_m2m_device(gsc); v4l2_device_unregister(&gsc->v4l2_dev); vb2_dma_contig_cleanup_ctx(gsc->alloc_ctx); pm_runtime_disable(&pdev->dev); gsc_clk_put(gsc); dev_dbg(&pdev->dev, "%s driver unloaded\n", pdev->name); return 0; } static int gsc_runtime_resume(struct device *dev) { struct gsc_dev *gsc = dev_get_drvdata(dev); int ret = 0; pr_debug("gsc%d: state: 0x%lx", gsc->id, gsc->state); ret = clk_enable(gsc->clock); if (ret) return ret; gsc_hw_set_sw_reset(gsc); gsc_wait_reset(gsc); return gsc_m2m_resume(gsc); } static int gsc_runtime_suspend(struct device *dev) { struct gsc_dev *gsc = dev_get_drvdata(dev); int ret = 0; ret = gsc_m2m_suspend(gsc); if (!ret) clk_disable(gsc->clock); pr_debug("gsc%d: state: 0x%lx", gsc->id, gsc->state); return ret; } static int gsc_resume(struct device *dev) { struct gsc_dev *gsc = dev_get_drvdata(dev); unsigned long flags; pr_debug("gsc%d: state: 0x%lx", gsc->id, gsc->state); /* Do not resume if the device was idle before system suspend */ spin_lock_irqsave(&gsc->slock, flags); if (!test_and_clear_bit(ST_SUSPEND, &gsc->state) || !gsc_m2m_opened(gsc)) { spin_unlock_irqrestore(&gsc->slock, flags); return 0; } spin_unlock_irqrestore(&gsc->slock, flags); if (!pm_runtime_suspended(dev)) return gsc_runtime_resume(dev); return 0; } static int gsc_suspend(struct device *dev) { struct gsc_dev *gsc = dev_get_drvdata(dev); pr_debug("gsc%d: state: 0x%lx", gsc->id, gsc->state); if (test_and_set_bit(ST_SUSPEND, &gsc->state)) return 0; if (!pm_runtime_suspended(dev)) return gsc_runtime_suspend(dev); return 0; } static const struct dev_pm_ops gsc_pm_ops = { .suspend = gsc_suspend, .resume = gsc_resume, .runtime_suspend = gsc_runtime_suspend, .runtime_resume = gsc_runtime_resume, }; static struct platform_driver gsc_driver = { .probe = gsc_probe, .remove = gsc_remove, .id_table = gsc_driver_ids, .driver = { .name = GSC_MODULE_NAME, .owner = THIS_MODULE, .pm = &gsc_pm_ops, .of_match_table = exynos_gsc_match, } }; module_platform_driver(gsc_driver); MODULE_AUTHOR("Hyunwong Kim <khw0178.kim@samsung.com>"); MODULE_DESCRIPTION("Samsung EXYNOS5 Soc series G-Scaler driver"); MODULE_LICENSE("GPL");
Barracuda09/media_build-bst
linux/drivers/media/platform/exynos-gsc/gsc-core.c
C
gpl-2.0
31,176
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Example: bib2xhtml -s paragraph -n Spinellis -u -U -r </title> <meta http-equiv="Content-type" content="text/html; charset=UTF-8" /> <meta name="Generator" content="http://www.spinellis.gr/sw/textproc/bib2xhtml/" /> </head> <body> <!-- BEGIN BIBLIOGRAPHY example --> <!-- DO NOT MODIFY THIS BIBLIOGRAPHY BY HAND! IT IS MAINTAINED AUTOMATICALLY! YOUR CHANGES WILL BE LOST THE NEXT TIME IT IS UPDATED! --> <!-- Generated by: bib2xhtml.pl -s paragraph -n Spinellis -u -U -r -h Example: bib2xhtml -s paragraph -n Spinellis -u -U -r example.bib eg/paragraph-n-u-r.html --> <div class="bib2xhtml"> <!-- Authors: Harold Abelson and Gerald Jay Sussman and Jullie Sussman --> <p><a name="SICP"></a>Harold Abelson, Gerald Jay Sussman, and Jullie Sussman. <cite>Structure and Interpretation of Computer Programs</cite>. MIT Press, Cambridge, 1985.</p> <!-- Authors: Alfred V Aho and John E Hopcroft and Jeffrey D Ullman --> <p><a name="RedDragon"></a>Alfred V. Aho, John E. Hopcroft, and Jeffrey D. Ullman. <cite>The Design and Analysis of Computer Algorithms</cite>. Addison-Wesley, Reading, MA, 1974.</p> <!-- Authors: Stephanos Androutsellis Theotokis and Diomidis Spinellis --> <p><a name="Androutsellis:2004"></a>Stephanos Androutsellis-Theotokis and <strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/jrnl/2004-ACMCS-p2p/html/AS04.html">A survey of peer-to-peer content distribution technologies</a>. <cite>ACM Computing Surveys</cite>, 36(4):335–371, December 2004. (<a href="http://dx.doi.org/10.1145/1041680.1041681">doi:10.1145/1041680.1041681</a>)</p> <!-- Authors: Albert Laszlo Barabasi and Monica Ferreira da Silva and F Paterno and Wladyslaw M Turski and Sten AAke Tarnlund and Ketil Bo and J Encarnaccao and Deltaiotaomicronmuetadeltaetavarsigma Sigmapiiotanuepsilonlambdalambdaetavarsigma and Pesster vCuezog --> <p><a name="XXX00"></a>Albert-László Barabási, Mônica Ferreira da Silva, F. Paternò, Władysław M. Turski, Sten-Åke Tärnlund, Ketil Bø, J. Encarnação, Διομηδης Σπινελλης, and Pëßtêr Čĕżōġ. Cite this paper. <cite>¡Journal of Authors Against ASCII!</cite>, 45(281):69–77, 2000.</p> <!-- Authors: Adele Goldberg and David Robson --> <p><a name="Smalltalk"></a>Adele Goldberg and David Robson. <cite>Smalltalk-80: The Language</cite>. Addison-Wesley, Reading, MA, 1989.</p> <!-- Authors: Stefanos Gritzalis and Diomidis Spinellis and Panagiotis Georgiadis --> <p><a name="Gritzalis:1999"></a>Stefanos Gritzalis, <strong>Diomidis Spinellis</strong>, and Panagiotis Georgiadis. <a href="http://www.dmst.aueb.gr/dds/pubs/jrnl/1997-CompComm-Formal/html/formal.htm">Security protocols over open networks and distributed systems: Formal methods for their analysis, design, and verification</a>. <cite>Computer Communications</cite>, 22(8):695–707, May 1999. (<a href="http://dx.doi.org/10.1016/S0140-3664(99)00030-4">doi:10.1016/S0140-3664(99)00030-4</a>)</p> <!-- Authors: Firstć Lastž and Second Thirdäöü --> <p><a name="testingUTFcharacters2018a"></a>Firstć Lastž and Second Thirdäöü. Just a title. In <cite>Pattern Recognition</cite>, 2018.</p> <!-- Authors: somelongidtotestbibtexlinebreaks --> <p><a name="somelongidtotestbibtexlinebreaks"></a>somelongidtotestbibtexlinebreaks. somelongidtotestbibtexlinebreaks.</p> <!-- Authors: Diomidis Spinellis --> <p><a name="Spi06i"></a><strong>Diomidis Spinellis</strong>. Open source and professional advancement. <cite>IEEE Software</cite>, 23(5):70–71, September/October 2006. (<a href="eg/v23n5.pdf">PDF</a>, 116157 bytes) (<a href="http://dx.doi.org/10.1109/MS.2006.136">doi:10.1109/MS.2006.136</a>)</p> <!-- Authors: Diomidis Spinellis --> <p><a name="CodeReading"></a><strong>Diomidis Spinellis</strong>. <a href="http://www.spinellis.gr/codereading"><cite>Code Reading: The Open Source Perspective</cite></a>. Effective Software Development Series. Addison-Wesley, Boston, MA, 2003.</p> <!-- Authors: Diomidis Spinellis --> <p><a name="Spinellis:2003b"></a><strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/jrnl/2003-TSE-Refactor/html/Spi03r.html">Global analysis and transformations in preprocessed languages</a>. <cite>IEEE Transactions on Software Engineering</cite>, 29(11):1019–1030, November 2003. (<a href="http://dx.doi.org/10.1109/TSE.2003.1245303">doi:10.1109/TSE.2003.1245303</a>)</p> <!-- Authors: Diomidis Spinellis --> <p><a name="Spinellis:2003"></a><strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/jrnl/2003-CACM-URLcite/html/urlcite.html">The decay and failures of web references</a>. <cite>Communications of the ACM</cite>, 46(1):71–77, January 2003. (<a href="http://dx.doi.org/10.1145/602421.602422">doi:10.1145/602421.602422</a>)</p> <!-- Authors: Diomidis Spinellis --> <p><a name="Spinellis:2000"></a><strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/conf/2000-Usenix-outwit/html/utool.html">Outwit: Unix tool-based programming meets the Windows world</a>. In Christopher Small, editor, <cite>USENIX 2000 Technical Conference Proceedings</cite>, pages 149–158, Berkeley, CA, June 2000. Usenix Association.</p> <!-- Authors: Diomidis Spinellis --> <p><a name="Spinellis:1996"></a><strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/tr/rfc-1947/html/RFC1947.html">Greek character encoding for electronic mail messages</a>. Network Information Center, Request for Comments 1947, May 1996. RFC-1947.</p> <!-- Authors: Diomidis Spinellis --> <p><a name="Spinellis:1994"></a><strong>Diomidis Spinellis</strong>. <cite>Programming Paradigms as Object Classes: A Structuring Mechanism for Multiparadigm Programming</cite>. PhD thesis, Imperial College of Science, Technology and Medicine, London, UK, February 1994. (<a href="http://www.dmst.aueb.gr/dds/pubs/thesis/PhD/html/thesis.pdf">PDF</a>)</p> <!-- Authors: Diomidis Spinellis --> <p><a name="Spinellis:1993"></a><strong>Diomidis Spinellis</strong>. <a href="http://www.dmst.aueb.gr/dds/pubs/jrnl/1993-StrProg-Haskell/html/exp.html">Implementing Haskell: Language implementation as a tool building exercise</a>. <cite>Structured Programming (Software Concepts and Tools)</cite>, 14:37–48, 1993.</p> <!-- Authors: Diomidis Spinellis --> <p><a name="Spinellis:1990"></a><strong>Diomidis Spinellis</strong>. An implementation of the Haskell language. Master's thesis, Imperial College, London, UK, June 1990. (<a href="http://www.dmst.aueb.gr/dds/pubs/thesis/MEng/html/haskell.pdf">PDF</a>)</p> <!-- Authors: Ken Thompson --> <p><a name="Thompson:1968"></a>Ken Thompson. Programming techniques: Regular expression search algorithm. <cite>Communications of the ACM</cite>, 11(6):419–422, 1968. (<a href="http://dx.doi.org/10.1145/363347.363387">doi:10.1145/363347.363387</a>)</p> <!-- Authors: Elizabeth Zwicky and Simon Cooper and D Brent Chapman --> <p><a name="Firewalls"></a>Elizabeth Zwicky, Simon Cooper, and D. Brent Chapman. <cite>Building Internet Firewalls</cite>. O'Reilly and Associates, Sebastopol, CA, second edition, 2000.</p> </div> <!-- END BIBLIOGRAPHY example --> </body></html>
dspinellis/bib2xhtml
test.ok/paragraph-n-u-r.html
HTML
gpl-2.0
7,481
--[[ filter.unused_media -- Remove unused medias. Copyright (C) 2013-2017 PUC-Rio/Laboratorio TeleMidia This file is part of DietNCL. DietNCL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DietNCL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DietNCL. If not, see <http://www.gnu.org/licenses/>. ]]-- local print = print local ipairs = ipairs local filter = {} local xml = require ('dietncl.xmlsugar') _ENV = nil --- -- Removes all `<descriptor>` elements from NCL document. -- -- @module dietncl.filter.descriptor --- --- -- Avoid property clash. Insert the property with the highest priority in -- an NCL document. local function insert_properties (ncl, media, name, value) if name=="id" or name=="region" then return end for par in media:children() do if name == par.name then return end end local prop = ncl.new('property') prop.name = name prop.value = value media:insert (prop) end --- -- Removes all descriptors from NCL document. The function proceeds by -- transforming the attributes of each media into equivalent parameters -- of the associated descriptor. -- @param ncl NCL document (root element). -- @return the modified NCL document (root element). --- function filter.apply (ncl) for desc in ncl:gmatch ('descriptor') do local list = {ncl:match ('media', 'descriptor', desc.id)} if #list == 0 then goto done end for _,media in ipairs (list) do for descpar in desc:children() do insert_properties (ncl, media, descpar.name, descpar.value) end for name, value in desc:attributes() do insert_properties (ncl, media, name, value) end media.descriptor = nil end ::done:: xml.remove (desc:parent(), desc) end return (ncl) end return filter
TeleMidia/dietncl
dietncl/filter/descriptor.lua
Lua
gpl-2.0
2,287
/***************************************************************** * $Id: acc_workorder.h 2191 2014-10-27 20:31:51Z rutger $ * Created: Oct 27, 2014 11:41:25 AM - rutger * * Copyright (C) 2014 Red-Bag. All rights reserved. * This file is part of the Biluna ACC project. * * See http://www.red-bag.com for further details. *****************************************************************/ #ifndef ACC_WORKORDER_H #define ACC_WORKORDER_H #include "rb_objectcontainer.h" /** * Class for (internal) work orders */ class ACC_WorkOrder : public RB_ObjectContainer { public: ACC_WorkOrder(const RB_String& id = "", RB_ObjectBase* p = NULL, const RB_String& n = "", RB_ObjectFactory* f = NULL); ACC_WorkOrder(ACC_WorkOrder* obj); virtual ~ACC_WorkOrder(); private: void createMembers(); }; #endif // ACC_WORKORDER_H
biluna/biluna
acc/src/model/acc_workorder.h
C
gpl-2.0
858
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wordservice.mvc; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.factory.GraphDatabaseFactory; import org.neo4j.kernel.impl.util.FileUtils; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.data.neo4j.rest.SpringRestGraphDatabase; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.io.File; import java.io.IOException; @Configuration @ComponentScan @ImportResource("classpath:META-INF/spring/spring-data-context.xml") @EnableTransactionManagement class ApplicationConfig { @Bean(destroyMethod = "shutdown") public GraphDatabaseService graphDatabaseService() { // return new SpringRestGraphDatabase("http://localhost:7474/db/data"); // try { // FileUtils.deleteRecursively(new File("real-db")); return new GraphDatabaseFactory().newEmbeddedDatabase("real-db"); // } catch (IOException e) { // throw new RuntimeException(e); // } } }
ilja903/wordservice
src/main/java/com/wordservice/mvc/ApplicationConfig.java
Java
gpl-2.0
1,815
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_07) on Wed Mar 07 15:34:11 CET 2007 --> <TITLE> Uses of Class thread.ViewTheoryThread </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class thread.ViewTheoryThread"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../thread/ViewTheoryThread.html" title="class in thread"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?thread//class-useViewTheoryThread.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ViewTheoryThread.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>thread.ViewTheoryThread</B></H2> </CENTER> No usage of thread.ViewTheoryThread <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../thread/ViewTheoryThread.html" title="class in thread"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?thread//class-useViewTheoryThread.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ViewTheoryThread.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
marcoramilli/spampig
docs/docSpamPIG/thread/class-use/ViewTheoryThread.html
HTML
gpl-2.0
5,507
package net.brokentrain.ftf.ui.gui.dialog; import net.brokentrain.ftf.ui.gui.GUI; import net.brokentrain.ftf.ui.gui.util.BrowserUtil; import net.brokentrain.ftf.ui.gui.util.FontUtil; import net.brokentrain.ftf.ui.gui.util.LayoutDataUtil; import net.brokentrain.ftf.ui.gui.util.LayoutUtil; import net.brokentrain.ftf.ui.gui.util.PaintUtil; import net.brokentrain.ftf.ui.gui.util.URLUtil; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; public class AboutDialog extends Dialog { private static final int LOGO_SIZE = 250; private Label fetcherIcon; private String title; public AboutDialog(Shell parentShell, String dialogTitle) { super(parentShell); this.title = dialogTitle; } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText(title); } @Override protected void createButtonsForButtonBar(Composite parent) { ((GridLayout) parent.getLayout()).marginHeight = 10; ((GridLayout) parent.getLayout()).marginWidth = 10; createButton(parent, IDialogConstants.OK_ID, "OK", true).setFont( FontUtil.dialogFont); } @Override protected Control createDialogArea(Composite parent) { Composite composite = (Composite) super.createDialogArea(parent); composite.setLayout(LayoutUtil.createGridLayout(1, 0, 0)); composite.setBackground(GUI.display.getSystemColor(SWT.COLOR_WHITE)); Composite bannerHolder = new Composite(composite, SWT.NONE); bannerHolder.setLayout(LayoutUtil.createFillLayout(0, 0)); bannerHolder.setBackground(GUI.display.getSystemColor(SWT.COLOR_WHITE)); fetcherIcon = new Label(bannerHolder, SWT.NONE); fetcherIcon.setImage(PaintUtil.iconFetcher); fetcherIcon.setCursor(GUI.display.getSystemCursor(SWT.CURSOR_HAND)); fetcherIcon.setToolTipText(URLUtil.FTF_WEBPAGE); fetcherIcon.setBackground(GUI.display.getSystemColor(SWT.COLOR_WHITE)); fetcherIcon.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { BrowserUtil.openLink(URLUtil.FTF_WEBPAGE); } }); Composite aboutTextHolder = new Composite(composite, SWT.NONE); aboutTextHolder.setLayoutData(LayoutDataUtil.createGridData( GridData.FILL_HORIZONTAL, 1, LOGO_SIZE)); aboutTextHolder.setLayout(LayoutUtil.createFillLayout(10, 10)); aboutTextHolder.setBackground(GUI.display .getSystemColor(SWT.COLOR_WHITE)); StyledText aboutTextLabel = new StyledText(aboutTextHolder, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY); aboutTextLabel.setText((char) 169 + " 2006-2007. All rights reserved.\n\n"); aboutTextLabel.setFont(FontUtil.dialogFont); aboutTextLabel.setCaret(null); aboutTextLabel.setBackground(GUI.display .getSystemColor(SWT.COLOR_WHITE)); Composite sepHolder = new Composite(parent, SWT.NONE); sepHolder.setLayoutData(LayoutDataUtil.createGridData( GridData.FILL_HORIZONTAL, 2)); sepHolder.setLayout(LayoutUtil.createGridLayout(1, 0, 0)); sepHolder.setBackground(GUI.display.getSystemColor(SWT.COLOR_WHITE)); Label separator = new Label(sepHolder, SWT.SEPARATOR | SWT.HORIZONTAL); separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); return composite; } @Override protected int getShellStyle() { int style = SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL | getDefaultOrientation(); return style; } @Override protected void setButtonLayoutData(Button button) { GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL); int widthHint = convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH); data.widthHint = Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); button.setLayoutData(data); } }
gaving/ftf
src/net/brokentrain/ftf/ui/gui/dialog/AboutDialog.java
Java
gpl-2.0
4,580
// -*- C++ -*- // // DynamicLoader.h is a part of ThePEG - Toolkit for HEP Event Generation // Copyright (C) 1999-2011 Leif Lonnblad // // ThePEG is licenced under version 2 of the GPL, see COPYING for details. // Please respect the MCnet academic guidelines, see GUIDELINES for details. // #ifndef ThePEG_DynamicLoader_H #define ThePEG_DynamicLoader_H // This is the declaration of the DynamicLoader class. #include "ThePEG/Config/ThePEG.h" namespace ThePEG { /** * <code>DynamicLoader</code> is the general interface to the dynamic * loader functions of the underlying operating system. Currently it * only works on Linux. * * @see ClassTraits * @see ClassDescription * @see DescriptionList * @see PersistentIStream */ class DynamicLoader { public: /** * The actual load command used on the current platform. */ static bool loadcmd(string); /** * Try to load the file given as argument. If the filename does not * begin with a '/', try to prepend the paths one at the time until * success. If all fail try without prepending a path. * @return true if the loading succeeded, false otherwise. */ static bool load(string file); /** * Add a path to the bottom of the list of directories to seach for * dynaically linkable libraries. */ static void appendPath(string); /** * Add a path to the top of the list of directories to seach for * dynaically linkable libraries. */ static void prependPath(string); /** * Return the last error message issued from the platforms loader. */ static string lastErrorMessage; /** * Insert the name of the given library with correct version numbers * appended, in the corresponding map. */ static void dlname(string); /** * Given a list of generic library names, return the same list with * appended version numbers where available. */ static string dlnameversion(string libs); /** * Return the full list of directories to seach for dynaically * linkable libraries. */ static const vector<string> & allPaths(); /** * Return the list of appended directories to seach for dynaically * linkable libraries. */ static const vector<string> & appendedPaths(); /** * Return the list of prepended directories to seach for dynaically * linkable libraries. */ static const vector<string> & prependedPaths(); private: /** * The list of directories to seach for dynaically linkable * libraries. */ static vector<string> paths; /** * The list of prepended directories to seach for dynaically linkable * libraries. */ static vector<string> prepaths; /** * The list of appended directories to seach for dynaically linkable * libraries. */ static vector<string> apppaths; /** * Used to initialize the paths vector from the ThePEG_PATH * environment. */ static vector<string> defaultPaths(); /** * Map of names of dynamic libraries with correct version numbers * indexed by their generic names. */ static map<string,string> versionMap; }; } #endif /* ThePEG_DynamicLoader_H */
cms-externals/thepeg
Utilities/DynamicLoader.h
C
gpl-2.0
3,118
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] use anyhow::{Error, Result}; use blobrepo::BlobRepo; use blobrepo_hg::BlobRepoHg; use context::CoreContext; use futures::{FutureExt, TryFutureExt}; use futures_old::{stream, Stream as StreamOld}; use mercurial_bundles::obsmarkers::MetadataEntry; use mercurial_bundles::{part_encode::PartEncodeBuilder, parts}; use mercurial_types::HgChangesetId; use mononoke_types::DateTime; pub fn pushrebased_changesets_to_obsmarkers_part( ctx: CoreContext, blobrepo: &BlobRepo, pushrebased_changesets: Vec<pushrebase::PushrebaseChangesetPair>, ) -> Option<Result<PartEncodeBuilder>> { let filtered_changesets: Vec<_> = pushrebased_changesets .into_iter() .filter(|c| c.id_old != c.id_new) .collect(); if filtered_changesets.is_empty() { return None; } let hg_pushrebased_changesets = pushrebased_changesets_to_hg_stream(ctx.clone(), blobrepo, filtered_changesets); let time = DateTime::now(); let mut metadata = vec![MetadataEntry::new("operation", "push")]; if let Some(user) = ctx.metadata().unix_name() { metadata.push(MetadataEntry::new("user", user.clone())); } let part = parts::obsmarkers_part(hg_pushrebased_changesets, time, metadata); Some(part) } fn pushrebased_changesets_to_hg_stream( ctx: CoreContext, blobrepo: &BlobRepo, pushrebased_changesets: Vec<pushrebase::PushrebaseChangesetPair>, ) -> impl StreamOld<Item = (HgChangesetId, Vec<HgChangesetId>), Error = Error> { let blobrepo = blobrepo.clone(); let futures = pushrebased_changesets.into_iter().map({ move |p| { let blobrepo = blobrepo.clone(); let ctx = ctx.clone(); async move { let (old, new) = futures::try_join!( blobrepo.get_hg_from_bonsai_changeset(ctx.clone(), p.id_old), blobrepo.get_hg_from_bonsai_changeset(ctx.clone(), p.id_new), )?; Ok((old, vec![new])) } .boxed() .compat() } }); stream::futures_unordered(futures) }
facebookexperimental/eden
eden/mononoke/repo_client/obsolete/src/lib.rs
Rust
gpl-2.0
2,303
/***************************************************************** Copyright (c) 1996-2001 the kicker authors. See file AUTHORS. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************/ #ifndef _konqy_menu_h_ #define _konqy_menu_h_ #include <kpanelmenu.h> #include <qvaluevector.h> class KonquerorProfilesMenu : public KPanelMenu { Q_OBJECT public: KonquerorProfilesMenu(QWidget *parent, const char *name, const QStringList & /*args*/); ~KonquerorProfilesMenu(); protected slots: void slotExec(int id); void initialize(); void slotAboutToShow(); protected: void reload(); QValueVector<QString> m_profiles; }; #endif
iegor/kdebase
kicker/menuext/konq-profiles/konqy_menu.h
C
gpl-2.0
1,694
#! /bin/sh -e # tup - A file-based build system # # Copyright (C) 2013-2020 Mike Shal <marfey@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # Sometimes we may want to skip further processing if a command produces # the same output as last time. Since this requires essentially diffing # the old outputs vs the new, it requires a per-command flag. . ./tup.sh cat > ok.sh << HERE echo stringa > a echo stringb > b echo stringc > c HERE cat > Tupfile << HERE : |> ^o sh ok.sh^ sh ok.sh |> a b c : a |> cat a |> : b |> cat b |> : c |> cat c |> HERE update > .output.txt gitignore_good stringa .output.txt gitignore_good stringb .output.txt gitignore_good stringc .output.txt cat > ok.sh << HERE echo stringa > a echo stringb > b echo cstring > c HERE tup touch ok.sh update > .output.txt gitignore_bad stringa .output.txt gitignore_bad stringb .output.txt gitignore_good cstring .output.txt eotup
ppannuto/tup
test/t4147-skip-same-outputs.sh
Shell
gpl-2.0
1,509
<?php /* * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; under version 2 of the License (non-upgradable). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Copyright (c) 2013 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT); */ namespace oat\taoQtiItem\model\qti; use oat\taoQtiItem\model\qti\container\FlowContainer; use oat\taoQtiItem\model\qti\container\ContainerItemBody; use oat\taoQtiItem\model\qti\interaction\Interaction; use oat\taoQtiItem\model\qti\feedback\ModalFeedback; use oat\taoQtiItem\model\qti\response\TemplatesDriven; use oat\taoQtiItem\model\qti\exception\QtiModelException; use \common_Serializable; use \common_Logger; use \common_ext_ExtensionsManager; use \taoItems_models_classes_TemplateRenderer; use \DOMDocument; use oat\tao\helpers\Template; /** * The QTI_Item object represent the assessmentItem. * It's the main QTI object, it contains all the other objects and * is the main point to render a complete item. * * @access public * @author Sam, <sam@taotesting.com> * @package taoQTI * @see http://www.imsglobal.org/question/qti_v2p0/imsqti_infov2p0.html#section10042 */ class Item extends IdentifiedElement implements FlowContainer, IdentifiedElementContainer, common_Serializable { /** * the QTI tag name as defined in QTI standard * * @access protected * @var string */ protected static $qtiTagName = 'assessmentItem'; /** * Item's body content * * @var \oat\taoQtiItem\model\qti\container\ContainerItemBody */ protected $body = null; /** * Item's response processing * * @access protected * @var array */ protected $responses = []; /** * Item's response processing * * @access protected * @var ResponseProcessing */ protected $responseProcessing = null; /** * Item's outcomes * * @access protected * @var array */ protected $outcomes = []; /** * Item's stylesheets * * @access protected * @var array */ protected $stylesheets = []; /** * Rubric blocks * * @access protected * @var array */ protected $modalFeedbacks = []; /** * The namespaces defined in the original qti.xml file, * others that the standard included ones * * @var array */ protected $namespaces = []; /** * The schema locations defined in the original qti.xml file, * * @var array */ protected $schemaLocations = []; /** * The information on apip accessibility. * It is currently stored as an xml string. * This opens opprtunity to manage APIP accessibility more thouroughly in the future * * @var type */ protected $apipAccessibility = ''; /** * Short description of method __construct * * @access public * @author Sam, <sam@taotesting.com> * @param array $attributes * @return mixed */ public function __construct($attributes = []) { // override the tool options ! $attributes['toolName'] = PRODUCT_NAME; $attributes['toolVersion'] = \tao_models_classes_TaoService::singleton()->getPlatformVersion(); // create container $this->body = new ContainerItemBody('', $this); parent::__construct($attributes); } public function addNamespace($name, $uri) { $this->namespaces[$name] = $uri; } public function getNamespaces() { return $this->namespaces; } public function getNamespace($uri) { return array_search($uri, $this->namespaces); } public function addSchemaLocation($uri, $url) { $this->schemaLocations[$uri] = $url; } public function getSchemaLocations() { return $this->schemaLocations; } public function getSchemaLocation($uri) { return $this->schemaLocations[$uri]; } public function setApipAccessibility($apipXml) { $this->apipAccessibility = $apipXml; } public function getApipAccessibility() { return $this->apipAccessibility; } protected function getUsedAttributes() { return [ 'oat\\taoQtiItem\\model\\qti\\attribute\\Title', 'oat\\taoQtiItem\\model\\qti\\attribute\\Label', 'oat\\taoQtiItem\\model\\qti\\attribute\\Lang', 'oat\\taoQtiItem\\model\\qti\\attribute\\Adaptive', 'oat\\taoQtiItem\\model\\qti\\attribute\\TimeDependent', 'oat\\taoQtiItem\\model\\qti\\attribute\\ToolName', 'oat\\taoQtiItem\\model\\qti\\attribute\\ToolVersion' ]; } public function getBody() { return $this->body; } /** * Short description of method addInteraction * * @access public * @author Sam, <sam@taotesting.com> * @param Interaction $interaction * @param $body * @return bool */ public function addInteraction(Interaction $interaction, $body) { $returnValue = false; if (!is_null($interaction)) { $returnValue = $this->getBody()->setElement($interaction, $body); } return (bool) $returnValue; } /** * Short description of method removeInteraction * * @access public * @author Sam, <sam@taotesting.com> * @param Interaction $interaction * @return bool */ public function removeInteraction(Interaction $interaction) { $returnValue = false; if (!is_null($interaction)) { $returnValue = $this->getBody()->removeElement($interaction); } return (bool) $returnValue; } public function getInteractions() { return $this->getComposingElements('oat\taoQtiItem\model\qti\interaction\Interaction'); } public function getObjects() { return $this->body->getElements(\oat\taoQtiItem\model\qti\QtiObject::class); } public function getRubricBlocks() { return $this->body->getElements('oat\\taoQtiItem\\model\\qti\\RubricBlock'); } public function getRelatedItem() { return $this; // the related item of an item is itself! } /** * Short description of method getResponseProcessing * * @access public * @author Sam, <sam@taotesting.com> * @return \oat\taoQtiItem\model\qti\response\ResponseProcessing */ public function getResponseProcessing() { return $this->responseProcessing; } /** * Short description of method setResponseProcessing * * @access public * @author Sam, <sam@taotesting.com> * @param $rprocessing * @return mixed */ public function setResponseProcessing($rprocessing) { $this->responseProcessing = $rprocessing; } /** * Short description of method setOutcomes * * @access public * @author Sam, <sam@taotesting.com> * @param * array outcomes * @return mixed * @throws InvalidArgumentException */ public function setOutcomes($outcomes) { $this->outcomes = []; foreach ($outcomes as $outcome) { if (!$outcome instanceof OutcomeDeclaration) { throw new \InvalidArgumentException("wrong entry in outcomes list"); } $this->addOutcome($outcome); } } /** * add an outcome declaration to the item * * @param \oat\taoQtiItem\model\qti\OutcomeDeclaration $outcome */ public function addOutcome(OutcomeDeclaration $outcome) { $this->outcomes[$outcome->getSerial()] = $outcome; $outcome->setRelatedItem($this); } /** * Short description of method getOutcomes * * @access public * @author Sam, <sam@taotesting.com> * @return array */ public function getOutcomes() { return $this->outcomes; } /** * Short description of method getOutcome * * @access public * @author Sam, <sam@taotesting.com> * @param * string serial * @return \oat\taoQtiItem\model\qti\OutcomeDeclaration */ public function getOutcome($serial) { $returnValue = null; if (!empty($serial)) { if (isset($this->outcomes[$serial])) { $returnValue = $this->outcomes[$serial]; } } return $returnValue; } /** * Short description of method removeOutcome * * @access public * @author Sam, <sam@taotesting.com> * @param OutcomeDeclaration $outcome * @return bool */ public function removeOutcome(OutcomeDeclaration $outcome) { $returnValue = (bool) false; if (!is_null($outcome)) { if (isset($this->outcomes[$outcome->getSerial()])) { unset($this->outcomes[$outcome->getSerial()]); $returnValue = true; } } else { common_Logger::w('Tried to remove null outcome'); } if (!$returnValue) { common_Logger::w('outcome not found ' . $outcome->getSerial()); } return (bool) $returnValue; } public function addResponse(ResponseDeclaration $response) { $this->responses[$response->getSerial()] = $response; $response->setRelatedItem($this); } public function getResponses() { return $this->responses; } public function addModalFeedback(ModalFeedback $modalFeedback) { $this->modalFeedbacks[$modalFeedback->getSerial()] = $modalFeedback; $modalFeedback->setRelatedItem($this); } public function removeModalFeedback(ModalFeedback $modalFeedback) { unset($this->modalFeedbacks[$modalFeedback->getSerial()]); } /** * Get the modal feedbacks of the item * * @access public * @author Sam, <sam@taotesting.com> * @return array */ public function getModalFeedbacks() { return $this->modalFeedbacks; } public function getModalFeedback($serial) { $returnValue = null; if (isset($this->modalFeedbacks[$serial])) { $returnValue = $this->modalFeedbacks[$serial]; } return $returnValue; } /** * Get the stylesheets of the item * * @access public * @author Sam, <sam@taotesting.com> * @return array */ public function getStylesheets() { return (array) $this->stylesheets; } public function addStylesheet(Stylesheet $stylesheet) { // @todo : validate style sheet before adding: $this->stylesheets[$stylesheet->getSerial()] = $stylesheet; $stylesheet->setRelatedItem($this); } public function removeStylesheet(Stylesheet $stylesheet) { unset($this->stylesheets[$stylesheet->getSerial()]); } public function removeResponse($response) { $serial = ''; if ($response instanceof ResponseDeclaration) { $serial = $response->getSerial(); } elseif (is_string($response)) { $serial = $response; } else { throw new \InvalidArgumentException('the argument must be an instance of taoQTI_models_classes_QTI_ResponseDeclaration or a string serial'); } if (!empty($serial)) { unset($this->responses[$serial]); } } /** * Get recursively all included identified QTI elements in the object (identifier => Object) * * @return array */ public function getIdentifiedElements() { $returnValue = $this->getBody()->getIdentifiedElements(); $returnValue->addMultiple($this->getOutcomes()); $returnValue->addMultiple($this->getResponses()); $returnValue->addMultiple($this->getModalFeedbacks()); return $returnValue; } /** * Short description of method toXHTML * * @access public * @author Sam, <sam@taotesting.com> * @param array $options * @param array $filtered * @return string */ public function toXHTML($options = [], &$filtered = []) { $template = static::getTemplatePath() . '/xhtml.item.tpl.php'; // get the variables to use in the template $variables = $this->getAttributeValues(); $variables['stylesheets'] = []; foreach ($this->getStylesheets() as $stylesheet) { $variables['stylesheets'][] = $stylesheet->getAttributeValues(); } //additional css: if (isset($options['css'])) { foreach ($options['css'] as $css) { $variables['stylesheets'][] = ['href' => $css, 'media' => 'all']; } } //additional js: $variables['javascripts'] = []; $variables['js_variables'] = []; if (isset($options['js'])) { foreach ($options['js'] as $js) { $variables['javascripts'][] = ['src' => $js]; } } if (isset($options['js_var'])) { foreach ($options['js_var'] as $name => $value) { $variables['js_variables'][$name] = $value; } } //user scripts $variables['user_scripts'] = $this->getUserScripts(); $dataForDelivery = $this->getDataForDelivery(); $variables['itemData'] = $dataForDelivery['core']; //copy all variable data into filtered array foreach ($dataForDelivery['variable'] as $serial => $data) { $filtered[$serial] = $data; } $variables['contentVariableElements'] = isset($options['contentVariableElements']) && is_array($options['contentVariableElements']) ? $options['contentVariableElements'] : []; $variables['tao_lib_path'] = isset($options['path']) && isset($options['path']['tao']) ? $options['path']['tao'] : ''; $variables['taoQtiItem_lib_path'] = isset($options['path']) && isset($options['path']['taoQtiItem']) ? $options['path']['taoQtiItem'] : ''; $variables['client_config_url'] = isset($options['client_config_url']) ? $options['client_config_url'] : ''; $tplRenderer = new taoItems_models_classes_TemplateRenderer($template, $variables); $returnValue = $tplRenderer->render(); return (string) $returnValue; } protected function getUserScripts() { $userScripts = []; $userScriptConfig = \common_ext_ExtensionsManager::singleton()->getExtensionById('taoQtiItem')->getConfig('userScripts'); if (is_array($userScriptConfig)) { foreach ($userScriptConfig as $data) { $userScripts[] = Template::js($data['src'], $data['extension']); } } return $userScripts; } public static function getTemplateQti() { return static::getTemplatePath() . '/qti.item.tpl.php'; } protected function getTemplateQtiVariables() { $variables = parent::getTemplateQtiVariables(); $variables['stylesheets'] = ''; foreach ($this->stylesheets as $stylesheet) { $variables['stylesheets'] .= $stylesheet->toQTI(); } $variables['responses'] = ''; foreach ($this->responses as $response) { $variables['responses'] .= $response->toQTI(); } $variables['outcomes'] = ''; foreach ($this->outcomes as $outcome) { $variables['outcomes'] .= $outcome->toQTI(); } $variables['feedbacks'] = ''; foreach ($this->modalFeedbacks as $feedback) { $variables['feedbacks'] .= $feedback->toQTI(); } $variables['namespaces'] = $this->getNamespaces(); $schemaLocations = ''; foreach ($this->getSchemaLocations() as $uri => $url) { $schemaLocations .= $uri . ' ' . $url . ' '; } $variables['schemaLocations'] = trim($schemaLocations); $nsXsi = $this->getNamespace('http://www.w3.org/2001/XMLSchema-instance'); $variables['xsi'] = $nsXsi ? $nsXsi . ':' : 'xsi:'; // render the responseProcessing $renderedResponseProcessing = ''; $responseProcessing = $this->getResponseProcessing(); if (isset($responseProcessing)) { if ($responseProcessing instanceof TemplatesDriven) { $renderedResponseProcessing = $responseProcessing->buildQTI(); } else { $renderedResponseProcessing = $responseProcessing->toQTI(); } } // move item CSS class to itemBody $variables['class'] = $this->getAttributeValue('class'); unset($variables['attributes']['class']); $variables['renderedResponseProcessing'] = $renderedResponseProcessing; $variables['apipAccessibility'] = $this->getApipAccessibility(); return $variables; } /** * Short description of method toQTI * * @access public * @author Sam, <sam@taotesting.com> * @param boolean $validate (optional) Validate the XML output against QTI Specification (XML Schema). Default is false. * @return string * @throws exception\QtiModelException */ public function toXML($validate = false) { $returnValue = ''; $qti = $this->toQTI(); // render and clean the xml $dom = new DOMDocument('1.0', 'UTF-8'); $domDocumentConfig = \common_ext_ExtensionsManager::singleton()->getExtensionById('taoQtiItem')->getConfig('XMLParser'); if (is_array($domDocumentConfig) && !empty($domDocumentConfig)) { foreach ($domDocumentConfig as $param => $value) { if (property_exists($dom, $param)) { $dom->$param = $value; } } } else { $dom->formatOutput = true; $dom->preserveWhiteSpace = false; $dom->validateOnParse = false; } if ($dom->loadXML($qti)) { $returnValue = $dom->saveXML(); //in debug mode, systematically check if the save QTI is standard compliant if ($validate) { $parserValidator = new Parser($returnValue); $parserValidator->validate(); if (!$parserValidator->isValid()) { common_Logger::w('Invalid QTI output: ' . PHP_EOL . ' ' . $parserValidator->displayErrors()); } } } else { $parserValidator = new Parser($qti); $parserValidator->validate(); if (!$parserValidator->isValid()) { throw new QtiModelException('Wrong QTI item output format'); } } return (string) $returnValue; } /** * Serialize item object into json format, handy to be used in js */ public function toArray($filterVariableContent = false, &$filtered = []) { $data = parent::toArray($filterVariableContent, $filtered); $data['namespaces'] = $this->getNamespaces(); $data['schemaLocations'] = $this->getSchemaLocations(); $data['stylesheets'] = $this->getArraySerializedElementCollection($this->getStylesheets(), $filterVariableContent, $filtered); $data['outcomes'] = $this->getArraySerializedElementCollection($this->getOutcomes(), $filterVariableContent, $filtered); $data['responses'] = $this->getArraySerializedElementCollection($this->getResponses(), $filterVariableContent, $filtered); $data['feedbacks'] = $this->getArraySerializedElementCollection($this->getModalFeedbacks(), $filterVariableContent, $filtered); $data['responseProcessing'] = $this->responseProcessing->toArray($filterVariableContent, $filtered); $data['apipAccessibility'] = $this->getApipAccessibility(); return $data; } public function getDataForDelivery() { $filtered = []; $itemData = $this->toArray(true, $filtered); unset($itemData['responseProcessing']); return ['core' => $itemData, 'variable' => $filtered]; } /** * @return mixed */ public function toForm() { $formContainer = new AssessmentItem($this); $returnValue = $formContainer->getForm(); return $returnValue; } }
oat-sa/extension-tao-itemqti
model/qti/Item.php
PHP
gpl-2.0
20,934
'use strict'; var express = require('express'); var passport = require('passport'); var config = require('../config/environment'); var User = require('../api/user/user.model'); // Passport Configuration require('./local/passport').setup(User, config); require('./facebook/passport').setup(User, config); require('./twitter/passport').setup(User, config); require('./basic/passport').setup(User, config); var router = express.Router(); router.use('/local', require('./local')); router.use('/facebook', require('./facebook')); router.use('/twitter', require('./twitter')); router.use('/oauth', require('./basic')); module.exports = router;
lbroudoux/vomov
server/auth/index.js
JavaScript
gpl-2.0
642
#define SVNWCREV_VERSION "1.1, Build 10"
cwtaylor2/testwcrev
src/version.h
C
gpl-2.0
42
FunWithNode =========== my first software project ever :) I am noob I'm going to be playing around with git and nodejs, trying to setup things like a webserver
ironmig/FunWithNode
README.md
Markdown
gpl-2.0
162
/**************************************************************** * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) * ============================================================= * License Information: http://lamsfoundation.org/licensing/lams/2.0/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2.0 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** */ package org.lamsfoundation.lams.lesson.dao; import java.util.Date; import java.util.List; import java.util.Map; import org.lamsfoundation.lams.learningdesign.Activity; import org.lamsfoundation.lams.lesson.LearnerProgress; import org.lamsfoundation.lams.lesson.LearnerProgressArchive; import org.lamsfoundation.lams.usermanagement.User; /** * Inteface defines Lesson DAO Methods * * @author chris */ public interface ILearnerProgressDAO { /** * Retrieves the Lesson * * @param lessonId * identifies the lesson to get * @return the lesson */ LearnerProgress getLearnerProgress(Long learnerProgressId); /** * Retrieves the learner progress object for user in a lesson. * * @param learnerId * the user who owns the learner progress data. * @param lessonId * the lesson for which the progress data applies * @return the user's progress data */ LearnerProgress getLearnerProgressByLearner(Integer learnerId, Long lessonId); /** * Saves or Updates learner progress data. * * @param learnerProgress * holds the learne progress data */ void saveLearnerProgress(LearnerProgress learnerProgress); /** * Deletes a LearnerProgress data <b>permanently</b>. * * @param learnerProgress */ void deleteLearnerProgress(LearnerProgress learnerProgress); /** * Update learner progress data. * * @param learnerProgress */ void updateLearnerProgress(LearnerProgress learnerProgress); /** * Get all the learner progress records where the current, previous or next activity is the given activity. * * @param activity * @return List<LearnerProgress> */ List<LearnerProgress> getLearnerProgressReferringToActivity(Activity activity); /** * Get learners who most recently entered the activity. */ List<User> getLearnersLatestByActivity(Long activityId, Integer limit, Integer offset); /** * Get learners who are at the given activities at the moment. */ List<User> getLearnersByActivities(Long[] activityIds, Integer limit, Integer offset, boolean orderAscending); /** * Get learners who most recently finished the lesson. */ List<User> getLearnersLatestCompletedForLesson(Long lessonId, Integer limit, Integer offset); /** * Get learners whose first name, last name or login match any of the tokens from search phrase. Sort by most * progressed first, then by name. Used by Learners tab in Monitoring interface. */ List<User> getLearnersByMostProgress(Long lessonId, String searchPhrase, Integer limit, Integer offset); /** * Get learner progress records for a lesson where the progress is marked as completed. * * @param lessonId * @return List<LearnerProgress> */ List<LearnerProgress> getCompletedLearnerProgressForLesson(Long lessonId, Integer limit, Integer offset, boolean orderAscending); /** * Get all the learner progress records for a lesson. * * @param lessonId * @return */ List<LearnerProgress> getLearnerProgressForLesson(Long lessonId); /** * Get all the learner progress records for a lesson restricted by list of these user ids. * * @param lessonId * @param userIds * return progresses for only these users * @return */ List<LearnerProgress> getLearnerProgressForLesson(Long lessonId, List<Integer> userIds); /** * Get all the learner progresses for a lesson list. * * @param lessonIds * @return */ List<LearnerProgress> getLearnerProgressForLessons(List<Long> lessonIds); /** * Get all the users records where the user has attempted the given activity, but has not completed it yet. Uses the * progress records to determine the users. */ List<User> getLearnersAttemptedActivity(Activity activity); /** * Get all the users records where the user has completed the given activity. Uses the progress records to determine * the users. */ List<User> getLearnersCompletedActivity(Activity activity); /** * Get all the users records where the user has ever attempted the given activity. Uses the progress records to * determine the users. * * @param activityId * @return List<User> */ List<User> getLearnersAttemptedOrCompletedActivity(Activity activity); /** * Count of the number of users that have attempted or completed an activity. Useful for activities that don't have * tool sessions. */ Integer getNumUsersAttemptedOrCompletedActivity(Activity activity); /** * Count of the number of users that have attempted but not completed an activity. Useful for activities that don't * have * tool sessions. */ Integer getNumUsersAttemptedActivity(Activity activity); /** * Count of the number of users that have completed an activity. Useful for activities that don't have tool * sessions. * * @param activityId * @return List<User> */ Integer getNumUsersCompletedActivity(Activity activity); /** * Get number of learners whose first name, last name or login match any of the tokens from search phrase. */ Integer getNumUsersByLesson(Long lessonId, String searchPhrase); /** * Get number of learners who finished the given lesson. */ Integer getNumUsersCompletedLesson(Long lessonId); /** * Get number of learners who are at the given activities at the moment. */ Map<Long, Integer> getNumUsersCurrentActivities(Long[] activityIds); /** * Get the last attempt ID for the given learner and lesson. */ Integer getLearnerProgressArchiveMaxAttemptID(Integer userId, Long lessonId); /** Get the number of learners who are in a particular activity at the moment */ Integer getNumUsersCurrentActivity(Activity activity); LearnerProgressArchive getLearnerProgressArchive(Long lessonId, Integer userId, Date archiveDate); }
lamsfoundation/lams
lams_common/src/java/org/lamsfoundation/lams/lesson/dao/ILearnerProgressDAO.java
Java
gpl-2.0
7,216
require 'activeresource' # WARNING: this is not really maintained or tested... # Install the ActiveResource gem if you don't already have it: # # sudo gem install activeresource --source http://gems.rubyonrails.org --include-dependencies # $ SITE="http://myusername:p4ssw0rd@mytracksinstallation.com" irb -r tracks_api_wrapper.rb # # >> my_pc = Tracks::Context.find(:first) # => #<Tracks::Context:0x139c3c0 @prefix_options={}, @attributes={"name"=>"my pc", "updated_at"=>Mon Aug 13 02:56:18 UTC 2007, "hide"=>0, "id"=>8, "position"=>1, "created_at"=>Wed Feb 28 07:07:28 UTC 2007} # >> my_pc.name # => "my pc" # >> my_pc.todos # => [#<Tracks::Todo:0x1e16b84 @prefix_options={}, @attributes={"context_id"=>8, "completed_at"=>Tue Apr 10 12:57:24 UTC 2007, "project_id"=>nil, "show_from"=>nil, "id"=>1432, "notes"=>nil, "description"=>"check rhino mocks bug", "due"=>Mon, 09 Apr 2007, "created_at"=>Sun Apr 08 04:56:35 UTC 2007, "state"=>"completed"}, #<Tracks::Todo:0x1e16b70 @prefix_options={}, @attributes={"context_id"=>8, "completed_at"=>Mon Oct 10 13:10:21 UTC 2005, "project_id"=>10, "show_from"=>nil, "id"=>17, "notes"=>"fusion problem", "description"=>"Fix Client Installer", "due"=>nil, "created_at"=>Sat Oct 08 00:19:33 UTC 2005, "state"=>"completed"}] # # >> t = Tracks::Todo.new # => #<Tracks::Todo:0x1ee9fc0 @prefix_options={}, @attributes={}> # >> t.description = "do it now" # => "do it now" # >> t.context_id = 8 # => 8 # >> t.save # => true # >> t.reload # => #<Tracks::Todo:0x1ee9fc0 @prefix_options={}, @attributes={"completed_at"=>nil, "context_id"=>8, "project_id"=>nil, "show_from"=>nil, "notes"=>nil, "id"=>1791, "description"=>"do it now", "due"=>nil, "created_at"=>Mon Dec 03 19:15:46 UTC 2007, "state"=>"active"} # >> t.put(:toggle_check) # => #<Net::HTTPOK 200 OK readbody=true> # >> t.reload # => #<Tracks::Todo:0x1ee9fc0 @prefix_options={}, @attributes={"completed_at"=>Mon Dec 03 19:17:46 UTC 2007, "context_id"=>8, "project_id"=>nil, "show_from"=>nil, "notes"=>nil, "id"=>1791, "description"=>"do it now", "due"=>nil, "created_at"=>Mon Dec 03 19:15:46 UTC 2007, "state"=>"completed"} # If you want to see the HTTP requests and responses that are being passed back and # forth, you can tweak your active_resource like as described in: # http://blog.pepperdust.org/2007/2/13/enabling-wire-level-debug-output-for-activeresource module Tracks class Base < ActiveResource::Base self.site = ENV["SITE"] || "http://127.0.0.1:3000/" end class Todo < Base end class Context < Base def todos return attributes["todos"] if attributes.keys.include?("todos") return Todo.find(:all, :params => {:context_id => id}) end end class Project < Base def todos return attributes["todos"] if attributes.keys.include?("todos") return Todo.find(:all, :params => {:project_id => id}) end end end
sprestage/ranch-tracks
doc/tracks_api_wrapper.rb
Ruby
gpl-2.0
2,871
/******************************************************************************* * Copyright 2014, * Luis Pina <luis@luispina.me>, * Michael Hicks <mwh@cs.umd.edu> * * This file is part of Rubah. * * Rubah is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Rubah is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Rubah. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package rubah.runtime.state.migrator; import rubah.runtime.state.strategy.MigrationStrategy; public abstract class MigratorSubFactory { protected MigrationStrategy strategy; public MigratorSubFactory(MigrationStrategy strategy) { this.strategy = strategy; } public abstract boolean canMigrate(Class<?> c); public abstract Migrator buildMigrator(); public long countMigrated() { return 0L; } public abstract class Migrator { public Object migrate(Object obj) { Object ret = this.doMigrate(obj); return ret; } protected abstract Object doMigrate(Object pre); public abstract void followReferences(Object post); public Object registerMapping(Object pre, Object post) { return strategy.getMapping().put(pre, post); } protected void follow(Object ref) { strategy.migrate(ref); } } }
plum-umd/rubah
src/main/java/rubah/runtime/state/migrator/MigratorSubFactory.java
Java
gpl-2.0
1,796
/* This file is part of the Vc library. Copyright (C) 2010-2012 Matthias Kretz <kretz@kde.org> Vc is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Vc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Vc. If not, see <http://www.gnu.org/licenses/>. */ #ifndef VC_VERSION_H #define VC_VERSION_H #define VC_VERSION_STRING "0.7.4" #define VC_VERSION_NUMBER 0x000708 #define VC_VERSION_CHECK(major, minor, patch) ((major << 16) | (minor << 8) | (patch << 1)) #define VC_LIBRARY_ABI_VERSION 3 /*OUTER_NAMESPACE_BEGIN*/ namespace Vc { static inline const char *versionString() { return VC_VERSION_STRING; } static inline unsigned int versionNumber() { return VC_VERSION_NUMBER; } #if !defined(VC_NO_VERSION_CHECK) && !defined(VC_COMPILE_LIB) void checkLibraryAbi(unsigned int compileTimeAbi, unsigned int versionNumber, const char *versionString); namespace { static struct runLibraryAbiCheck { runLibraryAbiCheck() { checkLibraryAbi(VC_LIBRARY_ABI_VERSION, VC_VERSION_NUMBER, VC_VERSION_STRING); } } _runLibraryAbiCheck; } #endif } // namespace Vc /*OUTER_NAMESPACE_END*/ #endif // VC_VERSION_H
desdemonda/cbmroot
vc_074/include/Vc/version.h
C
gpl-2.0
1,701
""" .. module:: poes :synopsis: A module for reading, writing, and storing poes Data .. moduleauthor:: AJ, 20130129 ********************* **Module**: gme.sat.poes ********************* **Classes**: * :class:`poesRec` **Functions**: * :func:`readPoes` * :func:`readPoesFtp` * :func:`mapPoesMongo` * :func:`overlayPoesTed` """ from davitpy.gme.base.gmeBase import gmeData class poesRec(gmeData): """a class to represent a record of poes data. Extends :class:`gmeBase.gmeData`. Insight on the class members can be obtained from `the NOAA NGDC site <ftp://satdat.ngdc.noaa.gov/sem/poes/data/readme.txt>`_. Note that Poes data is available from 1998-present day (or whatever the latest NOAA has uploaded is). **The data are the 16-second averages** **Members**: * **time** (`datetime <http://tinyurl.com/bl352yx>`_): an object identifying which time these data are for * **info** (str): information about where the data come from. *Please be courteous and give credit to data providers when credit is due.* * **dataSet** (str): the name of the data set * **satnum** (ind): the noaa satellite number * **sslat** (float): Geographic Latitude of sub-satellite point, degrees * **sslon** (float): Geographic Longitude of sub-satellite point, degrees * **folat** (float): Geographic Latitude of foot-of-field-line, degrees * **folon** (float): Geographic Longitude of foot-of-field-line, degrees * **lval** (float): L-value * **mlt** (float): Magnetic local time of foot-of-field-line, degrees * **pas0** (float): MEPED-0 pitch angle at satellite, degrees * **pas90** (float): MEPED-90 pitch angle at satellite, degrees * **mep0e1** (float): MEPED-0 > 30 keV electrons, counts/sec * **mep0e2** (float): MEPED-0 > 100 keV electrons, counts/sec * **mep0e3** (float): MEPED-0 > 300 keV electrons, counts/sec * **mep0p1** (float):MEPED-0 30 keV to 80 keV protons, counts/sec * **mep0p2** (float): MEPED-0 80 keV to 240 keV protons, counts/sec * **mep0p3** (float): 240 kev to 800 keV protons, counts/sec * **mep0p4** (float): MEPED-0 800 keV to 2500 keV protons, counts/sec * **mep0p5** (float): MEPED-0 2500 keV to 6900 keV protons, counts/sec * **mep0p6** (float): MEPED-0 > 6900 keV protons, counts/sec, * **mep90e1** (float): MEPED-90 > 30 keV electrons, counts/sec, * **mep90e2** (float): MEPED-90 > 100 keV electrons, counts/sec * **mep90e3** (float): MEPED-90 > 300 keV electrons, counts/sec * **mep90p1** (float): MEPED-90 30 keV to 80 keV protons, counts/sec * **mep90p2** (float): MEPED-90 80 keV to 240 keV protons, counts/sec * **mep90p3** (float): MEPED-90 240 kev to 800 keV protons, counts/sec, * **mep90p4** (float): MEPED-90 800 keV to 2500 keV protons, counts/sec * **mep90p5** (float): MEPED-90 2500 keV to 6900 keV protons, counts/sec * **mep90p6** (float):MEPED-90 > 6900 keV protons, counts/sec * **mepomp6** (float): MEPED omni-directional > 16 MeV protons, counts/sec * **mepomp7** (float): MEPED omni-directional > 36 Mev protons, counts/sec * **mepomp8** (float): MEPED omni-directional > 70 MeV protons, counts/sec * **mepomp9** (float): MEPED omni-directional >= 140 MeV protons * **ted** (float): TED, Total Energy Detector Average, ergs/cm2/sec * **echar** (float): TED characteristic energy of electrons, eV * **pchar** (float): TED characteristic energy of protons, eV * **econtr** (float): TED electron contribution, Electron Energy/Total Energy .. note:: If any of the members have a value of None, this means that they could not be read for that specific time **Methods**: * :func:`parseFtp` **Example**: :: emptyPoesObj = gme.sat.poesRec() written by AJ, 20130131 """ def parseFtp(self,line, header): """This method is used to convert a line of poes data read from the NOAA NGDC FTP site into a :class:`poesRec` object. .. note:: In general, users will not need to worry about this. **Belongs to**: :class:`poesRec` **Args**: * **line** (str): the ASCII line from the FTP server **Returns**: * Nothing. **Example**: :: myPoesObj.parseFtp(ftpLine) written by AJ, 20130131 """ import datetime as dt #split the line into cols cols = line.split() head = header.split() self.time = dt.datetime(int(cols[0]), int(cols[1]), int(cols[2]), int(cols[3]),int(cols[4]), \ int(float(cols[5])),int(round((float(cols[5])-int(float(cols[5])))*1e6))) for key in self.__dict__.iterkeys(): if(key == 'dataSet' or key == 'info' or key == 'satnum' or key == 'time'): continue try: ind = head.index(key) except Exception,e: print e print 'problem setting attribute',key #check for a good value if(float(cols[ind]) != -999.): setattr(self,key,float(cols[ind])) def __init__(self, ftpLine=None, dbDict=None, satnum=None, header=None): """the intialization fucntion for a :class:`omniRec` object. .. note:: In general, users will not need to worry about this. **Belongs to**: :class:`omniRec` **Args**: * [**ftpLine**] (str): an ASCII line from the FTP server. if this is provided, the object is initialized from it. header must be provided in conjunction with this. default=None * [**header**] (str): the header from the ASCII FTP file. default=None * [**dbDict**] (dict): a dictionary read from the mongodb. if this is provided, the object is initialized from it. default = None * [**satnum**] (int): the satellite nuber. default=None **Returns**: * Nothing. **Example**: :: myPoesObj = poesRec(ftpLine=aftpLine) written by AJ, 20130131 """ #note about where data came from self.dataSet = 'Poes' self.info = 'These data were downloaded from NASA SPDF. *Please be courteous and give credit to data providers when credit is due.*' self.satnum = satnum self.sslat = None self.sslon = None self.folat = None self.folon = None self.lval = None self.mlt = None self.pas0 = None self.pas90 = None self.mep0e1 = None self.mep0e2 = None self.mep0e3 = None self.mep0p1 = None self.mep0p2 = None self.mep0p3 = None self.mep0p4 = None self.mep0p5 = None self.mep0p6 = None self.mep90e1 = None self.mep90e2 = None self.mep90e3 = None self.mep90p1 = None self.mep90p2 = None self.mep90p3 = None self.mep90p4 = None self.mep90p5 = None self.mep90p6 = None self.mepomp6 = None self.mepomp7 = None self.mepomp8 = None self.mepomp9 = None self.ted = None self.echar = None self.pchar = None self.econtr = None #if we're initializing from an object, do it! if(ftpLine != None): self.parseFtp(ftpLine,header) if(dbDict != None): self.parseDb(dbDict) def readPoes(sTime,eTime=None,satnum=None,folat=None,folon=None,ted=None,echar=None,pchar=None): """This function reads poes data. First, it will try to get it from the mongodb, and if it can't find it, it will look on the NOAA NGDC FTP server using :func:`readPoesFtp`. The data are 16-second averages **Args**: * **sTime** (`datetime <http://tinyurl.com/bl352yx>`_ or None): the earliest time you want data for * [**eTime**] (`datetime <http://tinyurl.com/bl352yx>`_ or None): the latest time you want data for. if this is None, end Time will be 1 day after sTime. default = None * [**satnum**] (int): the satellite you want data for. eg 17 for noaa17. if this is None, data for all satellites will be returned. default = None * [**satnum**] (list or None): if this is not None, it must be a 2-element list of numbers, [a,b]. In this case, only data with bx values in the range [a,b] will be returned. default = None * [**folat**] (list or None): if this is not None, it must be a 2-element list of numbers, [a,b]. In this case, only data with bx values in the range [a,b] will be returned. default = None * [**folon**] (list or None): if this is not None, it must be a 2-element list of numbers, [a,b]. In this case, only data with bye values in the range [a,b] will be returned. default = None * [**ted**] (list or None): if this is not None, it must be a 2-element list of numbers, [a,b]. In this case, only data with bze values in the range [a,b] will be returned. default = None * [**echar**] (list or None): if this is not None, it must be a 2-element list of numbers, [a,b]. In this case, only data with bym values in the range [a,b] will be returned. default = None * [**pchar**] (list or None): if this is not None, it must be a 2-element list of numbers, [a,b]. In this case, only data with bzm values in the range [a,b] will be returned. default = None **Returns**: * **poesList** (list or None): if data is found, a list of :class:`poesRec` objects matching the input parameters is returned. If no data is found, None is returned. **Example**: :: import datetime as dt poesList = gme.sat.readPoes(sTime=dt.datetime(2011,1,1),eTime=dt.datetime(2011,6,1),folat=[60,80]) written by AJ, 20130131 """ import datetime as dt import davitpy.pydarn.sdio.dbUtils as db #check all the inputs for validity assert(isinstance(sTime,dt.datetime)), \ 'error, sTime must be a datetime object' assert(eTime == None or isinstance(eTime,dt.datetime)), \ 'error, eTime must be either None or a datetime object' assert(satnum == None or isinstance(satnum,int)), 'error, satnum must be an int' var = locals() for name in ['folat','folon','ted','echar','pchar']: assert(var[name] == None or (isinstance(var[name],list) and \ isinstance(var[name][0],(int,float)) and isinstance(var[name][1],(int,float)))), \ 'error,'+name+' must None or a list of 2 numbers' if(eTime == None): eTime = sTime+dt.timedelta(days=1) qryList = [] #if arguments are provided, query for those qryList.append({'time':{'$gte':sTime}}) if(eTime != None): qryList.append({'time':{'$lte':eTime}}) if(satnum != None): qryList.append({'satnum':satnum}) var = locals() for name in ['folat','folon','ted','echar','pchar']: if(var[name] != None): qryList.append({name:{'$gte':min(var[name])}}) qryList.append({name:{'$lte':max(var[name])}}) #construct the final query definition qryDict = {'$and': qryList} #connect to the database poesData = db.getDataConn(dbName='gme',collName='poes') #do the query if(qryList != []): qry = poesData.find(qryDict) else: qry = poesData.find() if(qry.count() > 0): poesList = [] for rec in qry.sort('time'): poesList.append(poesRec(dbDict=rec)) print '\nreturning a list with',len(poesList),'records of poes data' return poesList #if we didn't find anything on the mongodb else: print '\ncould not find requested data in the mongodb' return None #print 'we will look on the ftp server, but your conditions will be (mostly) ignored' ##read from ftp server #poesList = readPoesFtp(sTime, eTime) #if(poesList != None): #print '\nreturning a list with',len(poesList),'recs of poes data' #return poesList #else: #print '\n no data found on FTP server, returning None...' #return None def readPoesFtp(sTime,eTime=None): """This function reads poes data from the NOAA NGDC server via anonymous FTP connection. .. warning:: You should not use this. Use the general function :func:`readPoes` instead. **Args**: * **sTime** (`datetime <http://tinyurl.com/bl352yx>`_): the earliest time you want data for * [**eTime**] (`datetime <http://tinyurl.com/bl352yx>`_ or None): the latest time you want data for. if this is None, eTime will be equal 1 day after sTime. default = None **Returns**: * **poesList** (list or None): if data is found, a list of :class:`poesRec` objects matching the input parameters is returned. If no data is found, None is returned. **Example**: :: import datetime as dt poesList = gme.sat.readpoesFtp(dt.datetime(2011,1,1,1,50),eTime=dt.datetime(2011,1,1,10,0)) written by AJ, 20130128 """ from ftplib import FTP import datetime as dt assert(isinstance(sTime,dt.datetime)),'error, sTime must be datetime' if(eTime == None): eTime=sTime+dt.timedelta(days=1) assert(isinstance(eTime,dt.datetime)),'error, eTime must be datetime' assert(eTime >= sTime), 'error, end time greater than start time' #connect to the server try: ftp = FTP('satdat.ngdc.noaa.gov') except Exception,e: print e print 'problem connecting to NOAA server' return None #login as anonymous try: l=ftp.login() except Exception,e: print e print 'problem logging in to NOAA server' return None myPoes = [] #get the poes data myTime = dt.datetime(sTime.year,sTime.month,sTime.day) while(myTime <= eTime): #go to the data directory try: ftp.cwd('/sem/poes/data/avg/txt/'+str(myTime.year)) except Exception,e: print e print 'error getting to data directory' return None #list directory contents dirlist = ftp.nlst() for dire in dirlist: #check for satellite directory if(dire.find('noaa') == -1): continue satnum = dire.replace('noaa','') #chege to file directory ftp.cwd('/sem/poes/data/avg/txt/'+str(myTime.year)+'/'+dire) fname = 'poes_n'+satnum+'_'+myTime.strftime("%Y%m%d")+'.txt' print 'poes: RETR '+fname #list to hold the lines lines = [] #get the data try: ftp.retrlines('RETR '+fname,lines.append) except Exception,e: print e print 'error retrieving',fname #convert the ascii lines into a list of poesRec objects #skip first (header) line for line in lines[1:]: cols = line.split() t = dt.datetime(int(cols[0]), int(cols[1]), int(cols[2]), int(cols[3]),int(cols[4])) if(sTime <= t <= eTime): myPoes.append(poesRec(ftpLine=line,satnum=int(satnum),header=lines[0])) #increment myTime myTime += dt.timedelta(days=1) if(len(myPoes) > 0): return myPoes else: return None def mapPoesMongo(sYear,eYear=None): """This function reads poes data from the NOAA NGDC FTP server via anonymous FTP connection and maps it to the mongodb. .. warning:: In general, nobody except the database admins will need to use this function **Args**: * **sYear** (int): the year to begin mapping data * [**eYear**] (int or None): the end year for mapping data. if this is None, eYear will be sYear **Returns**: * Nothing. **Example**: :: gme.sat.mapPoesMongo(2004) written by AJ, 20130131 """ import davitpy.pydarn.sdio.dbUtils as db from davitpy import rcParams import datetime as dt #check inputs assert(isinstance(sYear,int)),'error, sYear must be int' if(eYear == None): eYear=sYear assert(isinstance(eYear,int)),'error, sYear must be None or int' assert(eYear >= sYear), 'error, end year greater than start year' #get data connection mongoData = db.getDataConn(username=rcParams['DBWRITEUSER'],password=rcParams['DBWRITEPASS'],\ dbAddress=rcParams['SDDB'],dbName='gme',collName='poes') #set up all of the indices mongoData.ensure_index('time') mongoData.ensure_index('satnum') mongoData.ensure_index('folat') mongoData.ensure_index('folon') mongoData.ensure_index('ted') mongoData.ensure_index('echar') mongoData.ensure_index('pchar') #read the poes data from the FTP server myTime = dt.datetime(sYear,1,1) while(myTime < dt.datetime(eYear+1,1,1)): #10 day at a time, to not fill up RAM templist = readPoesFtp(myTime,myTime+dt.timedelta(days=10)) if(templist == None): continue for rec in templist: #check if a duplicate record exists qry = mongoData.find({'$and':[{'time':rec.time},{'satnum':rec.satnum}]}) print rec.time, rec.satnum tempRec = rec.toDbDict() cnt = qry.count() #if this is a new record, insert it if(cnt == 0): mongoData.insert(tempRec) #if this is an existing record, update it elif(cnt == 1): print 'foundone!!' dbDict = qry.next() temp = dbDict['_id'] dbDict = tempRec dbDict['_id'] = temp mongoData.save(dbDict) else: print 'strange, there is more than 1 record for',rec.time del templist myTime += dt.timedelta(days=10) def overlayPoesTed( baseMapObj, axisHandle, startTime, endTime = None, coords = 'geo', \ hemi = 1, folat = [45., 90.], satNum = None, param='ted', scMin=-3.,scMax=0.5) : """This function overlays POES TED data onto a map object. **Args**: * **baseMapObj** (`datetime <http://tinyurl.com/bl352yx>`_ or None): the map object you want data to be overlayed on. * **axisHandle** (`datetime <http://tinyurl.com/bl352yx>`_ or None): the Axis Handle used. * **startTime** (`datetime <http://tinyurl.com/bl352yx>`_ or None): the starttime you want data for. If endTime is not given overlays data from satellites with in +/- 45 min of the startTime * [**endTime**] (`datetime <http://tinyurl.com/bl352yx>`_ or None): the latest time you want data for. if this is None, data from satellites with in +/- 45 min of the startTime is overlayed. default = None * [**satnum**] (int): the satellite you want data for. eg 17 for noaa17. if this is None, data for all satellites will be returned. default = None * [**coords**] (str): Coordinates of the map object on which you want data to be overlayed on, 'geo', 'mag', 'mlt'. Default 'geo' * [**hemi**] (list or None): Hemisphere of the map object on which you want data to be overlayed on. Value is 1 for northern hemisphere and -1 for the southern hemisphere.Default 1 [**folat**] (list or None): if this is not None, it must be a 2-element list of numbers, [a,b]. In this case, only data with latitude values in the range [a,b] will be returned. default = None * [**param**] (str): the name of the poes parameter to be plotted. default='ted' **Returns**: POES TED data is overlayed on the map object. If no data is found, None is returned. **Example**: :: import datetime as dt poesList = gme.sat.overlayPoesTed(MapObj, sTime=dt.datetime(2011,3,4,4)) written by Bharat Kunduri, 20130216 """ import utils import matplotlib as mp import datetime import numpy import matplotlib.pyplot as plt import gme.sat.poes as Poes import math import models import matplotlib.cm as cm from scipy import optimize #check all the inputs for validity assert(isinstance(startTime,datetime.datetime)), \ 'error, sTime must be a datetime object' assert(endTime == None or isinstance(endTime,datetime.datetime)), \ 'error, eTime must be either None or a datetime object' var = locals() assert(var['satNum'] == None or (isinstance(var['satNum'],list) )), \ 'error, satNum must None or a list of satellite (integer) numbers' if satNum != None : assert( len(satNum) <= 5 ), \ 'error, there are only 5 POES satellites in operation (atleast when I wrote this code)' assert(var['folat'] == None or (isinstance(var['folat'],list) and \ isinstance(var['folat'][0],(int,float)) and isinstance(var['folat'][1],(int,float)))), \ 'error, folat must None or a list of 2 numbers' # Check the hemisphere and get the appropriate folat folat = [ math.fabs( folat[0] ) * hemi, math.fabs( folat[1] ) * hemi ] # Check if the endTime is given in which case the user wants a specific time interval to search for # If not we'll give him the best available passes for the selected start time... if ( endTime != None ) : timeRange = numpy.array( [ startTime, endTime ] ) else : timeRange = None pltTimeInterval = numpy.array( datetime.timedelta( minutes = 45 ) ) # check if the timeRange is set... if not set the timeRange to +/- pltTimeInterval of the startTime if timeRange == None: timeRange = numpy.array( [ startTime - pltTimeInterval, startTime + pltTimeInterval ] ) # SatNums - currently operational POES satellites are 15, 16, 17, 18, 19 if satNum == None: satNum = [None] # If any particular satellite number is not chosen by user loop through all the available one's satNum = numpy.array( satNum ) # I like numpy arrays better that's why I'm converting the satNum list to a numpy array latPoesAll = [[] for j in range(len(satNum))] lonPoesAll = [[] for j in range(len(satNum))] tedPoesAll = [[] for j in range(len(satNum))] timePoesAll = [[] for j in range(len(satNum))] lenDataAll = [[] for j in range(len(satNum))] goodFlg=False for sN in range(len(satNum)) : if(satNum[sN] != None): currPoesList = Poes.readPoes(timeRange[0], eTime = timeRange[1], satnum = int(satNum[sN]), folat = folat) else: currPoesList = Poes.readPoes(timeRange[0], eTime = timeRange[1], satnum = satNum[sN], folat = folat) # Check if the data is loaded... if currPoesList == None : print 'No data found' continue #return None else: goodFlg=True # Loop through the list and store the data into arrays lenDataAll.append(len(currPoesList)) for l in currPoesList : # Store our data in arrays try: tedPoesAll[sN].append(math.log10(getattr(l,param))) if coords == 'mag' or coords == 'mlt': lat,lon,_ = models.aacgm.aacgmConv(l.folat,l.folon, 0., l.time.year, 0) latPoesAll[sN].append(lat) if coords == 'mag': lonPoesAll[sN].append(lon) else: lonPoesAll[sN].append(models.aacgm.mltFromEpoch(utils.timeUtils.datetimeToEpoch(l.time),lon)*360./24.) else: latPoesAll[sN].append(l.folat) lonPoesAll[sN].append(l.folon) timePoesAll[sN].append(l.time) except Exception,e: print e print 'could not get parameter for time',l.time if(not goodFlg): return None latPoesAll = numpy.array( latPoesAll ) lonPoesAll = numpy.array( lonPoesAll ) tedPoesAll = numpy.array( tedPoesAll ) timePoesAll = numpy.array( timePoesAll ) lenDataAll = numpy.array( lenDataAll ) poesTicks = [ -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5 ] # get the axis of the figure... ax = axisHandle for nn in range( len(satNum) ) : x, y = baseMapObj(lonPoesAll[nn], latPoesAll[nn]) bpltpoes = baseMapObj.scatter(x,y,c=tedPoesAll[nn], vmin=scMin, vmax=scMax, alpha = 0.7, cmap=cm.jet, zorder = 7., edgecolor='none') timeCurr = timePoesAll[nn] for aa in range( len(latPoesAll[nn]) ) : if aa % 10 == 0: str_curr = str(timeCurr[aa].hour)+':'+str(timeCurr[aa].minute) ax.annotate( str_curr, xy =( x[aa], y[aa] ), size = 5, zorder = 6. ) #cbar = plt.colorbar(bpltpoes, ticks = poesTicks, orientation='horizontal') #cbar.ax.set_xticklabels(poesTicks) #cbar.set_label(r"Total Log Energy Flux [ergs cm$^{-2}$ s$^{-1}$]") return bpltpoes def overlayPoesBnd( baseMapObj, axisHandle, startTime, coords = 'geo', hemi = 1, equBnd = True, polBnd = False ) : """This function reads POES TED data with in +/- 45min of the given time, fits the auroral oval boundaries and overlays them on a map object. The poleward boundary is not accurate all the times due to lesser number of satellite passes identifying it. **Args**: * **baseMapObj** (`datetime <http://tinyurl.com/bl352yx>`_ or None): the map object you want data to be overlayed on. * **axisHandle** (`datetime <http://tinyurl.com/bl352yx>`_ or None): the Axis Handle used. * **startTime** (`datetime <http://tinyurl.com/bl352yx>`_ or None): the starttime you want data for. If endTime is not given overlays data from satellites with in +/- 45 min of the startTime * [**coords**] (list or None): Coordinates of the map object on which you want data to be overlayed on. Default 'geo' * [**hemi**] (list or None): Hemisphere of the map object on which you want data to be overlayed on. Value is 1 for northern hemisphere and -1 for the southern hemisphere.Default 1 * [**equBnd**] (list or None): If this is True the equatorward auroral oval boundary fit from the TED data is overlayed on the map object. Default True * [**polBnd**] (list or None): If this is True the poleward auroral oval boundary fit from the TED data is overlayed on the map object. Default False **Returns**: POES TED data is overlayed on the map object. If no data is found, None is returned. **Example**: :: import datetime as dt poesList = gme.sat.overlayPoesTed(MapObj, sTime=dt.datetime(2011,3,4,4)) written by Bharat Kunduri, 20130216 """ import utils import matplotlib as mp import datetime import numpy import matplotlib.pyplot as plt import gme.sat.poes as Poes import math import matplotlib.cm as cm from scipy import optimize import models #check all the inputs for validity assert(isinstance(startTime,datetime.datetime)), \ 'error, sTime must be a datetime object' # Check the hemisphere and get the appropriate folat folat = [ 45. * hemi, 90. * hemi ] # Get the time range we choose +/- 45 minutes.... pltTimeInterval = numpy.array( datetime.timedelta( minutes = 45 ) ) timeRange = numpy.array( [ startTime - pltTimeInterval, startTime + pltTimeInterval ] ) satNum = [ 15, 16, 17, 18, 19 ] # We set the TED cut-off value to -0.75, # From observed cases this appeared to do well... # though fails sometimes especially during geomagnetically quiet times... # However this is version 1.0 and there always is room for improvement equBndCutoffVal = -0.75 # If any particular satellite number is not chosen by user loop through all the available one's satNum = numpy.array( satNum ) # I like numpy arrays better that's why I'm converting the satNum list to a numpy array latPoesAll = [[] for j in range(len(satNum))] lonPoesAll = [[] for j in range(len(satNum))] tedPoesAll = [[] for j in range(len(satNum))] timePoesAll = [[] for j in range(len(satNum))] lenDataAll = [[] for j in range(len(satNum))] for sN in range( len(satNum) ) : currPoesList = Poes.readPoes( timeRange[0], eTime = timeRange[1], satnum = int(satNum[sN]), folat = folat ) # Check if the data is loaded... if currPoesList == None : print 'No data found' continue # Loop through the list and store the data into arrays lenDataAll.append( len( currPoesList ) ) for l in range( lenDataAll[-1] ) : # Store our data in arrays if the TED data value is > than the cutoff value try: x = math.log10(currPoesList[l].ted) except: continue if x > equBndCutoffVal: if coords == 'mag' or coords == 'mlt': lat,lon,_ = models.aacgm.aacgmConv(currPoesList[l].folat,currPoesList[l].folon, 0., currPoesList[l].time.year, 0) latPoesAll[sN].append(lat) if coords == 'mag': lonPoesAll[sN].append(lon) else: lonPoesAll[sN].append(models.aacgm.mltFromEpoch(utils.timeUtils.datetimeToEpoch(currPoesList[l].time),lon)*360./24.) else: latPoesAll[sN].append(currPoesList[l].folat) lonPoesAll[sN].append(currPoesList[l].folon) # latPoesAll[sN].append( currPoesList[l].folat ) # lonPoesAll[sN].append( currPoesList[l].folon ) tedPoesAll[sN].append( math.log10(currPoesList[l].ted) ) timePoesAll[sN].append( currPoesList[l].time ) latPoesAll = numpy.array( latPoesAll ) lonPoesAll = numpy.array( lonPoesAll ) tedPoesAll = numpy.array( tedPoesAll ) timePoesAll = numpy.array( timePoesAll ) lenDataAll = numpy.array( lenDataAll ) # Now to identify the boundaries... # Also need to check if the boundary is equatorward or poleward.. # When satellite is moving from high-lat to low-lat decrease in flux would mean equatorward boundary # When satellite is moving from low-lat to high-lat increase in flux would mean equatorward boundary # that is what we are trying to check here eqBndLats = [] eqBndLons = [] poBndLats = [] poBndLons = [] for n1 in range( len(satNum) ) : currSatLats = latPoesAll[n1] currSatLons = lonPoesAll[n1] currSatTeds = tedPoesAll[n1] testLatArrLtoh = [] testLonArrLtoh = [] testLatArrHtol = [] testLonArrHtol = [] testLatArrLtohP = [] testLonArrLtohP = [] testLatArrHtolP = [] testLonArrHtolP = [] for n2 in range( len(currSatLats)-1 ) : #Check if the satellite is moving form low-lat to high-lat or otherwise if ( math.fabs( currSatLats[n2] ) < math.fabs( currSatLats[n2+1] ) ) : if ( currSatTeds[n2] < currSatTeds[n2+1] ) : testLatArrLtoh.append( currSatLats[n2] ) testLonArrLtoh.append( currSatLons[n2] ) if ( currSatTeds[n2] > currSatTeds[n2+1] ) : testLatArrLtohP.append( currSatLats[n2] ) testLonArrLtohP.append( currSatLons[n2] ) if ( math.fabs( currSatLats[n2] ) > math.fabs( currSatLats[n2+1] ) ) : if ( currSatTeds[n2] > currSatTeds[n2+1] ) : testLatArrHtol.append( currSatLats[n2] ) testLonArrHtol.append( currSatLons[n2] ) if ( currSatTeds[n2] < currSatTeds[n2+1] ) : testLatArrHtolP.append( currSatLats[n2] ) testLonArrHtolP.append( currSatLons[n2] ) # I do this to find the index of the min lat... if ( testLatArrLtoh != [] ) : testLatArrLtoh = numpy.array( testLatArrLtoh ) testLonArrLtoh = numpy.array( testLonArrLtoh ) VarEqLat1 = testLatArrLtoh[ numpy.where( testLatArrLtoh == min(testLatArrLtoh) ) ] VarEqLon1 = testLonArrLtoh[ numpy.where( testLatArrLtoh == min(testLatArrLtoh) ) ] eqBndLats.append( VarEqLat1[0] ) eqBndLons.append( VarEqLon1[0] ) if ( testLatArrHtol != [] ) : testLatArrHtol = numpy.array( testLatArrHtol ) testLonArrHtol = numpy.array( testLonArrHtol ) VarEqLat2 = testLatArrHtol[ numpy.where( testLatArrHtol == min(testLatArrHtol) ) ] VarEqLon2 = testLonArrHtol[ numpy.where( testLatArrHtol == min(testLatArrHtol) ) ] eqBndLats.append( VarEqLat2[0] ) eqBndLons.append( VarEqLon2[0] ) if ( testLatArrLtohP != [] ) : testLatArrLtohP = numpy.array( testLatArrLtohP ) testLonArrLtohP = numpy.array( testLonArrLtohP ) VarEqLatP1 = testLatArrLtohP[ numpy.where( testLatArrLtohP == min(testLatArrLtohP) ) ] VarEqLonP1 = testLonArrLtohP[ numpy.where( testLatArrLtohP == min(testLatArrLtohP) ) ] if VarEqLatP1[0] > 64. : poBndLats.append( VarEqLatP1[0] ) poBndLons.append( VarEqLonP1[0] ) if ( testLatArrHtolP != [] ) : testLatArrHtolP = numpy.array( testLatArrHtolP ) testLonArrHtolP = numpy.array( testLonArrHtolP ) VarEqLatP2 = testLatArrHtolP[ numpy.where( testLatArrHtolP == min(testLatArrHtolP) ) ] VarEqLonP2 = testLonArrHtolP[ numpy.where( testLatArrHtolP == min(testLatArrHtolP) ) ] if VarEqLatP2[0] > 64 : poBndLats.append( VarEqLatP2[0] ) poBndLons.append( VarEqLonP2[0] ) eqBndLats = numpy.array( eqBndLats ) eqBndLons = numpy.array( eqBndLons ) poBndLats = numpy.array( poBndLats ) poBndLons = numpy.array( poBndLons ) #get the axis Handle used ax = axisHandle # Now we do the fitting part... fitfunc = lambda p, x: p[0] + p[1]*numpy.cos(2*math.pi*(x/360.)+p[2]) # Target function errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function # Initial guess for the parameters # Equatorward boundary p0Equ = [ 1., 1., 1.] p1Equ, successEqu = optimize.leastsq(errfunc, p0Equ[:], args=(eqBndLons, eqBndLats)) if polBnd == True : p0Pol = [ 1., 1., 1.] p1Pol, successPol = optimize.leastsq(errfunc, p0Pol[:], args=(poBndLons, poBndLats)) allPlotLons = numpy.linspace(0., 360., 25.) allPlotLons[-1] = 0. eqPlotLats = [] if polBnd == True : poPlotLats = [] for xx in allPlotLons : if equBnd == True : eqPlotLats.append( p1Equ[0] + p1Equ[1]*numpy.cos(2*math.pi*(xx/360.)+p1Equ[2] ) ) if polBnd == True : poPlotLats.append( p1Pol[0] + p1Pol[1]*numpy.cos(2*math.pi*(xx/360.)+p1Pol[2] ) ) xEqu, yEqu = baseMapObj(allPlotLons, eqPlotLats) bpltpoes = baseMapObj.plot( xEqu,yEqu, zorder = 7., color = 'b' ) if polBnd == True : xPol, yPol = baseMapObj(allPlotLons, poPlotLats) bpltpoes = baseMapObj.plot( xPol,yPol, zorder = 7., color = 'r' )
Shirling-VT/davitpy_sam
davitpy/gme/sat/poes.py
Python
gpl-3.0
33,273
/** * This class is generated by jOOQ */ package com.aviafix.db.generated.tables.pojos; import java.io.Serializable; import javax.annotation.Generated; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.5" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class REPAIRPROJECTION implements Serializable { private static final long serialVersionUID = 1577413207; private Integer ERIDREPAIR; private Integer PNUMREPAIR; private Integer ORDNUMREPAIR; public REPAIRPROJECTION() {} public REPAIRPROJECTION(REPAIRPROJECTION value) { this.ERIDREPAIR = value.ERIDREPAIR; this.PNUMREPAIR = value.PNUMREPAIR; this.ORDNUMREPAIR = value.ORDNUMREPAIR; } public REPAIRPROJECTION( Integer ERIDREPAIR, Integer PNUMREPAIR, Integer ORDNUMREPAIR ) { this.ERIDREPAIR = ERIDREPAIR; this.PNUMREPAIR = PNUMREPAIR; this.ORDNUMREPAIR = ORDNUMREPAIR; } public Integer ERIDREPAIR() { return this.ERIDREPAIR; } public void ERIDREPAIR(Integer ERIDREPAIR) { this.ERIDREPAIR = ERIDREPAIR; } public Integer PNUMREPAIR() { return this.PNUMREPAIR; } public void PNUMREPAIR(Integer PNUMREPAIR) { this.PNUMREPAIR = PNUMREPAIR; } public Integer ORDNUMREPAIR() { return this.ORDNUMREPAIR; } public void ORDNUMREPAIR(Integer ORDNUMREPAIR) { this.ORDNUMREPAIR = ORDNUMREPAIR; } @Override public String toString() { StringBuilder sb = new StringBuilder("REPAIRPROJECTION ("); sb.append(ERIDREPAIR); sb.append(", ").append(PNUMREPAIR); sb.append(", ").append(ORDNUMREPAIR); sb.append(")"); return sb.toString(); } }
purple-sky/avia-fixers
app/src/main/java/com/aviafix/db/generated/tables/pojos/REPAIRPROJECTION.java
Java
gpl-3.0
1,908
import { ComponentFixture, TestBed, waitForAsync } from "@angular/core/testing"; import { AttendanceWeekDashboardComponent } from "./attendance-week-dashboard.component"; import { RouterTestingModule } from "@angular/router/testing"; import { ChildPhotoService } from "../../../children/child-photo-service/child-photo.service"; import { AttendanceModule } from "../../attendance.module"; import { AttendanceService } from "../../attendance.service"; describe("AttendanceWeekDashboardComponent", () => { let component: AttendanceWeekDashboardComponent; let fixture: ComponentFixture<AttendanceWeekDashboardComponent>; let mockAttendanceService: jasmine.SpyObj<AttendanceService>; beforeEach( waitForAsync(() => { mockAttendanceService = jasmine.createSpyObj([ "getAllActivityAttendancesForPeriod", ]); mockAttendanceService.getAllActivityAttendancesForPeriod.and.resolveTo( [] ); TestBed.configureTestingModule({ imports: [AttendanceModule, RouterTestingModule.withRoutes([])], providers: [ { provide: ChildPhotoService, useValue: jasmine.createSpyObj(["getImage"]), }, { provide: AttendanceService, useValue: mockAttendanceService }, ], }).compileComponents(); }) ); beforeEach(() => { fixture = TestBed.createComponent(AttendanceWeekDashboardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it("should create", () => { expect(component).toBeTruthy(); }); });
NGO-DB/ndb-core
src/app/child-dev-project/attendance/dashboard-widgets/attendance-week-dashboard/attendance-week-dashboard.component.spec.ts
TypeScript
gpl-3.0
1,569
/*copyright 2010 Simon Graeser*/ /* This file is part of Pina. Pina is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Pina is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Pina. If not, see <http://www.gnu.org/licenses/>. */ #include "Texture.h" #include "../Templates/Ordering.h" #include "../Core/Extra.h" #define THIS Texture namespace PINA_NAMESPACE{ THIS::THIS(XmlElement* h):Element(h){ /* attributes */ createAttribute(attrib_texture,"texture"); createAttribute(attrib_texcoord,"texcoord"); /* children */ buildChildren(Types()); /* data */ } std::string THIS::getName() const { return Name; } void THIS::order(){ children.sort(Ordering<Types>()); } const std::string THIS::Name = "rgb"; THIS::~THIS(){ } }/*PINA_NAMESPACE*/ #undef THIS
kaiserlicious/Pina
FX/Texture.cpp
C++
gpl-3.0
1,234
/* inflate.h -- internal inflate state definition * Copyright (C) 1995-2004 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* WARNING: this file should *not* be used by applications. It is part of the implementation of the compression library and is subject to change. Applications should only use zlib.h. */ /* define NO_GZIP when compiling if you want to disable gzip header and trailer decoding by inflate(). NO_GZIP would be used to avoid linking in the crc code when it is not needed. For shared libraries, gzip decoding should be left enabled. */ #ifndef NO_GZIP # define GUNZIP #endif /* Possible inflate modes between inflate() calls */ typedef enum { HEAD, /* i: waiting for magic header */ FLAGS, /* i: waiting for method and flags (gzip) */ TIME, /* i: waiting for modification time (gzip) */ OS, /* i: waiting for extra flags and operating system (gzip) */ EXLEN, /* i: waiting for extra length (gzip) */ EXTRA, /* i: waiting for extra bytes (gzip) */ NAME, /* i: waiting for end of file name (gzip) */ COMMENT, /* i: waiting for end of comment (gzip) */ HCRC, /* i: waiting for header crc (gzip) */ DICTID, /* i: waiting for dictionary check value */ DICT, /* waiting for inflateSetDictionary() call */ TYPE, /* i: waiting for type bits, including last-flag bit */ TYPEDO, /* i: same, but skip check to exit inflate on new block */ STORED, /* i: waiting for stored size (length and complement) */ COPY, /* i/o: waiting for input or output to copy stored block */ TABLE, /* i: waiting for dynamic block table lengths */ LENLENS, /* i: waiting for code length code lengths */ CODELENS, /* i: waiting for length/lit and distance code lengths */ LEN, /* i: waiting for length/lit code */ LENEXT, /* i: waiting for length extra bits */ DIST, /* i: waiting for distance code */ DISTEXT, /* i: waiting for distance extra bits */ MATCH, /* o: waiting for output space to copy string */ LIT, /* o: waiting for output space to write literal */ CHECK, /* i: waiting for 32-bit check value */ LENGTH, /* i: waiting for 32-bit length (gzip) */ DONE, /* finished check, done -- remain here until reset */ BAD, /* got a data error -- remain here until reset */ MEM, /* got an inflate() memory error -- remain here until reset */ SYNC /* looking for synchronization bytes to restart inflate() */ } inflate_mode; /* State transitions between above modes - (most modes can go to the BAD or MEM mode -- not shown for clarity) Process header: HEAD -> (gzip) or (zlib) (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME NAME -> COMMENT -> HCRC -> TYPE (zlib) -> DICTID or TYPE DICTID -> DICT -> TYPE Read deflate blocks: TYPE -> STORED or TABLE or LEN or CHECK STORED -> COPY -> TYPE TABLE -> LENLENS -> CODELENS -> LEN Read deflate codes: LEN -> LENEXT or LIT or TYPE LENEXT -> DIST -> DISTEXT -> MATCH -> LEN LIT -> LEN Process trailer: CHECK -> LENGTH -> DONE */ /* state maintained between inflate() calls. Approximately 7K bytes. */ struct inflate_state { inflate_mode mode; /* current inflate mode */ int last; /* true if processing last block */ int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ int havedict; /* true if dictionary provided */ int flags; /* gzip header method and flags (0 if zlib) */ unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ unsigned long check; /* protected copy of check value */ unsigned long total; /* protected copy of output count */ gz_headerp head; /* where to save gzip header information */ /* sliding window */ unsigned wbits; /* log base 2 of requested window size */ unsigned wsize; /* window size or zero if not using window */ unsigned whave; /* valid bytes in the window */ unsigned write; /* window write index */ unsigned char FAR *window; /* allocated sliding window, if needed */ /* bit accumulator */ unsigned long hold; /* input bit accumulator */ unsigned bits; /* number of bits in "in" */ /* for string and stored block copying */ unsigned length; /* literal or length of data to copy */ unsigned offset; /* distance back to copy string from */ /* for table and code decoding */ unsigned extra; /* extra bits needed */ /* fixed and dynamic code tables */ code const FAR *lencode; /* starting table for length/literal codes */ code const FAR *distcode; /* starting table for distance codes */ unsigned lenbits; /* index bits for lencode */ unsigned distbits; /* index bits for distcode */ /* dynamic table building */ unsigned ncode; /* number of code length code lengths */ unsigned nlen; /* number of length code lengths */ unsigned ndist; /* number of distance code lengths */ unsigned have; /* number of code lengths in lens[] */ code FAR *next; /* next available space in codes[] */ unsigned short lens[320]; /* temporary storage for code lengths */ unsigned short work[288]; /* work area for code table building */ code codes[ENOUGH]; /* space for code tables */ };
MartijnB/ETGoldy
src/zlib/inflate.h
C
gpl-3.0
5,691
/* Return the next element of a path. Copyright (C) 1992, 2010 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Written by David MacKenzie <djm@gnu.org>, inspired by John P. Rouillard <rouilj@cs.umb.edu>. */ #ifndef INC_NEXTELEM_H #define INC_NEXTELEM_H 1 char *next_element (const char *path, int curdir_ok); #endif
Distrotech/findutils
lib/nextelem.h
C
gpl-3.0
959
package com.github.xzzpig.pigutils.thread; public class PigThreadExecptionEvent extends PigThreadEvent { private Exception e; public PigThreadExecptionEvent(PigThread t, Exception e) { super(t); this.e = e; } public Exception getException() { return e; } }
xzzpig/PigUtils
Thread/src/main/java/com/github/xzzpig/pigutils/thread/PigThreadExecptionEvent.java
Java
gpl-3.0
272
<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ namespace Nette\Database\Table; use Nette; use Nette\Database\Context; use Nette\Database\IConventions; use Nette\Database\IStructure; use Nette\Database\ISupplementalDriver; use Nette\Database\SqlLiteral; /** * Builds SQL query. * SqlBuilder is based on great library NotORM http://www.notorm.com written by Jakub Vrana. */ class SqlBuilder { use Nette\SmartObject; /** @var string */ protected $tableName; /** @var IConventions */ protected $conventions; /** @var string delimited table name */ protected $delimitedTable; /** @var array of column to select */ protected $select = []; /** @var array of where conditions */ protected $where = []; /** @var array of array of join conditions */ protected $joinCondition = []; /** @var array of where conditions for caching */ protected $conditions = []; /** @var array of parameters passed to where conditions */ protected $parameters = [ 'select' => [], 'joinCondition' => [], 'where' => [], 'group' => [], 'having' => [], 'order' => [], ]; /** @var array or columns to order by */ protected $order = []; /** @var int number of rows to fetch */ protected $limit; /** @var int first row to fetch */ protected $offset; /** @var string columns to grouping */ protected $group = ''; /** @var string grouping condition */ protected $having = ''; /** @var array of reserved table names associated with chain */ protected $reservedTableNames = []; /** @var array of table aliases */ protected $aliases = []; /** @var string currently parsing alias for joins */ protected $currentAlias; /** @var ISupplementalDriver */ private $driver; /** @var IStructure */ private $structure; /** @var array */ private $cacheTableList; /** @var array of expanding joins */ private $expandingJoins = []; public function __construct($tableName, Context $context) { $this->tableName = $tableName; $this->driver = $context->getConnection()->getSupplementalDriver(); $this->conventions = $context->getConventions(); $this->structure = $context->getStructure(); $tableNameParts = explode('.', $tableName); $this->delimitedTable = implode('.', array_map([$this->driver, 'delimite'], $tableNameParts)); $this->checkUniqueTableName(end($tableNameParts), $tableName); } /** * @return string */ public function getTableName() { return $this->tableName; } /** * @param string */ public function buildInsertQuery() { return "INSERT INTO {$this->delimitedTable}"; } /** * @param string */ public function buildUpdateQuery() { $query = "UPDATE {$this->delimitedTable} SET ?set" . $this->tryDelimite($this->buildConditions()); if ($this->limit !== null || $this->offset) { $this->driver->applyLimit($query, $this->limit, $this->offset); } return $query; } /** * @param string */ public function buildDeleteQuery() { $query = "DELETE FROM {$this->delimitedTable}" . $this->tryDelimite($this->buildConditions()); if ($this->limit !== null || $this->offset) { $this->driver->applyLimit($query, $this->limit, $this->offset); } return $query; } /** * Returns select query hash for caching. * @return string */ public function getSelectQueryHash(array $columns = null) { $parts = [ 'delimitedTable' => $this->delimitedTable, 'queryCondition' => $this->buildConditions(), 'queryEnd' => $this->buildQueryEnd(), $this->aliases, $this->limit, $this->offset, ]; if ($this->select) { $parts[] = $this->select; } elseif ($columns) { $parts[] = [$this->delimitedTable, $columns]; } elseif ($this->group && !$this->driver->isSupported(ISupplementalDriver::SUPPORT_SELECT_UNGROUPED_COLUMNS)) { $parts[] = [$this->group]; } else { $parts[] = "{$this->delimitedTable}.*"; } return $this->getConditionHash(json_encode($parts), [ $this->parameters['select'], $this->parameters['joinCondition'], $this->parameters['where'], $this->parameters['group'], $this->parameters['having'], $this->parameters['order'], ]); } /** * Returns SQL query. * @param string[] list of columns * @return string */ public function buildSelectQuery(array $columns = null) { if (!$this->order && ($this->limit !== null || $this->offset)) { $this->order = array_map( function ($col) { return "$this->tableName.$col"; }, (array) $this->conventions->getPrimary($this->tableName) ); } $queryJoinConditions = $this->buildJoinConditions(); $queryCondition = $this->buildConditions(); $queryEnd = $this->buildQueryEnd(); $joins = []; $finalJoinConditions = $this->parseJoinConditions($joins, $queryJoinConditions); $this->parseJoins($joins, $queryCondition); $this->parseJoins($joins, $queryEnd); if ($this->select) { $querySelect = $this->buildSelect($this->select); $this->parseJoins($joins, $querySelect); } elseif ($columns) { $prefix = $joins ? "{$this->delimitedTable}." : ''; $cols = []; foreach ($columns as $col) { $cols[] = $prefix . $col; } $querySelect = $this->buildSelect($cols); } elseif ($this->group && !$this->driver->isSupported(ISupplementalDriver::SUPPORT_SELECT_UNGROUPED_COLUMNS)) { $querySelect = $this->buildSelect([$this->group]); $this->parseJoins($joins, $querySelect); } else { $prefix = $joins ? "{$this->delimitedTable}." : ''; $querySelect = $this->buildSelect([$prefix . '*']); } $queryJoins = $this->buildQueryJoins($joins, $finalJoinConditions); $query = "{$querySelect} FROM {$this->delimitedTable}{$queryJoins}{$queryCondition}{$queryEnd}"; $this->driver->applyLimit($query, $this->limit, $this->offset); return $this->tryDelimite($query); } /** * @return array */ public function getParameters() { if (!isset($this->parameters['joinConditionSorted'])) { $this->buildSelectQuery(); } return array_merge( $this->parameters['select'], $this->parameters['joinConditionSorted'] ? call_user_func_array('array_merge', $this->parameters['joinConditionSorted']) : [], $this->parameters['where'], $this->parameters['group'], $this->parameters['having'], $this->parameters['order'] ); } public function importConditions(SqlBuilder $builder) { $this->where = $builder->where; $this->joinCondition = $builder->joinCondition; $this->parameters['where'] = $builder->parameters['where']; $this->parameters['joinCondition'] = $builder->parameters['joinCondition']; $this->conditions = $builder->conditions; $this->aliases = $builder->aliases; $this->reservedTableNames = $builder->reservedTableNames; } /********************* SQL selectors ****************d*g**/ public function addSelect($columns, ...$params) { if (is_array($columns)) { throw new Nette\InvalidArgumentException('Select column must be a string.'); } $this->select[] = $columns; $this->parameters['select'] = array_merge($this->parameters['select'], $params); } /** * @return array */ public function getSelect() { return $this->select; } /** * @return bool */ public function addWhere($condition, ...$params) { return $this->addCondition($condition, $params, $this->where, $this->parameters['where']); } /** * @return array */ public function addJoinCondition($tableChain, $condition, ...$params) { $this->parameters['joinConditionSorted'] = null; if (!isset($this->joinCondition[$tableChain])) { $this->joinCondition[$tableChain] = $this->parameters['joinCondition'][$tableChain] = []; } return $this->addCondition($condition, $params, $this->joinCondition[$tableChain], $this->parameters['joinCondition'][$tableChain]); } /** * @return bool */ protected function addCondition($condition, array $params, array &$conditions, array &$conditionsParameters) { if (is_array($condition) && !empty($params[0]) && is_array($params[0])) { return $this->addConditionComposition($condition, $params[0], $conditions, $conditionsParameters); } $hash = $this->getConditionHash($condition, $params); if (isset($this->conditions[$hash])) { return false; } $this->conditions[$hash] = $condition; $placeholderCount = substr_count($condition, '?'); if ($placeholderCount > 1 && count($params) === 1 && is_array($params[0])) { $params = $params[0]; } $condition = trim($condition); if ($placeholderCount === 0 && count($params) === 1) { $condition .= ' ?'; } elseif ($placeholderCount !== count($params)) { throw new Nette\InvalidArgumentException('Argument count does not match placeholder count.'); } $replace = null; $placeholderNum = 0; foreach ($params as $arg) { preg_match('#(?:.*?\?.*?){' . $placeholderNum . '}(((?:&|\||^|~|\+|-|\*|/|%|\(|,|<|>|=|(?<=\W|^)(?:REGEXP|ALL|AND|ANY|BETWEEN|EXISTS|IN|[IR]?LIKE|OR|NOT|SOME|INTERVAL))\s*)?(?:\(\?\)|\?))#s', $condition, $match, PREG_OFFSET_CAPTURE); $hasOperator = ($match[1][0] === '?' && $match[1][1] === 0) ? true : !empty($match[2][0]); if ($arg === null) { $replace = 'IS NULL'; if ($hasOperator) { if (trim($match[2][0]) === 'NOT') { $replace = 'IS NOT NULL'; } else { throw new Nette\InvalidArgumentException('Column operator does not accept null argument.'); } } } elseif (is_array($arg) || $arg instanceof Selection) { if ($hasOperator) { if (trim($match[2][0]) === 'NOT') { $match[2][0] = rtrim($match[2][0]) . ' IN '; } elseif (trim($match[2][0]) !== 'IN') { throw new Nette\InvalidArgumentException('Column operator does not accept array argument.'); } } else { $match[2][0] = 'IN '; } if ($arg instanceof Selection) { $clone = clone $arg; if (!$clone->getSqlBuilder()->select) { try { $clone->select($clone->getPrimary()); } catch (\LogicException $e) { throw new Nette\InvalidArgumentException('Selection argument must have defined a select column.', 0, $e); } } if ($this->driver->isSupported(ISupplementalDriver::SUPPORT_SUBSELECT)) { $arg = null; $replace = $match[2][0] . '(' . $clone->getSql() . ')'; $conditionsParameters = array_merge($conditionsParameters, $clone->getSqlBuilder()->getParameters()); } else { $arg = []; foreach ($clone as $row) { $arg[] = array_values(iterator_to_array($row)); } } } if ($arg !== null) { if (!$arg) { $hasBrackets = strpos($condition, '(') !== false; $hasOperators = preg_match('#AND|OR#', $condition); $hasNot = strpos($condition, 'NOT') !== false; $hasPrefixNot = strpos($match[2][0], 'NOT') !== false; if (!$hasBrackets && ($hasOperators || ($hasNot && !$hasPrefixNot))) { throw new Nette\InvalidArgumentException('Possible SQL query corruption. Add parentheses around operators.'); } if ($hasPrefixNot) { $replace = 'IS NULL OR TRUE'; } else { $replace = 'IS NULL AND FALSE'; } $arg = null; } else { $replace = $match[2][0] . '(?)'; $conditionsParameters[] = $arg; } } } elseif ($arg instanceof SqlLiteral) { $conditionsParameters[] = $arg; } else { if (!$hasOperator) { $replace = '= ?'; } $conditionsParameters[] = $arg; } if ($replace) { $condition = substr_replace($condition, $replace, $match[1][1], strlen($match[1][0])); $replace = null; } if ($arg !== null) { $placeholderNum++; } } $conditions[] = $condition; return true; } /** * @return array */ public function getConditions() { return array_values($this->conditions); } /** * Adds alias. * @param string * @param string * @return void */ public function addAlias($chain, $alias) { if (isset($chain[0]) && $chain[0] !== '.' && $chain[0] !== ':') { $chain = '.' . $chain; // unified chain format } $this->checkUniqueTableName($alias, $chain); $this->aliases[$alias] = $chain; } /** * @param string * @param string * @return void */ protected function checkUniqueTableName($tableName, $chain) { if (isset($this->aliases[$tableName]) && ($chain === '.' . $tableName)) { $chain = $this->aliases[$tableName]; } if (isset($this->reservedTableNames[$tableName])) { if ($this->reservedTableNames[$tableName] === $chain) { return; } throw new Nette\InvalidArgumentException("Table alias '$tableName' from chain '$chain' is already in use by chain '{$this->reservedTableNames[$tableName]}'. Please add/change alias for one of them."); } $this->reservedTableNames[$tableName] = $chain; } public function addOrder($columns, ...$params) { $this->order[] = $columns; $this->parameters['order'] = array_merge($this->parameters['order'], $params); } public function setOrder(array $columns, array $parameters) { $this->order = $columns; $this->parameters['order'] = $parameters; } /** * @return array */ public function getOrder() { return $this->order; } /** * @param int|null * @param int|null * @return void */ public function setLimit($limit, $offset) { $this->limit = $limit; $this->offset = $offset; } /** * @return int|null */ public function getLimit() { return $this->limit; } /** * @return int|null */ public function getOffset() { return $this->offset; } public function setGroup($columns, ...$params) { $this->group = $columns; $this->parameters['group'] = $params; } /** * @return string */ public function getGroup() { return $this->group; } public function setHaving($having, ...$params) { $this->having = $having; $this->parameters['having'] = $params; } /** * @return string */ public function getHaving() { return $this->having; } /********************* SQL building ****************d*g**/ /** * @return string */ protected function buildSelect(array $columns) { return 'SELECT ' . implode(', ', $columns); } /** * @return array */ protected function parseJoinConditions(&$joins, $joinConditions) { $tableJoins = $leftJoinDependency = $finalJoinConditions = []; foreach ($joinConditions as $tableChain => &$joinCondition) { $fooQuery = $tableChain . '.foo'; $requiredJoins = []; $this->parseJoins($requiredJoins, $fooQuery); $tableAlias = substr($fooQuery, 0, -4); $tableJoins[$tableAlias] = $requiredJoins; $leftJoinDependency[$tableAlias] = []; $finalJoinConditions[$tableAlias] = preg_replace_callback($this->getColumnChainsRegxp(), function ($match) use ($tableAlias, &$tableJoins, &$leftJoinDependency) { $requiredJoins = []; $query = $this->parseJoinsCb($requiredJoins, $match); $queryParts = explode('.', $query); $tableJoins[$queryParts[0]] = $requiredJoins; if ($queryParts[0] !== $tableAlias) { foreach (array_keys($requiredJoins) as $requiredTable) { $leftJoinDependency[$tableAlias][$requiredTable] = $requiredTable; } } return $query; }, $joinCondition); } $this->parameters['joinConditionSorted'] = []; if (count($joinConditions)) { while (reset($tableJoins)) { $this->getSortedJoins(key($tableJoins), $leftJoinDependency, $tableJoins, $joins); } } return $finalJoinConditions; } protected function getSortedJoins($table, &$leftJoinDependency, &$tableJoins, &$finalJoins) { if (isset($this->expandingJoins[$table])) { $path = implode("' => '", array_map(function ($value) { return $this->reservedTableNames[$value]; }, array_merge(array_keys($this->expandingJoins), [$table]))); throw new Nette\InvalidArgumentException("Circular reference detected at left join conditions (tables '$path')."); } if (isset($tableJoins[$table])) { $this->expandingJoins[$table] = true; if (isset($leftJoinDependency[$table])) { foreach ($leftJoinDependency[$table] as $requiredTable) { if ($requiredTable === $table) { continue; } $this->getSortedJoins($requiredTable, $leftJoinDependency, $tableJoins, $finalJoins); } } if ($tableJoins[$table]) { foreach ($tableJoins[$table] as $requiredTable => $tmp) { if ($requiredTable === $table) { continue; } $this->getSortedJoins($requiredTable, $leftJoinDependency, $tableJoins, $finalJoins); } } $finalJoins += $tableJoins[$table]; $key = isset($this->aliases[$table]) ? $table : $this->reservedTableNames[$table]; $this->parameters['joinConditionSorted'] += isset($this->parameters['joinCondition'][$key]) ? [$table => $this->parameters['joinCondition'][$key]] : []; unset($tableJoins[$table], $this->expandingJoins[$table]); } } protected function parseJoins(&$joins, &$query) { $query = preg_replace_callback($this->getColumnChainsRegxp(), function ($match) use (&$joins) { return $this->parseJoinsCb($joins, $match); }, $query); } /** * @return string */ private function getColumnChainsRegxp() { return '~ (?(DEFINE) (?P<word> [\w_]*[a-z][\w_]* ) (?P<del> [.:] ) (?P<node> (?&del)? (?&word) (\((?&word)\))? ) ) (?P<chain> (?!\.) (?&node)*) \. (?P<column> (?&word) | \* ) ~xi'; } /** * @return string */ public function parseJoinsCb(&$joins, $match) { $chain = $match['chain']; if (!empty($chain[0]) && ($chain[0] !== '.' && $chain[0] !== ':')) { $chain = '.' . $chain; // unified chain format } preg_match_all('~ (?(DEFINE) (?P<word> [\w_]*[a-z][\w_]* ) ) (?P<del> [.:])?(?P<key> (?&word))(\((?P<throughColumn> (?&word))\))? ~xi', $chain, $keyMatches, PREG_SET_ORDER); $parent = $this->tableName; $parentAlias = preg_replace('#^(.*\.)?(.*)$#', '$2', $this->tableName); // join schema keyMatch and table keyMatch to schema.table keyMatch if ($this->driver->isSupported(ISupplementalDriver::SUPPORT_SCHEMA) && count($keyMatches) > 1) { $tables = $this->getCachedTableList(); if (!isset($tables[$keyMatches[0]['key']]) && isset($tables[$keyMatches[0]['key'] . '.' . $keyMatches[1]['key']])) { $keyMatch = array_shift($keyMatches); $keyMatches[0]['key'] = $keyMatch['key'] . '.' . $keyMatches[0]['key']; $keyMatches[0]['del'] = $keyMatch['del']; } } // do not make a join when referencing to the current table column - inner conditions // check it only when not making backjoin on itself - outer condition if ($keyMatches[0]['del'] === '.') { if (count($keyMatches) > 1 && ($parent === $keyMatches[0]['key'] || $parentAlias === $keyMatches[0]['key'])) { throw new Nette\InvalidArgumentException("Do not prefix table chain with origin table name '{$keyMatches[0]['key']}'. If you want to make self reference, please add alias."); } if ($parent === $keyMatches[0]['key']) { return "{$parent}.{$match['column']}"; } elseif ($parentAlias === $keyMatches[0]['key']) { return "{$parentAlias}.{$match['column']}"; } } $tableChain = null; foreach ($keyMatches as $index => $keyMatch) { $isLast = !isset($keyMatches[$index + 1]); if (!$index && isset($this->aliases[$keyMatch['key']])) { if ($keyMatch['del'] === ':') { throw new Nette\InvalidArgumentException("You are using has many syntax with alias (':{$keyMatch['key']}'). You have to move it to alias definition."); } else { $previousAlias = $this->currentAlias; $this->currentAlias = $keyMatch['key']; $requiredJoins = []; $query = $this->aliases[$keyMatch['key']] . '.foo'; $this->parseJoins($requiredJoins, $query); $aliasJoin = array_pop($requiredJoins); $joins += $requiredJoins; list($table, , $parentAlias, $column, $primary) = $aliasJoin; $this->currentAlias = $previousAlias; } } elseif ($keyMatch['del'] === ':') { if (isset($keyMatch['throughColumn'])) { $table = $keyMatch['key']; $belongsTo = $this->conventions->getBelongsToReference($table, $keyMatch['throughColumn']); if (!$belongsTo) { throw new Nette\InvalidArgumentException("No reference found for \${$parent}->{$keyMatch['key']}."); } list(, $primary) = $belongsTo; } else { $hasMany = $this->conventions->getHasManyReference($parent, $keyMatch['key']); if (!$hasMany) { throw new Nette\InvalidArgumentException("No reference found for \${$parent}->related({$keyMatch['key']})."); } list($table, $primary) = $hasMany; } $column = $this->conventions->getPrimary($parent); } else { $belongsTo = $this->conventions->getBelongsToReference($parent, $keyMatch['key']); if (!$belongsTo) { throw new Nette\InvalidArgumentException("No reference found for \${$parent}->{$keyMatch['key']}."); } list($table, $column) = $belongsTo; $primary = $this->conventions->getPrimary($table); } if ($this->currentAlias && $isLast) { $tableAlias = $this->currentAlias; } elseif ($parent === $table) { $tableAlias = $parentAlias . '_ref'; } elseif ($keyMatch['key']) { $tableAlias = $keyMatch['key']; } else { $tableAlias = preg_replace('#^(.*\.)?(.*)$#', '$2', $table); } $tableChain .= $keyMatch[0]; if (!$isLast || !$this->currentAlias) { $this->checkUniqueTableName($tableAlias, $tableChain); } $joins[$tableAlias] = [$table, $tableAlias, $parentAlias, $column, $primary]; $parent = $table; $parentAlias = $tableAlias; } return $tableAlias . ".{$match['column']}"; } /** * @return string */ protected function buildQueryJoins(array $joins, array $leftJoinConditions = []) { $return = ''; foreach ($joins as list($joinTable, $joinAlias, $table, $tableColumn, $joinColumn)) { $return .= " LEFT JOIN {$joinTable}" . ($joinTable !== $joinAlias ? " {$joinAlias}" : '') . " ON {$table}.{$tableColumn} = {$joinAlias}.{$joinColumn}" . (isset($leftJoinConditions[$joinAlias]) ? " {$leftJoinConditions[$joinAlias]}" : ''); } return $return; } /** * @return array */ protected function buildJoinConditions() { $conditions = []; foreach ($this->joinCondition as $tableChain => $joinConditions) { $conditions[$tableChain] = 'AND (' . implode(') AND (', $joinConditions) . ')'; } return $conditions; } /** * @return string */ protected function buildConditions() { return $this->where ? ' WHERE (' . implode(') AND (', $this->where) . ')' : ''; } /** * @return string */ protected function buildQueryEnd() { $return = ''; if ($this->group) { $return .= ' GROUP BY ' . $this->group; } if ($this->having) { $return .= ' HAVING ' . $this->having; } if ($this->order) { $return .= ' ORDER BY ' . implode(', ', $this->order); } return $return; } /** * @return string */ protected function tryDelimite($s) { return preg_replace_callback('#(?<=[^\w`"\[?]|^)[a-z_][a-z0-9_]*(?=[^\w`"(\]]|\z)#i', function ($m) { return strtoupper($m[0]) === $m[0] ? $m[0] : $this->driver->delimite($m[0]); }, $s); } /** * @return bool */ protected function addConditionComposition(array $columns, array $parameters, array &$conditions, array &$conditionsParameters) { if ($this->driver->isSupported(ISupplementalDriver::SUPPORT_MULTI_COLUMN_AS_OR_COND)) { $conditionFragment = '(' . implode(' = ? AND ', $columns) . ' = ?) OR '; $condition = substr(str_repeat($conditionFragment, count($parameters)), 0, -4); return $this->addCondition($condition, [Nette\Utils\Arrays::flatten($parameters)], $conditions, $conditionsParameters); } else { return $this->addCondition('(' . implode(', ', $columns) . ') IN', [$parameters], $conditions, $conditionsParameters); } } /** * @return string */ private function getConditionHash($condition, array $parameters) { foreach ($parameters as $key => &$parameter) { if ($parameter instanceof Selection) { $parameter = $this->getConditionHash($parameter->getSql(), $parameter->getSqlBuilder()->getParameters()); } elseif ($parameter instanceof SqlLiteral) { $parameter = $this->getConditionHash($parameter->__toString(), $parameter->getParameters()); } elseif (is_object($parameter) && method_exists($parameter, '__toString')) { $parameter = $parameter->__toString(); } elseif (is_array($parameter) || $parameter instanceof \ArrayAccess) { $parameter = $this->getConditionHash($key, $parameter); } } return md5($condition . json_encode($parameters)); } /** * @return array */ private function getCachedTableList() { if (!$this->cacheTableList) { $this->cacheTableList = array_flip(array_map(function ($pair) { return isset($pair['fullName']) ? $pair['fullName'] : $pair['name']; }, $this->structure->getTables())); } return $this->cacheTableList; } }
Kajry/Kajry-PersonalWeb
vendor/nette/database/src/Database/Table/SqlBuilder.php
PHP
gpl-3.0
24,807
# filename-regex [![NPM version](https://img.shields.io/npm/v/filename-regex.svg?style=flat)](https://www.npmjs.com/package/filename-regex) [![NPM monthly downloads](https://img.shields.io/npm/dm/filename-regex.svg?style=flat)](https://npmjs.org/package/filename-regex) [![NPM total downloads](https://img.shields.io/npm/dt/filename-regex.svg?style=flat)](https://npmjs.org/package/filename-regex) [![Linux Build Status](https://img.shields.io/travis/regexhq/filename-regex.svg?style=flat&label=Travis)](https://travis-ci.org/regexhq/filename-regex) > Regular expression for matching file names, with or without extension. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save filename-regex ``` ## Usage ```js var regex = require('filename-regex'); 'a/b/c/d.min.js'.match(regex()); //=> match[0] = 'd.min.js' 'a/b/c/.dotfile'.match(regex()); //=> match[0] = '.dotfile' ``` ## About ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.3, on April 28, 2017._
tohshige/test
used12_1801_bak/node_modules/filename-regex/README.md
Markdown
gpl-3.0
2,131
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: mavProxyLink.proto #ifndef PROTOBUF_mavProxyLink_2eproto__INCLUDED #define PROTOBUF_mavProxyLink_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 3004000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) namespace mav { class Aircraft; class AircraftDefaultTypeInternal; extern AircraftDefaultTypeInternal _Aircraft_default_instance_; class AircraftLink; class AircraftLinkDefaultTypeInternal; extern AircraftLinkDefaultTypeInternal _AircraftLink_default_instance_; class Waypoint; class WaypointDefaultTypeInternal; extern WaypointDefaultTypeInternal _Waypoint_default_instance_; class Waypoints; class WaypointsDefaultTypeInternal; extern WaypointsDefaultTypeInternal _Waypoints_default_instance_; } // namespace mav namespace mav { namespace protobuf_mavProxyLink_2eproto { // Internal implementation detail -- do not call these. struct TableStruct { static const ::google::protobuf::internal::ParseTableField entries[]; static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; static const ::google::protobuf::internal::ParseTable schema[]; static const ::google::protobuf::uint32 offsets[]; static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static void InitDefaultsImpl(); }; void AddDescriptors(); void InitDefaults(); } // namespace protobuf_mavProxyLink_2eproto // =================================================================== class Aircraft : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:mav.Aircraft) */ { public: Aircraft(); virtual ~Aircraft(); Aircraft(const Aircraft& from); inline Aircraft& operator=(const Aircraft& from) { CopyFrom(from); return *this; } #if LANG_CXX11 Aircraft(Aircraft&& from) noexcept : Aircraft() { *this = ::std::move(from); } inline Aircraft& operator=(Aircraft&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } static const ::google::protobuf::Descriptor* descriptor(); static const Aircraft& default_instance(); static inline const Aircraft* internal_default_instance() { return reinterpret_cast<const Aircraft*>( &_Aircraft_default_instance_); } static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = 0; void Swap(Aircraft* other); friend void swap(Aircraft& a, Aircraft& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline Aircraft* New() const PROTOBUF_FINAL { return New(NULL); } Aircraft* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL; void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void CopyFrom(const Aircraft& from); void MergeFrom(const Aircraft& from); void Clear() PROTOBUF_FINAL; bool IsInitialized() const PROTOBUF_FINAL; size_t ByteSizeLong() const PROTOBUF_FINAL; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const PROTOBUF_FINAL; void InternalSwap(Aircraft* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // required double lat = 1; bool has_lat() const; void clear_lat(); static const int kLatFieldNumber = 1; double lat() const; void set_lat(double value); // required double lon = 2; bool has_lon() const; void clear_lon(); static const int kLonFieldNumber = 2; double lon() const; void set_lon(double value); // required double bearing = 3; bool has_bearing() const; void clear_bearing(); static const int kBearingFieldNumber = 3; double bearing() const; void set_bearing(double value); // required double speed = 4; bool has_speed() const; void clear_speed(); static const int kSpeedFieldNumber = 4; double speed() const; void set_speed(double value); // required double altitude = 5; bool has_altitude() const; void clear_altitude(); static const int kAltitudeFieldNumber = 5; double altitude() const; void set_altitude(double value); // required double wind_speed = 6; bool has_wind_speed() const; void clear_wind_speed(); static const int kWindSpeedFieldNumber = 6; double wind_speed() const; void set_wind_speed(double value); // required double wind_direction = 7; bool has_wind_direction() const; void clear_wind_direction(); static const int kWindDirectionFieldNumber = 7; double wind_direction() const; void set_wind_direction(double value); // required double motor_current = 8; bool has_motor_current() const; void clear_motor_current(); static const int kMotorCurrentFieldNumber = 8; double motor_current() const; void set_motor_current(double value); // required double motor_throttle = 9; bool has_motor_throttle() const; void clear_motor_throttle(); static const int kMotorThrottleFieldNumber = 9; double motor_throttle() const; void set_motor_throttle(double value); // @@protoc_insertion_point(class_scope:mav.Aircraft) private: void set_has_lat(); void clear_has_lat(); void set_has_lon(); void clear_has_lon(); void set_has_bearing(); void clear_has_bearing(); void set_has_speed(); void clear_has_speed(); void set_has_altitude(); void clear_has_altitude(); void set_has_wind_speed(); void clear_has_wind_speed(); void set_has_wind_direction(); void clear_has_wind_direction(); void set_has_motor_current(); void clear_has_motor_current(); void set_has_motor_throttle(); void clear_has_motor_throttle(); // helper for ByteSizeLong() size_t RequiredFieldsByteSizeFallback() const; ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; mutable int _cached_size_; double lat_; double lon_; double bearing_; double speed_; double altitude_; double wind_speed_; double wind_direction_; double motor_current_; double motor_throttle_; friend struct protobuf_mavProxyLink_2eproto::TableStruct; }; // ------------------------------------------------------------------- class Waypoints : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:mav.Waypoints) */ { public: Waypoints(); virtual ~Waypoints(); Waypoints(const Waypoints& from); inline Waypoints& operator=(const Waypoints& from) { CopyFrom(from); return *this; } #if LANG_CXX11 Waypoints(Waypoints&& from) noexcept : Waypoints() { *this = ::std::move(from); } inline Waypoints& operator=(Waypoints&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } static const ::google::protobuf::Descriptor* descriptor(); static const Waypoints& default_instance(); static inline const Waypoints* internal_default_instance() { return reinterpret_cast<const Waypoints*>( &_Waypoints_default_instance_); } static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = 1; void Swap(Waypoints* other); friend void swap(Waypoints& a, Waypoints& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline Waypoints* New() const PROTOBUF_FINAL { return New(NULL); } Waypoints* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL; void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void CopyFrom(const Waypoints& from); void MergeFrom(const Waypoints& from); void Clear() PROTOBUF_FINAL; bool IsInitialized() const PROTOBUF_FINAL; size_t ByteSizeLong() const PROTOBUF_FINAL; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const PROTOBUF_FINAL; void InternalSwap(Waypoints* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated .mav.Waypoint waypoint = 1; int waypoint_size() const; void clear_waypoint(); static const int kWaypointFieldNumber = 1; const ::mav::Waypoint& waypoint(int index) const; ::mav::Waypoint* mutable_waypoint(int index); ::mav::Waypoint* add_waypoint(); ::google::protobuf::RepeatedPtrField< ::mav::Waypoint >* mutable_waypoint(); const ::google::protobuf::RepeatedPtrField< ::mav::Waypoint >& waypoint() const; // @@protoc_insertion_point(class_scope:mav.Waypoints) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; mutable int _cached_size_; ::google::protobuf::RepeatedPtrField< ::mav::Waypoint > waypoint_; friend struct protobuf_mavProxyLink_2eproto::TableStruct; }; // ------------------------------------------------------------------- class Waypoint : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:mav.Waypoint) */ { public: Waypoint(); virtual ~Waypoint(); Waypoint(const Waypoint& from); inline Waypoint& operator=(const Waypoint& from) { CopyFrom(from); return *this; } #if LANG_CXX11 Waypoint(Waypoint&& from) noexcept : Waypoint() { *this = ::std::move(from); } inline Waypoint& operator=(Waypoint&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } static const ::google::protobuf::Descriptor* descriptor(); static const Waypoint& default_instance(); static inline const Waypoint* internal_default_instance() { return reinterpret_cast<const Waypoint*>( &_Waypoint_default_instance_); } static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = 2; void Swap(Waypoint* other); friend void swap(Waypoint& a, Waypoint& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline Waypoint* New() const PROTOBUF_FINAL { return New(NULL); } Waypoint* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL; void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void CopyFrom(const Waypoint& from); void MergeFrom(const Waypoint& from); void Clear() PROTOBUF_FINAL; bool IsInitialized() const PROTOBUF_FINAL; size_t ByteSizeLong() const PROTOBUF_FINAL; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const PROTOBUF_FINAL; void InternalSwap(Waypoint* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // required double lat = 1; bool has_lat() const; void clear_lat(); static const int kLatFieldNumber = 1; double lat() const; void set_lat(double value); // required double lon = 2; bool has_lon() const; void clear_lon(); static const int kLonFieldNumber = 2; double lon() const; void set_lon(double value); // required double altitude = 3; bool has_altitude() const; void clear_altitude(); static const int kAltitudeFieldNumber = 3; double altitude() const; void set_altitude(double value); // required double speed = 4; bool has_speed() const; void clear_speed(); static const int kSpeedFieldNumber = 4; double speed() const; void set_speed(double value); // required int32 type = 5; bool has_type() const; void clear_type(); static const int kTypeFieldNumber = 5; ::google::protobuf::int32 type() const; void set_type(::google::protobuf::int32 value); // @@protoc_insertion_point(class_scope:mav.Waypoint) private: void set_has_lat(); void clear_has_lat(); void set_has_lon(); void clear_has_lon(); void set_has_altitude(); void clear_has_altitude(); void set_has_speed(); void clear_has_speed(); void set_has_type(); void clear_has_type(); // helper for ByteSizeLong() size_t RequiredFieldsByteSizeFallback() const; ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; mutable int _cached_size_; double lat_; double lon_; double altitude_; double speed_; ::google::protobuf::int32 type_; friend struct protobuf_mavProxyLink_2eproto::TableStruct; }; // ------------------------------------------------------------------- class AircraftLink : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:mav.AircraftLink) */ { public: AircraftLink(); virtual ~AircraftLink(); AircraftLink(const AircraftLink& from); inline AircraftLink& operator=(const AircraftLink& from) { CopyFrom(from); return *this; } #if LANG_CXX11 AircraftLink(AircraftLink&& from) noexcept : AircraftLink() { *this = ::std::move(from); } inline AircraftLink& operator=(AircraftLink&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _internal_metadata_.unknown_fields(); } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } static const ::google::protobuf::Descriptor* descriptor(); static const AircraftLink& default_instance(); static inline const AircraftLink* internal_default_instance() { return reinterpret_cast<const AircraftLink*>( &_AircraftLink_default_instance_); } static PROTOBUF_CONSTEXPR int const kIndexInFileMessages = 3; void Swap(AircraftLink* other); friend void swap(AircraftLink& a, AircraftLink& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline AircraftLink* New() const PROTOBUF_FINAL { return New(NULL); } AircraftLink* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL; void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL; void CopyFrom(const AircraftLink& from); void MergeFrom(const AircraftLink& from); void Clear() PROTOBUF_FINAL; bool IsInitialized() const PROTOBUF_FINAL; size_t ByteSizeLong() const PROTOBUF_FINAL; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL; int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const PROTOBUF_FINAL; void InternalSwap(AircraftLink* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated .mav.Aircraft aircrafts = 1; int aircrafts_size() const; void clear_aircrafts(); static const int kAircraftsFieldNumber = 1; const ::mav::Aircraft& aircrafts(int index) const; ::mav::Aircraft* mutable_aircrafts(int index); ::mav::Aircraft* add_aircrafts(); ::google::protobuf::RepeatedPtrField< ::mav::Aircraft >* mutable_aircrafts(); const ::google::protobuf::RepeatedPtrField< ::mav::Aircraft >& aircrafts() const; // repeated .mav.Waypoints waypoints = 2; int waypoints_size() const; void clear_waypoints(); static const int kWaypointsFieldNumber = 2; const ::mav::Waypoints& waypoints(int index) const; ::mav::Waypoints* mutable_waypoints(int index); ::mav::Waypoints* add_waypoints(); ::google::protobuf::RepeatedPtrField< ::mav::Waypoints >* mutable_waypoints(); const ::google::protobuf::RepeatedPtrField< ::mav::Waypoints >& waypoints() const; // @@protoc_insertion_point(class_scope:mav.AircraftLink) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; mutable int _cached_size_; ::google::protobuf::RepeatedPtrField< ::mav::Aircraft > aircrafts_; ::google::protobuf::RepeatedPtrField< ::mav::Waypoints > waypoints_; friend struct protobuf_mavProxyLink_2eproto::TableStruct; }; // =================================================================== // =================================================================== #if !PROTOBUF_INLINE_NOT_IN_HEADERS #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // Aircraft // required double lat = 1; inline bool Aircraft::has_lat() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void Aircraft::set_has_lat() { _has_bits_[0] |= 0x00000001u; } inline void Aircraft::clear_has_lat() { _has_bits_[0] &= ~0x00000001u; } inline void Aircraft::clear_lat() { lat_ = 0; clear_has_lat(); } inline double Aircraft::lat() const { // @@protoc_insertion_point(field_get:mav.Aircraft.lat) return lat_; } inline void Aircraft::set_lat(double value) { set_has_lat(); lat_ = value; // @@protoc_insertion_point(field_set:mav.Aircraft.lat) } // required double lon = 2; inline bool Aircraft::has_lon() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void Aircraft::set_has_lon() { _has_bits_[0] |= 0x00000002u; } inline void Aircraft::clear_has_lon() { _has_bits_[0] &= ~0x00000002u; } inline void Aircraft::clear_lon() { lon_ = 0; clear_has_lon(); } inline double Aircraft::lon() const { // @@protoc_insertion_point(field_get:mav.Aircraft.lon) return lon_; } inline void Aircraft::set_lon(double value) { set_has_lon(); lon_ = value; // @@protoc_insertion_point(field_set:mav.Aircraft.lon) } // required double bearing = 3; inline bool Aircraft::has_bearing() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void Aircraft::set_has_bearing() { _has_bits_[0] |= 0x00000004u; } inline void Aircraft::clear_has_bearing() { _has_bits_[0] &= ~0x00000004u; } inline void Aircraft::clear_bearing() { bearing_ = 0; clear_has_bearing(); } inline double Aircraft::bearing() const { // @@protoc_insertion_point(field_get:mav.Aircraft.bearing) return bearing_; } inline void Aircraft::set_bearing(double value) { set_has_bearing(); bearing_ = value; // @@protoc_insertion_point(field_set:mav.Aircraft.bearing) } // required double speed = 4; inline bool Aircraft::has_speed() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void Aircraft::set_has_speed() { _has_bits_[0] |= 0x00000008u; } inline void Aircraft::clear_has_speed() { _has_bits_[0] &= ~0x00000008u; } inline void Aircraft::clear_speed() { speed_ = 0; clear_has_speed(); } inline double Aircraft::speed() const { // @@protoc_insertion_point(field_get:mav.Aircraft.speed) return speed_; } inline void Aircraft::set_speed(double value) { set_has_speed(); speed_ = value; // @@protoc_insertion_point(field_set:mav.Aircraft.speed) } // required double altitude = 5; inline bool Aircraft::has_altitude() const { return (_has_bits_[0] & 0x00000010u) != 0; } inline void Aircraft::set_has_altitude() { _has_bits_[0] |= 0x00000010u; } inline void Aircraft::clear_has_altitude() { _has_bits_[0] &= ~0x00000010u; } inline void Aircraft::clear_altitude() { altitude_ = 0; clear_has_altitude(); } inline double Aircraft::altitude() const { // @@protoc_insertion_point(field_get:mav.Aircraft.altitude) return altitude_; } inline void Aircraft::set_altitude(double value) { set_has_altitude(); altitude_ = value; // @@protoc_insertion_point(field_set:mav.Aircraft.altitude) } // required double wind_speed = 6; inline bool Aircraft::has_wind_speed() const { return (_has_bits_[0] & 0x00000020u) != 0; } inline void Aircraft::set_has_wind_speed() { _has_bits_[0] |= 0x00000020u; } inline void Aircraft::clear_has_wind_speed() { _has_bits_[0] &= ~0x00000020u; } inline void Aircraft::clear_wind_speed() { wind_speed_ = 0; clear_has_wind_speed(); } inline double Aircraft::wind_speed() const { // @@protoc_insertion_point(field_get:mav.Aircraft.wind_speed) return wind_speed_; } inline void Aircraft::set_wind_speed(double value) { set_has_wind_speed(); wind_speed_ = value; // @@protoc_insertion_point(field_set:mav.Aircraft.wind_speed) } // required double wind_direction = 7; inline bool Aircraft::has_wind_direction() const { return (_has_bits_[0] & 0x00000040u) != 0; } inline void Aircraft::set_has_wind_direction() { _has_bits_[0] |= 0x00000040u; } inline void Aircraft::clear_has_wind_direction() { _has_bits_[0] &= ~0x00000040u; } inline void Aircraft::clear_wind_direction() { wind_direction_ = 0; clear_has_wind_direction(); } inline double Aircraft::wind_direction() const { // @@protoc_insertion_point(field_get:mav.Aircraft.wind_direction) return wind_direction_; } inline void Aircraft::set_wind_direction(double value) { set_has_wind_direction(); wind_direction_ = value; // @@protoc_insertion_point(field_set:mav.Aircraft.wind_direction) } // required double motor_current = 8; inline bool Aircraft::has_motor_current() const { return (_has_bits_[0] & 0x00000080u) != 0; } inline void Aircraft::set_has_motor_current() { _has_bits_[0] |= 0x00000080u; } inline void Aircraft::clear_has_motor_current() { _has_bits_[0] &= ~0x00000080u; } inline void Aircraft::clear_motor_current() { motor_current_ = 0; clear_has_motor_current(); } inline double Aircraft::motor_current() const { // @@protoc_insertion_point(field_get:mav.Aircraft.motor_current) return motor_current_; } inline void Aircraft::set_motor_current(double value) { set_has_motor_current(); motor_current_ = value; // @@protoc_insertion_point(field_set:mav.Aircraft.motor_current) } // required double motor_throttle = 9; inline bool Aircraft::has_motor_throttle() const { return (_has_bits_[0] & 0x00000100u) != 0; } inline void Aircraft::set_has_motor_throttle() { _has_bits_[0] |= 0x00000100u; } inline void Aircraft::clear_has_motor_throttle() { _has_bits_[0] &= ~0x00000100u; } inline void Aircraft::clear_motor_throttle() { motor_throttle_ = 0; clear_has_motor_throttle(); } inline double Aircraft::motor_throttle() const { // @@protoc_insertion_point(field_get:mav.Aircraft.motor_throttle) return motor_throttle_; } inline void Aircraft::set_motor_throttle(double value) { set_has_motor_throttle(); motor_throttle_ = value; // @@protoc_insertion_point(field_set:mav.Aircraft.motor_throttle) } // ------------------------------------------------------------------- // Waypoints // repeated .mav.Waypoint waypoint = 1; inline int Waypoints::waypoint_size() const { return waypoint_.size(); } inline void Waypoints::clear_waypoint() { waypoint_.Clear(); } inline const ::mav::Waypoint& Waypoints::waypoint(int index) const { // @@protoc_insertion_point(field_get:mav.Waypoints.waypoint) return waypoint_.Get(index); } inline ::mav::Waypoint* Waypoints::mutable_waypoint(int index) { // @@protoc_insertion_point(field_mutable:mav.Waypoints.waypoint) return waypoint_.Mutable(index); } inline ::mav::Waypoint* Waypoints::add_waypoint() { // @@protoc_insertion_point(field_add:mav.Waypoints.waypoint) return waypoint_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::mav::Waypoint >* Waypoints::mutable_waypoint() { // @@protoc_insertion_point(field_mutable_list:mav.Waypoints.waypoint) return &waypoint_; } inline const ::google::protobuf::RepeatedPtrField< ::mav::Waypoint >& Waypoints::waypoint() const { // @@protoc_insertion_point(field_list:mav.Waypoints.waypoint) return waypoint_; } // ------------------------------------------------------------------- // Waypoint // required double lat = 1; inline bool Waypoint::has_lat() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void Waypoint::set_has_lat() { _has_bits_[0] |= 0x00000001u; } inline void Waypoint::clear_has_lat() { _has_bits_[0] &= ~0x00000001u; } inline void Waypoint::clear_lat() { lat_ = 0; clear_has_lat(); } inline double Waypoint::lat() const { // @@protoc_insertion_point(field_get:mav.Waypoint.lat) return lat_; } inline void Waypoint::set_lat(double value) { set_has_lat(); lat_ = value; // @@protoc_insertion_point(field_set:mav.Waypoint.lat) } // required double lon = 2; inline bool Waypoint::has_lon() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void Waypoint::set_has_lon() { _has_bits_[0] |= 0x00000002u; } inline void Waypoint::clear_has_lon() { _has_bits_[0] &= ~0x00000002u; } inline void Waypoint::clear_lon() { lon_ = 0; clear_has_lon(); } inline double Waypoint::lon() const { // @@protoc_insertion_point(field_get:mav.Waypoint.lon) return lon_; } inline void Waypoint::set_lon(double value) { set_has_lon(); lon_ = value; // @@protoc_insertion_point(field_set:mav.Waypoint.lon) } // required double altitude = 3; inline bool Waypoint::has_altitude() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void Waypoint::set_has_altitude() { _has_bits_[0] |= 0x00000004u; } inline void Waypoint::clear_has_altitude() { _has_bits_[0] &= ~0x00000004u; } inline void Waypoint::clear_altitude() { altitude_ = 0; clear_has_altitude(); } inline double Waypoint::altitude() const { // @@protoc_insertion_point(field_get:mav.Waypoint.altitude) return altitude_; } inline void Waypoint::set_altitude(double value) { set_has_altitude(); altitude_ = value; // @@protoc_insertion_point(field_set:mav.Waypoint.altitude) } // required double speed = 4; inline bool Waypoint::has_speed() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void Waypoint::set_has_speed() { _has_bits_[0] |= 0x00000008u; } inline void Waypoint::clear_has_speed() { _has_bits_[0] &= ~0x00000008u; } inline void Waypoint::clear_speed() { speed_ = 0; clear_has_speed(); } inline double Waypoint::speed() const { // @@protoc_insertion_point(field_get:mav.Waypoint.speed) return speed_; } inline void Waypoint::set_speed(double value) { set_has_speed(); speed_ = value; // @@protoc_insertion_point(field_set:mav.Waypoint.speed) } // required int32 type = 5; inline bool Waypoint::has_type() const { return (_has_bits_[0] & 0x00000010u) != 0; } inline void Waypoint::set_has_type() { _has_bits_[0] |= 0x00000010u; } inline void Waypoint::clear_has_type() { _has_bits_[0] &= ~0x00000010u; } inline void Waypoint::clear_type() { type_ = 0; clear_has_type(); } inline ::google::protobuf::int32 Waypoint::type() const { // @@protoc_insertion_point(field_get:mav.Waypoint.type) return type_; } inline void Waypoint::set_type(::google::protobuf::int32 value) { set_has_type(); type_ = value; // @@protoc_insertion_point(field_set:mav.Waypoint.type) } // ------------------------------------------------------------------- // AircraftLink // repeated .mav.Aircraft aircrafts = 1; inline int AircraftLink::aircrafts_size() const { return aircrafts_.size(); } inline void AircraftLink::clear_aircrafts() { aircrafts_.Clear(); } inline const ::mav::Aircraft& AircraftLink::aircrafts(int index) const { // @@protoc_insertion_point(field_get:mav.AircraftLink.aircrafts) return aircrafts_.Get(index); } inline ::mav::Aircraft* AircraftLink::mutable_aircrafts(int index) { // @@protoc_insertion_point(field_mutable:mav.AircraftLink.aircrafts) return aircrafts_.Mutable(index); } inline ::mav::Aircraft* AircraftLink::add_aircrafts() { // @@protoc_insertion_point(field_add:mav.AircraftLink.aircrafts) return aircrafts_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::mav::Aircraft >* AircraftLink::mutable_aircrafts() { // @@protoc_insertion_point(field_mutable_list:mav.AircraftLink.aircrafts) return &aircrafts_; } inline const ::google::protobuf::RepeatedPtrField< ::mav::Aircraft >& AircraftLink::aircrafts() const { // @@protoc_insertion_point(field_list:mav.AircraftLink.aircrafts) return aircrafts_; } // repeated .mav.Waypoints waypoints = 2; inline int AircraftLink::waypoints_size() const { return waypoints_.size(); } inline void AircraftLink::clear_waypoints() { waypoints_.Clear(); } inline const ::mav::Waypoints& AircraftLink::waypoints(int index) const { // @@protoc_insertion_point(field_get:mav.AircraftLink.waypoints) return waypoints_.Get(index); } inline ::mav::Waypoints* AircraftLink::mutable_waypoints(int index) { // @@protoc_insertion_point(field_mutable:mav.AircraftLink.waypoints) return waypoints_.Mutable(index); } inline ::mav::Waypoints* AircraftLink::add_waypoints() { // @@protoc_insertion_point(field_add:mav.AircraftLink.waypoints) return waypoints_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::mav::Waypoints >* AircraftLink::mutable_waypoints() { // @@protoc_insertion_point(field_mutable_list:mav.AircraftLink.waypoints) return &waypoints_; } inline const ::google::protobuf::RepeatedPtrField< ::mav::Waypoints >& AircraftLink::waypoints() const { // @@protoc_insertion_point(field_list:mav.AircraftLink.waypoints) return waypoints_; } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ #endif // !PROTOBUF_INLINE_NOT_IN_HEADERS // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace mav // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_mavProxyLink_2eproto__INCLUDED
dell-o/EFLS
src/mavProxyLink.pb.h
C
gpl-3.0
34,310
// * This file is part of the COLOBOT source code // * Copyright (C) 2001-2008, Daniel ROUX & EPSITEC SA, www.epsitec.ch // * Copyright (C) 2012, Polish Portal of Colobot (PPC) // * // * This program is free software: you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation, either version 3 of the License, or // * (at your option) any later version. // * // * This program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with this program. If not, see http://www.gnu.org/licenses/. #include "object/auto/autokid.h" #include "graphics/engine/particle.h" #include "graphics/engine/water.h" #include <stdio.h> // Object's constructor. CAutoKid::CAutoKid(CObject* object) : CAuto(object) { m_soundChannel = -1; Init(); } // Object's constructor. CAutoKid::~CAutoKid() { if ( m_soundChannel != -1 ) { m_sound->FlushEnvelope(m_soundChannel); m_sound->AddEnvelope(m_soundChannel, 0.0f, 1.0f, 1.0f, SOPER_STOP); m_soundChannel = -1; } } // Destroys the object. void CAutoKid::DeleteObject(bool bAll) { CAuto::DeleteObject(bAll); } // Initialize the object. void CAutoKid::Init() { Math::Vector pos; m_speed = 1.0f/1.0f; m_progress = 0.0f; m_lastParticle = 0.0f; if ( m_type == OBJECT_TEEN36 ) // trunk ? { pos = m_object->GetPosition(0); m_speed = 1.0f/(1.0f+(Math::Mod(pos.x/10.0f-0.5f, 1.0f)*0.2f)); m_progress = Math::Mod(pos.x/10.0f, 1.0f); } if ( m_type == OBJECT_TEEN37 ) // boat? { pos = m_object->GetPosition(0); m_speed = 1.0f/(1.0f+(Math::Mod(pos.x/10.0f-0.5f, 1.0f)*0.2f))*2.5f; m_progress = Math::Mod(pos.x/10.0f, 1.0f); } if ( m_type == OBJECT_TEEN38 ) // fan? { if ( m_soundChannel == -1 ) { //? m_soundChannel = m_sound->Play(SOUND_MANIP, m_object->GetPosition(0), 1.0f, 0.5f, true); m_bSilent = false; } } } // Management of an event. bool CAutoKid::EventProcess(const Event &event) { Math::Vector vib, pos, speed; Math::Point dim; CAuto::EventProcess(event); if ( m_soundChannel != -1 ) { if ( m_engine->GetPause() ) { if ( !m_bSilent ) { m_sound->AddEnvelope(m_soundChannel, 0.0f, 0.5f, 0.1f, SOPER_CONTINUE); m_bSilent = true; } } else { if ( m_bSilent ) { m_sound->AddEnvelope(m_soundChannel, 1.0f, 0.5f, 0.1f, SOPER_CONTINUE); m_bSilent = false; } } } if ( m_engine->GetPause() ) return true; if ( event.type != EVENT_FRAME ) return true; m_progress += event.rTime*m_speed; if ( m_type == OBJECT_TEEN36 ) // trunk? { vib.x = 0.0f; vib.y = sinf(m_progress)*1.0f; vib.z = 0.0f; m_object->SetLinVibration(vib); vib.x = 0.0f; vib.y = 0.0f; vib.z = sinf(m_progress*0.5f)*0.05f; m_object->SetCirVibration(vib); if ( m_lastParticle+m_engine->ParticleAdapt(0.15f) <= m_time ) { m_lastParticle = m_time; pos = m_object->GetPosition(0); pos.y = m_water->GetLevel()+1.0f; pos.x += (Math::Rand()-0.5f)*50.0f; pos.z += (Math::Rand()-0.5f)*50.0f; speed.y = 0.0f; speed.x = 0.0f; speed.z = 0.0f; dim.x = 50.0f; dim.y = dim.x; m_particle->CreateParticle(pos, speed, dim, Gfx::PARTIFLIC, 3.0f, 0.0f, 0.0f); } } if ( m_type == OBJECT_TEEN37 ) // boat? { vib.x = 0.0f; vib.y = sinf(m_progress)*1.0f; vib.z = 0.0f; m_object->SetLinVibration(vib); vib.x = 0.0f; vib.y = 0.0f; vib.z = sinf(m_progress*0.5f)*0.15f; m_object->SetCirVibration(vib); if ( m_lastParticle+m_engine->ParticleAdapt(0.15f) <= m_time ) { m_lastParticle = m_time; pos = m_object->GetPosition(0); pos.y = m_water->GetLevel()+1.0f; pos.x += (Math::Rand()-0.5f)*20.0f; pos.z += (Math::Rand()-0.5f)*20.0f; speed.y = 0.0f; speed.x = 0.0f; speed.z = 0.0f; dim.x = 20.0f; dim.y = dim.x; m_particle->CreateParticle(pos, speed, dim, Gfx::PARTIFLIC, 3.0f, 0.0f, 0.0f); } } if ( m_type == OBJECT_TEEN38 ) // fan? { m_object->SetAngleY(1, sinf(m_progress*0.6f)*0.4f); m_object->SetAngleX(2, m_progress*5.0f); } return true; } // Returns an error due the state of the automation. Error CAutoKid::GetError() { return ERR_OK; }
OdyX/colobot
src/object/auto/autokid.cpp
C++
gpl-3.0
5,113
'use strict'; var chakram = require('chakram'), expect = chakram.expect, Request = require('../../commons/request.js'), request = new Request(), User = require('../user/user.js'), user = new User(), Project = require('./project.js'), project = new Project(), ObjectID = require('mongodb').ObjectID, config = require('../../../../config/config.json'); describe('Project test', function() { //GET / get project published it('Get project published - all params', function() { return request.getBackend('/project?count=*&page=0&query=%7B%22hardwareTags%22:%7B%22$all%22:%5B%22us%22%5D%7D%7D',200).then(function(response) { expect(response).not.have.to.json([]); return chakram.wait(); }); }); it.skip('Get project published - without params', function() { return request.getBackend('/project',400).then(function() { return chakram.wait(); }); }); it.skip('Get project published - invalid params', function() { return request.getBackend('/project?p=0',400).then(function() { return request.getBackend('/project?cont=*',400).then(function() { return request.getBackend('/project?qery=%7B%22hardwareTags%22:%7B%22$all%22:%5B%22us%22%5D%7D%7D',400).then(function() { return chakram.wait(); }); }); }); }); it('Get project published - one params', function() { return request.getBackend('/project?page=1',200).then(function(response1) { expect(response1).not.have.to.json([]); return request.getBackend('/project?count=*',200).then(function(response2) { expect(response2).have.to.json('count', function(number) { expect(number).to.be.at.least(0); }); return request.getBackend('/project?query=%7B%22hardwareTags%22:%7B%22$all%22:%5B%22us%22%5D%7D%7D',200).then(function(response3) { expect(response3).not.have.to.json([]); return chakram.wait(); }); }); }); }); //GET /project/me it('Get projects of a user', function() { var userRandom = user.generateRandomUser(); return request.postBackend('/user',200,userRandom).then(function(response) { var project1 = project.generateProjectRandom(); var project2 = project.generateProjectRandom(); return request.postBackend('/project',200,project1,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() { return request.postBackend('/project',200,project2,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() { return request.getBackend('/project/me?page=0&pageSize=1',200,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response2) { expect(response2).have.to.json(function(json) { expect(json.length).to.be.equal(1); }); return request.getBackend('/project/me?pageSize=5',200,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response3) { expect(response3).have.to.json(function(json) { expect(json.length).to.be.equal(2); }); return chakram.wait(); }); }); }); }); }); }); it.skip('Get projects of a user - without mandatory params', function() { var userRandom = user.generateRandomUser(); return request.postBackend('/user',200,userRandom).then(function(response) { return request.getBackend('/project/me?page=0',400,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() { return request.getBackend('/project/me',400,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() { return chakram.wait(); }); }); }); }); it('Get projects of a user - token is incorrect', function() { var token = Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2); return request.getBackend('/project/me',401,{headers:{'Authorization':'Bearer '+token}}).then(function() { return request.getBackend('/project/me?page=0',401,{headers:{'Authorization':'Bearer '+token}}).then(function() { return request.getBackend('/project/me?pageSize=1',401,{headers:{'Authorization':'Bearer '+token}}).then(function() { return request.getBackend('/project/me?page=0&pageSize=1',401,{headers:{'Authorization':'Bearer '+token}}).then(function() { return chakram.wait(); }); }); }); }); }); //GET /project/shared it('Get shared projects of a user', function() { return request.postBackend('/auth/local',200,config.adminLogin).then(function(response) { return request.getBackend('/project/shared?pageSize=1',200,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response2) { expect(response2).have.to.json(function(json) { expect(json.length).to.be.equal(1); }); return request.getBackend('/project/shared?page=0&pageSize=3',200,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response3) { expect(response3).have.to.json(function(json) { expect(json.length).to.be.equal(3); }); }); }); }); }); it('Get shared projects of a user - token is incorrect', function() { var token = Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2); return request.getBackend('/project/shared',401,{headers:{'Authorization':'Bearer '+token}}).then(function() { return request.getBackend('/project/shared?page=0',401,{headers:{'Authorization':'Bearer '+token}}).then(function() { return request.getBackend('/project/shared?pageSize=1',401,{headers:{'Authorization':'Bearer '+token}}).then(function() { return request.getBackend('/project/shared?page=0&pageSize=1',401,{headers:{'Authorization':'Bearer '+token}}).then(function() { return chakram.wait(); }); }); }); }); }); it.skip('Get projects of a user - without mandatory params', function() { return request.postBackend('/auth/local',200,config.adminLogin).then(function(response) { return request.getBackend('/project/shared?page=0',400,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() { return request.getBackend('/project/shared',400,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() { return chakram.wait(); }); }); }); }); //GET /project/:id it('Get a project', function() { var userRandom = user.generateRandomUser(); return request.postBackend('/user',200,userRandom).then(function(response) { var project1 = project.generateProjectRandom(); return request.postBackend('/project',200,project1,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response2) { return request.getBackend('/project/'+response2.body,200,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response3) { expect(response3).not.have.to.json({}); chakram.wait(); }); }); }); }); it('Get a project - the project no exist', function() { var idRandom = new ObjectID(); var userRandom = user.generateRandomUser(); return request.postBackend('/user',200,userRandom).then(function(response) { return request.getBackend('/project/'+idRandom,404,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() { chakram.wait(); }); }); }); it('Get a project - invalid token', function() { var token = Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2); var userRandom = user.generateRandomUser(); return request.postBackend('/user',200,userRandom).then(function(response) { var project1 = project.generateProjectRandom(); return request.postBackend('/project',200,project1,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response2) { return request.getBackend('/project/'+response2.body,401,{headers:{'Authorization':'Bearer '+token}}).then(function() { chakram.wait(); }); }); }); }); });
bq/bitbloq-qa-backend
test/integration/api/backend/project/project_spec.js
JavaScript
gpl-3.0
9,144
package com.epam.wilma.webapp.stub.response.formatter.xsl; /*========================================================================== Copyright 2013-2015 EPAM Systems This file is part of Wilma. Wilma is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Wilma is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Wilma. If not, see <http://www.gnu.org/licenses/>. ===========================================================================*/ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import java.io.File; import java.io.IOException; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.epam.wilma.common.helper.FileFactory; import com.epam.wilma.common.helper.FileUtils; import com.epam.wilma.domain.http.WilmaHttpRequest; import com.epam.wilma.domain.stubconfig.StubResourcePathProvider; import com.epam.wilma.domain.stubconfig.parameter.Parameter; import com.epam.wilma.domain.stubconfig.parameter.ParameterList; import com.epam.wilma.webapp.domain.exception.TemplateFormattingFailedException; /** * Tests for {@link XslBasedTemplateFormatter}. * @author Tamas_Bihari * */ public class XslBasedTemplateFormatterTest { private static final String XSL_PARAM_KEY = "xslFile"; @Mock private FileUtils fileUtils; @Mock private FileFactory fileFactory; @Mock private StubResourcePathProvider stubResourcePathProvider; @Mock private XslResponseGenerator xslResponseGenerator; @Mock private WilmaHttpRequest wilmaRequest; @Mock private File file; @InjectMocks private XslBasedTemplateFormatter underTest; private byte[] templateResource; private ParameterList params; @BeforeMethod public void setUp() { MockitoAnnotations.initMocks(this); templateResource = new byte[1]; params = new ParameterList(); } @Test(expectedExceptions = TemplateFormattingFailedException.class) public void testFormatTemplateShouldThrowExceptionWhenXslFileParamDoesNotExist() throws Exception { //GIVEN in setUp //WHEN underTest.formatTemplate(wilmaRequest, templateResource, params, null); //THEN exception is thrown } @Test(expectedExceptions = TemplateFormattingFailedException.class) public void testFormatTemplateShouldThrowExceptionWhenXslFileResourceDoesNotExist() throws Exception { //GIVEN params.addParameter(new Parameter(XSL_PARAM_KEY, XSL_PARAM_KEY)); given(stubResourcePathProvider.getTemplatesPathAsString()).willReturn(XSL_PARAM_KEY); given(fileFactory.createFile(Mockito.anyString())).willReturn(file); given(fileUtils.getFileAsByteArray(file)).willThrow(new IOException()); //WHEN underTest.formatTemplate(wilmaRequest, templateResource, params, null); //THEN exception is thrown } @Test public void testFormatTemplateShouldGetRequestBodyFromWilmaRequest() throws Exception { //GIVEN params.addParameter(new Parameter(XSL_PARAM_KEY, XSL_PARAM_KEY)); given(stubResourcePathProvider.getTemplatesPathAsString()).willReturn(XSL_PARAM_KEY); given(fileFactory.createFile(Mockito.anyString())).willReturn(file); given(fileUtils.getFileAsByteArray(file)).willReturn(templateResource); given(wilmaRequest.getBody()).willReturn(templateResource.toString()); //WHEN underTest.formatTemplate(wilmaRequest, templateResource, params, null); //THEN verify(wilmaRequest).getBody(); } @Test public void testFormatTemplateShouldCallGenerateResponseOnXslResponseGenerator() throws Exception { //GIVEN params.addParameter(new Parameter(XSL_PARAM_KEY, XSL_PARAM_KEY)); given(stubResourcePathProvider.getTemplatesPathAsString()).willReturn(XSL_PARAM_KEY); given(fileFactory.createFile(Mockito.anyString())).willReturn(file); given(fileUtils.getFileAsByteArray(file)).willReturn(templateResource); given(wilmaRequest.getBody()).willReturn(XSL_PARAM_KEY); //WHEN underTest.formatTemplate(wilmaRequest, templateResource, params, null); //THEN verify(xslResponseGenerator).generateResponse(XSL_PARAM_KEY.getBytes(), templateResource, templateResource); } }
nagyistoce/Wilma
wilma-application/modules/wilma-webapp/src/test/java/com/epam/wilma/webapp/stub/response/formatter/xsl/XslBasedTemplateFormatterTest.java
Java
gpl-3.0
4,879
<template name="mainOverlaysDebugLeitnerItem"> <div class="debugLeitnerTimer"> <table class="table table-condensed"> <thead> <tr> <th colspan="2"> <strong>{{_ "overlays.debugLeitnerTimer.title"}}</strong> </th> </tr> </thead> <tbody> <tr> <td> {{_ "overlays.debugLeitnerTimer.workloadTime"}}: </td> <td> {{getWorkloadTimer}} </td> </tr> <tr> <td> {{_ "overlays.debugLeitnerTimer.breakTime"}}: </td> <td> {{getBreakTimer}} </td> </tr> <tr> <td> {{_ "overlays.debugLeitnerTimer.workloadsCompleted"}}: </td> <td> {{getWorkloadsCompleted}} </td> </tr> <tr> <td> {{_ "overlays.debugLeitnerTimer.breaksCompleted"}}: </td> <td> {{getBreaksCompleted}} </td> </tr> </tbody> </table> <div class="text-info text-center">{{getStatus}}</div> </div> </template>
thm-projects/arsnova-flashcards
imports/ui/main/overlays/debug/leitnerTimer.html
HTML
gpl-3.0
1,564
#!/usr/bin/env python # encoding: UTF-8 """ This file is part of Commix Project (http://commixproject.com). Copyright (c) 2014-2017 Anastasios Stasinopoulos (@ancst). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more see the file 'readme/COPYING' for copying permission. """ import os import sys import time import base64 import sqlite3 import urllib2 from src.utils import menu from src.utils import settings from src.thirdparty.colorama import Fore, Back, Style, init """ Session handler via SQLite3 db. """ no_such_table = False """ Generate table name for SQLite3 db. """ def table_name(url): host = url.split('//', 1)[1].split('/', 1)[0] table_name = "session_" + host.replace(".","_").replace(":","_").replace("-","_") return table_name """ Flush session. """ def flush(url): info_msg = "Flushing the stored session from the session file... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: conn = sqlite3.connect(settings.SESSION_FILE) tables = list(conn.execute("SELECT name FROM sqlite_master WHERE type is 'table'")) conn.executescript(';'.join(["DROP TABLE IF EXISTS %s" %i for i in tables])) conn.commit() conn.close() print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]" except sqlite3.OperationalError, err_msg: print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]" err_msg = "Unable to flush the session file." + str(err_msg).title() print settings.print_critical_msg(err_msg) """ Clear injection point records except latest for every technique. """ def clear(url): try: if no_such_table: conn = sqlite3.connect(settings.SESSION_FILE) conn.execute("DELETE FROM " + table_name(url) + "_ip WHERE "\ "id NOT IN (SELECT MAX(id) FROM " + \ table_name(url) + "_ip GROUP BY technique);") conn.commit() conn.close() except sqlite3.OperationalError, err_msg: print settings.print_critical_msg(err_msg) except: settings.LOAD_SESSION = False return False """ Import successful injection points to session file. """ def injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable): try: conn = sqlite3.connect(settings.SESSION_FILE) conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_ip" + \ "(id INTEGER PRIMARY KEY, url VARCHAR, technique VARCHAR, injection_type VARCHAR, separator VARCHAR," \ "shell VARCHAR, vuln_parameter VARCHAR, prefix VARCHAR, suffix VARCHAR, "\ "TAG VARCHAR, alter_shell VARCHAR, payload VARCHAR, http_header VARCHAR, http_request_method VARCHAR, url_time_response INTEGER, "\ "timesec INTEGER, how_long INTEGER, output_length INTEGER, is_vulnerable VARCHAR);") conn.execute("INSERT INTO " + table_name(url) + "_ip(url, technique, injection_type, separator, "\ "shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_header, http_request_method, "\ "url_time_response, timesec, how_long, output_length, is_vulnerable) "\ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", \ (str(url), str(technique), str(injection_type), \ str(separator), str(shell), str(vuln_parameter), str(prefix), str(suffix), \ str(TAG), str(alter_shell), str(payload), str(settings.HTTP_HEADER), str(http_request_method), \ int(url_time_response), int(timesec), int(how_long), \ int(output_length), str(is_vulnerable))) conn.commit() conn.close() if settings.INJECTION_CHECKER == False: settings.INJECTION_CHECKER = True except sqlite3.OperationalError, err_msg: err_msg = str(err_msg)[:1].upper() + str(err_msg)[1:] + "." err_msg += " You are advised to rerun with switch '--flush-session'." print settings.print_critical_msg(err_msg) sys.exit(0) except sqlite3.DatabaseError, err_msg: err_msg = "An error occurred while accessing session file ('" err_msg += settings.SESSION_FILE + "'). " err_msg += "If the problem persists use the '--flush-session' option." print "\n" + settings.print_critical_msg(err_msg) sys.exit(0) """ Export successful applied techniques from session file. """ def applied_techniques(url, http_request_method): try: conn = sqlite3.connect(settings.SESSION_FILE) if settings.TESTABLE_PARAMETER: applied_techniques = conn.execute("SELECT technique FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ "vuln_parameter = '" + settings.TESTABLE_PARAMETER + "' AND "\ "http_request_method = '" + http_request_method + "' "\ "ORDER BY id DESC ;") else: applied_techniques = conn.execute("SELECT technique FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ "vuln_parameter = '" + settings.INJECT_TAG + "' AND "\ "http_request_method = '" + http_request_method + "' "\ "ORDER BY id DESC ;") values = [] for session in applied_techniques: if "tempfile" in session[0][:8]: settings.TEMPFILE_BASED_STATE = True session = session[0][4:] elif "dynamic" in session[0][:7]: settings.EVAL_BASED_STATE = True session = session[0][13:] values += session[0][:1] applied_techniques = ''.join(list(set(values))) return applied_techniques except sqlite3.OperationalError, err_msg: #print settings.print_critical_msg(err_msg) settings.LOAD_SESSION = False return False except: settings.LOAD_SESSION = False return False """ Export successful applied techniques from session file. """ def applied_levels(url, http_request_method): try: conn = sqlite3.connect(settings.SESSION_FILE) if settings.TESTABLE_PARAMETER: applied_level = conn.execute("SELECT is_vulnerable FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ "vuln_parameter = '" + settings.TESTABLE_PARAMETER + "' AND "\ "http_request_method = '" + http_request_method + "' "\ "ORDER BY id DESC;") else: applied_level = conn.execute("SELECT is_vulnerable FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ "vuln_parameter = '" + settings.INJECT_TAG + "' AND "\ "http_request_method = '" + http_request_method + "' "\ "ORDER BY id DESC;") for session in applied_level: return session[0] except sqlite3.OperationalError, err_msg: #print settings.print_critical_msg(err_msg) settings.LOAD_SESSION = False return False except: settings.LOAD_SESSION = False return False """ Export successful injection points from session file. """ def injection_point_exportation(url, http_request_method): try: if not menu.options.flush_session: conn = sqlite3.connect(settings.SESSION_FILE) result = conn.execute("SELECT * FROM sqlite_master WHERE name = '" + \ table_name(url) + "_ip' AND type = 'table';") if result: if menu.options.tech[:1] == "c": select_injection_type = "R" elif menu.options.tech[:1] == "e": settings.EVAL_BASED_STATE = True select_injection_type = "R" elif menu.options.tech[:1] == "t": select_injection_type = "B" else: select_injection_type = "S" if settings.TEMPFILE_BASED_STATE and select_injection_type == "S": check_injection_technique = "t" elif settings.EVAL_BASED_STATE and select_injection_type == "R": check_injection_technique = "d" else: check_injection_technique = menu.options.tech[:1] if settings.TESTABLE_PARAMETER: cursor = conn.execute("SELECT * FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ "injection_type like '" + select_injection_type + "%' AND "\ "technique like '" + check_injection_technique + "%' AND "\ "vuln_parameter = '" + settings.TESTABLE_PARAMETER + "' AND "\ "http_request_method = '" + http_request_method + "' "\ "ORDER BY id DESC limit 1;") else: cursor = conn.execute("SELECT * FROM " + table_name(url) + "_ip WHERE "\ "url = '" + url + "' AND "\ "injection_type like '" + select_injection_type + "%' AND "\ "technique like '" + check_injection_technique + "%' AND "\ "http_header = '" + settings.HTTP_HEADER + "' AND "\ "http_request_method = '" + http_request_method + "' "\ "ORDER BY id DESC limit 1;") for session in cursor: url = session[1] technique = session[2] injection_type = session[3] separator = session[4] shell = session[5] vuln_parameter = session[6] prefix = session[7] suffix = session[8] TAG = session[9] alter_shell = session[10] payload = session[11] http_request_method = session[13] url_time_response = session[14] timesec = session[15] how_long = session[16] output_length = session[17] is_vulnerable = session[18] return url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable else: no_such_table = True pass except sqlite3.OperationalError, err_msg: #print settings.print_critical_msg(err_msg) settings.LOAD_SESSION = False return False except: settings.LOAD_SESSION = False return False """ Notification about session. """ def notification(url, technique, injection_type): try: if settings.LOAD_SESSION == True: success_msg = "A previously stored session has been held against that host." print settings.print_success_msg(success_msg) while True: if not menu.options.batch: question_msg = "Do you want to resume to the " question_msg += "(" + injection_type.split(" ")[0] + ") " question_msg += technique.rsplit(' ', 2)[0] question_msg += " injection point? [Y/n] > " sys.stdout.write(settings.print_question_msg(question_msg)) settings.LOAD_SESSION = sys.stdin.readline().replace("\n","").lower() else: settings.LOAD_SESSION = "" if len(settings.LOAD_SESSION) == 0: settings.LOAD_SESSION = "y" if settings.LOAD_SESSION in settings.CHOICE_YES: return True elif settings.LOAD_SESSION in settings.CHOICE_NO: settings.LOAD_SESSION = False if technique[:1] != "c": while True: question_msg = "Which technique do you want to re-evaluate? [(C)urrent/(a)ll/(n)one] > " sys.stdout.write(settings.print_question_msg(question_msg)) proceed_option = sys.stdin.readline().replace("\n","").lower() if len(proceed_option) == 0: proceed_option = "c" if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "a": settings.RETEST = True break elif proceed_option.lower() == "c" : settings.RETEST = False break elif proceed_option.lower() == "n": raise SystemExit() else: pass else: err_msg = "'" + proceed_option + "' is not a valid answer." print settings.print_error_msg(err_msg) pass if settings.SESSION_APPLIED_TECHNIQUES: menu.options.tech = ''.join(settings.AVAILABLE_TECHNIQUES) return False elif settings.LOAD_SESSION in settings.CHOICE_QUIT: raise SystemExit() else: err_msg = "'" + settings.LOAD_SESSION + "' is not a valid answer." print settings.print_error_msg(err_msg) pass except sqlite3.OperationalError, err_msg: print settings.print_critical_msg(err_msg) """ Check for specific stored parameter. """ def check_stored_parameter(url, http_request_method): if injection_point_exportation(url, http_request_method): if injection_point_exportation(url, http_request_method)[16] == str(menu.options.level): # Check for stored alternative shell if injection_point_exportation(url, http_request_method)[9] != "": menu.options.alter_shell = injection_point_exportation(url, http_request_method)[9] return True else: return False else: return False """ Import successful command execution outputs to session file. """ def store_cmd(url, cmd, shell, vuln_parameter): try: conn = sqlite3.connect(settings.SESSION_FILE) conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_ir" + \ "(cmd VARCHAR, output VARCHAR, vuln_parameter VARCHAR);") if settings.TESTABLE_PARAMETER: conn.execute("INSERT INTO " + table_name(url) + "_ir(cmd, output, vuln_parameter) "\ "VALUES(?,?,?)", \ (str(base64.b64encode(cmd)), str(base64.b64encode(shell)), str(vuln_parameter))) else: conn.execute("INSERT INTO " + table_name(url) + "_ir(cmd, output, vuln_parameter) "\ "VALUES(?,?,?)", \ (str(base64.b64encode(cmd)), str(base64.b64encode(shell)), str(settings.HTTP_HEADER))) conn.commit() conn.close() except sqlite3.OperationalError, err_msg: print settings.print_critical_msg(err_msg) except TypeError, err_msg: pass """ Export successful command execution outputs from session file. """ def export_stored_cmd(url, cmd, vuln_parameter): try: if not menu.options.flush_session: conn = sqlite3.connect(settings.SESSION_FILE) output = None conn = sqlite3.connect(settings.SESSION_FILE) if settings.TESTABLE_PARAMETER: cursor = conn.execute("SELECT output FROM " + table_name(url) + \ "_ir WHERE cmd='" + base64.b64encode(cmd) + "' AND "\ "vuln_parameter= '" + vuln_parameter + "';").fetchall() else: cursor = conn.execute("SELECT output FROM " + table_name(url) + \ "_ir WHERE cmd='" + base64.b64encode(cmd) + "' AND "\ "vuln_parameter= '" + settings.HTTP_HEADER + "';").fetchall() conn.commit() conn.close() for session in cursor: output = base64.b64decode(session[0]) return output else: no_such_table = True pass except sqlite3.OperationalError, err_msg: pass """ Import valid credentials to session file. """ def import_valid_credentials(url, authentication_type, admin_panel, username, password): try: conn = sqlite3.connect(settings.SESSION_FILE) conn.execute("CREATE TABLE IF NOT EXISTS " + table_name(url) + "_creds" + \ "(id INTEGER PRIMARY KEY, url VARCHAR, authentication_type VARCHAR, admin_panel VARCHAR, "\ "username VARCHAR, password VARCHAR);") conn.execute("INSERT INTO " + table_name(url) + "_creds(url, authentication_type, "\ "admin_panel, username, password) VALUES(?,?,?,?,?)", \ (str(url), str(authentication_type), str(admin_panel), \ str(username), str(password))) conn.commit() conn.close() except sqlite3.OperationalError, err_msg: print settings.print_critical_msg(err_msg) except sqlite3.DatabaseError, err_msg: err_msg = "An error occurred while accessing session file ('" err_msg += settings.SESSION_FILE + "'). " err_msg += "If the problem persists use the '--flush-session' option." print "\n" + settings.print_critical_msg(err_msg) sys.exit(0) """ Export valid credentials from session file. """ def export_valid_credentials(url, authentication_type): try: if not menu.options.flush_session: conn = sqlite3.connect(settings.SESSION_FILE) output = None conn = sqlite3.connect(settings.SESSION_FILE) cursor = conn.execute("SELECT username, password FROM " + table_name(url) + \ "_creds WHERE url='" + url + "' AND "\ "authentication_type= '" + authentication_type + "';").fetchall() cursor = ":".join(cursor[0]) return cursor else: no_such_table = True pass except sqlite3.OperationalError, err_msg: pass # eof
hackersql/sq1map
comm1x/src/utils/session_handler.py
Python
gpl-3.0
17,851
// <auto-generated /> namespace MakeYourPizza.Domain.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class InitialCreate : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(InitialCreate)); string IMigrationMetadata.Id { get { return "201612021808279_InitialCreate"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
sergiu05/make-your-pizza-aspnet-mvc5
MakeYourPizza/MakeYourPizza.Domain/Migrations/201612021808279_InitialCreate.Designer.cs
C#
gpl-3.0
831
package com.example.gabri.apasos; import java.util.Date; /** * Created by 8fprogmm09 on 7/4/16. */ public class Ruta { private int id_ruta; private String fecha; public Ruta(int id,String f){ id_ruta=id; fecha=f; } public int getId_ruta() { return id_ruta; } public void setId_ruta(int id_ruta) { this.id_ruta = id_ruta; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } }
gabritejedor/apasos
Apasos/app/src/main/java/com/example/gabri/apasos/Ruta.java
Java
gpl-3.0
534
This is the Inno Setup script that creates the Windows installer
rafaelalmeidatk/Super-Pete-The-Pirate
Setup/README.md
Markdown
gpl-3.0
64
package com.betting.ui; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author Rob * @since 10.02.2016 */ @SpringBootApplication public class ApplicationBootstrap { public static void main(String[] args) { SpringApplication.run(ApplicationBootstrap.class, args); } }
rtelle/websckt-demo
betting-ui/src/main/java/com/betting/ui/ApplicationBootstrap.java
Java
gpl-3.0
369
* html .u0_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u0_original.png"); } * html .u2_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u28_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u28_line.png"); } * html .u29_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u29_original.png"); } * html .u31_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u33_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u35_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u35_line.png"); } * html .u36_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u82_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u82_original.png"); } * html .u84_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u84_original.png"); } * html .u89_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u89_line.png"); } * html .u90_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u90_line.png"); } * html .u93_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="footer_files/u34_line.png"); } * html .u178_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u178_line.png"); } * html .u179_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u84_original.png"); } * html .u181_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u84_original.png"); } * html .u183_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u84_original.png"); } * html .u188_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u188_line.png"); } * html .u189_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u189_line.png"); } * html .u190_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u190_original.png"); } * html .u192_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u192_original.png"); } * html .u194_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u194_original.png"); } * html .u196_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u194_original.png"); } * html .u198_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u198_original.png"); } * html .u200_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u200_original.png"); } * html .u270_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u270_line.png"); } * html .u271_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u271_original.png"); } * html .u277_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u200_original.png"); } * html .u280_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u280_line.png"); } * html .u281_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u283_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u285_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u285_line.png"); } * html .u286_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u360_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u360_line.png"); } * html .u361_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u271_original.png"); } * html .u367_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u367_line.png"); } * html .u368_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u394_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u394_line.png"); } * html .u395_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u421_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u421_line.png"); } * html .u422_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u200_original.png"); } * html .u425_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u427_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u429_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u429_line.png"); } * html .u430_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u504_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u504_line.png"); } * html .u505_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u271_original.png"); } * html .u511_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u511_line.png"); } * html .u512_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u2_original.png"); } * html .u538_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u538_line.png"); } * html .u540_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u200_original.png"); } * html .u542_original { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="cm-passo-4-orcamento_files/u542_original.png"); } * html .u552_line { background-image: none; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="header-curta-metragem_files/u84_line.png"); }
clebersantos/sasp
doc/wireframe/editais-sav/cm-passo-4-orcamento_files/axurerp_pagespecificstyles_ie6.css
CSS
gpl-3.0
9,100