repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
jazzsequence/games-collector
vendor/fig-r/psr2r-sniffer/PSR2R/Sniffs/ControlStructures/ElseIfDeclarationSniff.php
1981
<?php /** * PSR2_Sniffs_ControlStructures_ElseIfDeclarationSniff. * * PHP version 5 * * @category PHP * * @author Greg Sherwood <[email protected]> * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * * @link http://pear.php.net/package/PHP_CodeSniffer */ namespace PSR2R\Sniffs\ControlStructures; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\Sniff; /** * PSR2_Sniffs_ControlStructures_ElseIfDeclarationSniff. * * Verifies that there are no else if statements. Elseif should be used instead. * * @author Greg Sherwood <[email protected]> * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * * @version Release: @package_version@ * * @link http://pear.php.net/package/PHP_CodeSniffer */ class ElseIfDeclarationSniff implements Sniff { /** * @inheritDoc */ public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if ($tokens[$stackPtr]['code'] === T_ELSEIF) { $phpcsFile->recordMetric($stackPtr, 'Use of ELSE IF or ELSEIF', 'elseif'); return; } $next = $phpcsFile->findNext(T_WHITESPACE, $stackPtr + 1, null, true); if ($tokens[$next]['code'] === T_IF) { $phpcsFile->recordMetric($stackPtr, 'Use of ELSE IF or ELSEIF', 'else if'); $error = 'Usage of ELSE IF is discouraged; use ELSEIF instead'; $fix = $phpcsFile->addFixableWarning($error, $stackPtr, 'NotAllowed'); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); $phpcsFile->fixer->replaceToken($stackPtr, 'elseif'); for ($i = ($stackPtr + 1); $i <= $next; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->endChangeset(); } } } /** * @inheritDoc */ public function register() { return [ T_ELSE, T_ELSEIF, ]; } }
gpl-3.0
cosminrentea/roda
src/main/java/ro/roda/service/DataSourceTypeServiceImpl.java
1092
package ro.roda.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ro.roda.domain.DataSourceType; @Service @Transactional public class DataSourceTypeServiceImpl implements DataSourceTypeService { public long countAllDataSourceTypes() { return DataSourceType.countDataSourceTypes(); } public void deleteDataSourceType(DataSourceType dataSourceType) { dataSourceType.remove(); } public DataSourceType findDataSourceType(Integer id) { return DataSourceType.findDataSourceType(id); } public List<DataSourceType> findAllDataSourceTypes() { return DataSourceType.findAllDataSourceTypes(); } public List<DataSourceType> findDataSourceTypeEntries(int firstResult, int maxResults) { return DataSourceType.findDataSourceTypeEntries(firstResult, maxResults); } public void saveDataSourceType(DataSourceType dataSourceType) { dataSourceType.persist(); } public DataSourceType updateDataSourceType(DataSourceType dataSourceType) { return dataSourceType.merge(); } }
gpl-3.0
rgarro/emptyLibJS
3D/Util/Props/SmokeEmitter.js
2664
/** * Red Foreman muffler shop is in point place wisconsin .... * * @author Rolando <[email protected]> */ var SmokeEmitter = (function(){ function SmokeEmitter(scene){ this.scene = scene this.textureUrl = "/emptyLibJS/3D/Games/Kalero/assets/smokeb.png"; this.smokeParticles = null; this.smoke = null; this.smokeColor = 0x111111; this.smokeSize = 50; this.transparent = true; this.smokeX = -150; this.smokeY = 0; this.smokeZ = 0; this.density = 15;//300 this.smokeClouds = []; this.smokeCloudsPS = []; this.smokeParticles = null; this.cloudCount = 0; this.smokeTexture = null; this.clock = new THREE.Clock(); } SmokeEmitter.prototype.doSmoke = function(){ var smokeParticles = new THREE.Geometry; this.smokeTexture = new THREE.TextureLoader().load(this.textureUrl); var smokeMaterial = new THREE.PointsMaterial({ map: this.smokeTexture, transparent: this.transparent, blending: THREE.AdditiveBlending, size: this.smokeSize, color: this.smokeColor }); for (var i = 0; i < this.density; i++) { var particle = new THREE.Vector3(Math.random() * 32 - 16, Math.random() * 230, Math.random() * 32 - 16); smokeParticles.vertices.push(particle); } this.smoke = new THREE.Points(smokeParticles,smokeMaterial); this.smoke.sortParticles = true; this.smoke.position.x = this.smokeX; this.smoke.position.y = this.smokeY; this.smoke.position.z = this.smokeZ; this.smoke.name = "smokeCloud" + this.cloudCount; smokeParticles.name = "smokeP" + this.cloudCount; this.cloudCount ++; this.smokeClouds.unshift(smokeParticles); this.smokeCloudsPS.unshift(this.smoke); this.scene.add(this.smoke); } SmokeEmitter.prototype.onRender = function(){ this.clock = new THREE.Clock(); var delta = this.clock.getDelta(); this.smokeParticles = this.smokeClouds[0]; var particleCount = this.smokeParticles.vertices.length; while (particleCount--) { var particle = this.smokeParticles.vertices[particleCount]; particle.y += delta * 50; if (particle.y >= 100) { particle.y = Math.random() * 16; particle.x = Math.random() * 32 - 16; particle.z = Math.random() * 32 - 16; } } this.smokeParticles.__dirtyVertices = true; if(this.smokeClouds.length > 1){ this.smokeClouds.pop(); var cloud = (this.smokeCloudsPS.pop()).name; var fadingCloud = this.scene.getObjectByName(cloud); this.scene.remove(fadingCloud); //this.doSmoke(); } } return SmokeEmitter; })(); eO.Util.Props.SmokeEmitter = SmokeEmitter;
gpl-3.0
aasisvinayak/flymyshop
core/config/database.php
4259
<?php return [ /* |-------------------------------------------------------------------------- | PDO Fetch Style |-------------------------------------------------------------------------- | | By default, database results will be returned as instances of the PHP | stdClass object; however, you may desire to retrieve records in an | array format for simplicity. Here you can tweak the fetch style. | */ 'fetch' => PDO::FETCH_CLASS, /* |-------------------------------------------------------------------------- | Default Database Connection Name |-------------------------------------------------------------------------- | | Here you may specify which of the database connections below you wish | to use as your default connection for all database work. Of course | you may use many connections at once using the Database library. | */ 'default' => env('DB_CONNECTION', 'mysql'), /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => [ 'sqlite' => [ 'driver' => 'sqlite', 'database' => storage_path().'/database.sqlite', 'prefix' => '', ], 'sqlite_testing' => [ 'driver' => 'sqlite', 'database' => database_path('testing.sqlite'), 'prefix' => '', ], 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST'), 'port' => env('DB_PORT'), 'database' => env('DB_DATABASE'), 'username' => env('DB_USERNAME'), 'password' => env('DB_PASSWORD'), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, 'engine' => null, ], 'testing' => [ 'driver' => 'sqlite', 'database' => storage_path().'/database.sqlite', 'prefix' => '', ], 'pgsql' => [ 'driver' => 'pgsql', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', '5432'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', ], ], /* |-------------------------------------------------------------------------- | Migration Repository Table |-------------------------------------------------------------------------- | | This table keeps track of all the migrations that have already run for | your application. Using this information, we can determine which of | the migrations on disk haven't actually been run in the database. | */ 'migrations' => 'migrations', /* |-------------------------------------------------------------------------- | Redis Databases |-------------------------------------------------------------------------- | | Redis is an open source, fast, and advanced key-value store that also | provides a richer set of commands than a typical key-value systems | such as APC or Memcached. Laravel makes it easy to dig right in. | */ 'redis' => [ 'cluster' => false, 'default' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], ], ];
gpl-3.0
tacalvin/rshell
src/Shell.cpp
7889
#include "./headers/Shell.h" #include "./headers/Base.h" #include "./headers/Command.h" #include <vector> #include <pwd.h> #include <iostream> #include <unistd.h> #include <sstream> #include <string.h> #include <cstdlib> #include <stdio.h> #include <errno.h> #include <csignal> #include <deque> #include <stdexcept> const int BUFFSIZE = 1024; const char* AND = "&&"; const char* OR = "||"; const char* SEMI = ";"; const char* REDIRL = "<"; const char* REDIRR = ">"; Shell::Shell() { //do configuration stuff here } void signalHandler( int signum ) { cout << "Interrupt signal (" << signum << ") received.\n"; // cleanup and close up stuff here // terminate program exit(signum); } void Shell::run() { //getlogin does not work on windows bash atm char* uname = getpwuid(getuid())->pw_name; char hname[BUFFSIZE]; gethostname(hname,BUFFSIZE); if(hname == NULL) perror("error getting hostname"); //register signal handler signal(SIGINT,signalHandler); string line; char* currDir = getenv("PWD"); cout << uname << "@" << hname <<"$ " << currDir << endl; //setting HOME char home[1024]; strcpy(home,"/home/"); strcat(home,uname); setenv("HOME",home,1); //cout << uname <<"@" << hname <<"$" ; while(getline(cin,line)) { try { if(line == "") { cout << uname << "@" << hname<<"$ "; continue; } stack<string> cmds = parse(line); // cin.clear(); //fseek(stdin,0,SEEK_END); //eof = false; //continue; Base* cmd = buildCommand(cmds); cmd->evaluate(); } catch (runtime_error& e) { cout << e.what() << endl; } uname = getpwuid(getuid())->pw_name; currDir = getenv("PWD"); cout << uname << "@" << hname << "$ " << currDir << endl; } } Base* Shell::buildParenthesis(stack<string>& commandStack) { int counter = 1; deque<string> tempDeque; while (counter > 0) { string tempString = commandStack.top(); commandStack.pop(); if (tempString == ")") { counter++; tempDeque.push_front(tempString); } else if (tempString == "(") { counter--; if (counter > 0) tempDeque.push_front(tempString); } else { tempDeque.push_front(tempString); } } stack<string> dequeStack(tempDeque); return buildCommand(dequeStack); } Base* Shell::buildCommand(stack<string>& commandStack) { stack<Base*> treeStack; while (!commandStack.empty()) { string currString = commandStack.top(); commandStack.pop(); if (currString == ")") { treeStack.push(buildParenthesis(commandStack)); } else if (currString == ";") { Base* left = buildCommand(commandStack); Base* right = treeStack.top(); treeStack.pop(); treeStack.push(new SemiOperator(left, right)); } else if (currString == "&&") { Base* left; if (commandStack.top() == ")") { commandStack.pop(); left = buildParenthesis(commandStack); } else { left = new Command(convertCharVector(commandStack.top())); commandStack.pop(); } Base* right = treeStack.top(); treeStack.pop(); treeStack.push(new AndOperator(left, right)); } else if (currString == "||") { Base* left; if (commandStack.top() == ")") { commandStack.pop(); left = buildParenthesis(commandStack); } else { left = new Command(convertCharVector(commandStack.top())); commandStack.pop(); } Base* right = treeStack.top(); treeStack.pop(); treeStack.push(new OrOperator(left, right)); } else { treeStack.push(new Command(convertCharVector(currString))); } } if (treeStack.size() != 1) throw runtime_error("tempstack building didn't work."); return treeStack.top(); } stack<string> Shell::parse(string line) { char currChar; string delimiters = ";|&()"; stack<string> commandStack; istringstream ss(line); int parenthesisStatus = 0; //shit solution, but simple, iterate through and increment for each (, decrement for each ), must be 0 and //should never go to negative if valid while(ss.get(currChar)) { if (currChar == '(') parenthesisStatus++; else if (currChar == ')') parenthesisStatus--; if (parenthesisStatus < 0) { throw runtime_error("syntax error near unexpected token ')'"); } } if (parenthesisStatus) { throw runtime_error("syntax error near unexpected token '('"); } ss.clear(); ss.str(line); // false = operator is not fine, true = operator fine bool operatorValid = false; string command = ""; // the purpose of this loop is the create a vector of strings of individual // commands to parse seperately, operators are their own entries while(ss.get(currChar)) { size_t delimStatus = delimiters.find(currChar); // if the current character is not a delimiter if (currChar =='#') break; if (delimStatus == string::npos && !ss.eof()) { // add the character as part of the command command.push_back(currChar); if (currChar != ' ') operatorValid = true; } else { //if the current character is a delimiter candidate if (currChar == '(') { if (operatorValid && !commandStack.empty()) throw runtime_error("1syntax error near unexpected token '('"); command = "("; cleanPush(commandStack, command); command = ""; } else if (currChar == ')') { if (!operatorValid) throw runtime_error("syntax error near unexpected token ')'"); if (commandStack.top() == "(" && command.empty()) throw runtime_error("syntax error near unexpected token '('"); cleanPush(commandStack, command); command = ")"; cleanPush(commandStack, command); command = ""; } else if (currChar == ';') { if (!operatorValid) throw runtime_error("syntax error near unexpected token `;'"); cleanPush(commandStack, command); command = ";"; cleanPush(commandStack, command); command = ""; operatorValid = false; } else if (currChar == '&' && ss.peek() == '&') { if (!operatorValid) throw runtime_error("syntax error near unexpected token `&&'"); cleanPush(commandStack, command); command = "&&"; cleanPush(commandStack, command); command = ""; // remove extra & currChar = ss.get(); operatorValid = false; } else if (currChar == '|' && ss.peek() == '|') { if (!operatorValid) throw runtime_error("syntax error near unexpected token `||'"); cleanPush(commandStack, command); command = "||"; cleanPush(commandStack, command); command = ""; currChar = ss.get(); operatorValid = false; } else { command.push_back(currChar); } } } if (!operatorValid) throw runtime_error("syntax error near unexpected ending token"); cleanPush(commandStack, command); //TODO: test case of what happens if there is a leading space //debug return commandStack; } void Shell::cleanPush(stack<string>& targetStack, string target) { if (target == "" || target.find_first_not_of(' ') == string::npos) return; target.erase(0, target.find_first_not_of(' ')); target.erase(target.find_last_not_of(' ') + 1); targetStack.push(target); } vector<char*> Shell::convertCharVector(string command) { vector<char*> s; istringstream ss(command); //since char** is needed converting const char* to char* via copying while(getline(ss,command,' ')) { //create new char* of size line char* lineC = new char[command.size()]; //char* lineC = new char(sizeof(command.c_str())); strcpy(lineC,command.c_str()); s.push_back(lineC); } return s; }
gpl-3.0
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/plugins/embedbase/lang/ug.js
829
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'embedbase', 'ug', { pathName: 'ۋاسىتە ئوبيېكتى', title: 'سىڭدۈرمە ۋاسىتە', button: 'سىڭدۈرمە ۋاسىتە قىستۇر', unsupportedUrlGiven: 'بەلگىلەنگەن ئۇلانمىنى قوللىمايدۇ .', unsupportedUrl: 'The URL {url} is not supported by Media Embed.', // MISSING fetchingFailedGiven: 'Failed to fetch content for the given URL.', // MISSING fetchingFailed: 'Failed to fetch content for {url}.', // MISSING fetchingOne: 'oEmbed نىڭ ئىنكاسىغا ئېرىشىۋاتىدۇ ...', fetchingMany: 'Fetching oEmbed responses, {current} of {max} done...' // MISSING } );
gpl-3.0
xamarindevelopervietnaminc/XInfiniteListView
XInfiniteListView/XInfiniteListView/XInfiniteListView.iOS/AppDelegate.cs
1042
using Foundation; using UIKit; namespace XInfiniteListView.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
gpl-3.0
jvianney/SwiftHR
application/modules/default/library/HTMLPurifier/Printer/ConfigForm.php
13324
<?php /** * @todo Rewrite to use Interchange objects */ class HTMLPurifier_Printer_ConfigForm extends HTMLPurifier_Printer { /** * Printers for specific fields */ protected $fields = array(); /** * Documentation URL, can have fragment tagged on end */ protected $docURL; /** * Name of form element to stuff config in */ protected $name; /** * Whether or not to compress directive names, clipping them off * after a certain amount of letters. False to disable or integer letters * before clipping. */ protected $compress = false; /** * @param $name Form element name for directives to be stuffed into * @param $doc_url String documentation URL, will have fragment tagged on * @param $compress Integer max length before compressing a directive name, set to false to turn off */ public function __construct( $name, $doc_url = null, $compress = false ) { parent::__construct(); $this->docURL = $doc_url; $this->name = $name; $this->compress = $compress; // initialize sub-printers $this->fields[0] = new HTMLPurifier_Printer_ConfigForm_default(); $this->fields[HTMLPurifier_VarParser::BOOL] = new HTMLPurifier_Printer_ConfigForm_bool(); } /** * Retrieves styling, in case it is not accessible by webserver */ public static function getCSS() { return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.css'); } /** * Retrieves JavaScript, in case it is not accessible by webserver */ public static function getJavaScript() { return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.js'); } /** * Sets default column and row size for textareas in sub-printers * @param $cols Integer columns of textarea, null to use default * @param $rows Integer rows of textarea, null to use default */ public function setTextareaDimensions($cols = null, $rows = null) { if ($cols) $this->fields['default']->cols = $cols; if ($rows) $this->fields['default']->rows = $rows; } /** * Returns HTML output for a configuration form * @param $config Configuration object of current form state, or an array * where [0] has an HTML namespace and [1] is being rendered. * @param $allowed Optional namespace(s) and directives to restrict form to. */ public function render($config, $allowed = true, $render_controls = true) { if (is_array($config) && isset($config[0])) { $gen_config = $config[0]; $config = $config[1]; } else { $gen_config = $config; } $this->config = $config; $this->genConfig = $gen_config; $this->prepareGenerator($gen_config); $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $config->def); $all = array(); foreach ($allowed as $key) { list($ns, $directive) = $key; $all[$ns][$directive] = $config->get($ns . '.' . $directive); } $ret = ''; $ret .= $this->start('table', array('class' => 'hp-config')); $ret .= $this->start('thead'); $ret .= $this->start('tr'); $ret .= $this->element('th', 'Directive', array('class' => 'hp-directive')); $ret .= $this->element('th', 'Value', array('class' => 'hp-value')); $ret .= $this->end('tr'); $ret .= $this->end('thead'); foreach ($all as $ns => $directives) { $ret .= $this->renderNamespace($ns, $directives); } if ($render_controls) { $ret .= $this->start('tbody'); $ret .= $this->start('tr'); $ret .= $this->start('td', array('colspan' => 2, 'class' => 'controls')); $ret .= $this->elementEmpty('input', array('type' => 'submit', 'value' => 'Submit')); $ret .= '[<a href="?">Reset</a>]'; $ret .= $this->end('td'); $ret .= $this->end('tr'); $ret .= $this->end('tbody'); } $ret .= $this->end('table'); return $ret; } /** * Renders a single namespace * @param $ns String namespace name * @param $directive Associative array of directives to values */ protected function renderNamespace($ns, $directives) { $ret = ''; $ret .= $this->start('tbody', array('class' => 'namespace')); $ret .= $this->start('tr'); $ret .= $this->element('th', $ns, array('colspan' => 2)); $ret .= $this->end('tr'); $ret .= $this->end('tbody'); $ret .= $this->start('tbody'); foreach ($directives as $directive => $value) { $ret .= $this->start('tr'); $ret .= $this->start('th'); if ($this->docURL) { $url = str_replace('%s', urlencode("$ns.$directive"), $this->docURL); $ret .= $this->start('a', array('href' => $url)); } $attr = array('for' => "{$this->name}:$ns.$directive"); // crop directive name if it's too long if (!$this->compress || (strlen($directive) < $this->compress)) { $directive_disp = $directive; } else { $directive_disp = substr($directive, 0, $this->compress - 2) . '...'; $attr['title'] = $directive; } $ret .= $this->element( 'label', $directive_disp, // component printers must create an element with this id $attr ); if ($this->docURL) $ret .= $this->end('a'); $ret .= $this->end('th'); $ret .= $this->start('td'); $def = $this->config->def->info["$ns.$directive"]; if (is_int($def)) { $allow_null = $def < 0; $type = abs($def); } else { $type = $def->type; $allow_null = isset($def->allow_null); } if (!isset($this->fields[$type])) $type = 0; // default $type_obj = $this->fields[$type]; if ($allow_null) { $type_obj = new HTMLPurifier_Printer_ConfigForm_NullDecorator($type_obj); } $ret .= $type_obj->render($ns, $directive, $value, $this->name, array($this->genConfig, $this->config)); $ret .= $this->end('td'); $ret .= $this->end('tr'); } $ret .= $this->end('tbody'); return $ret; } } /** * Printer decorator for directives that accept null */ class HTMLPurifier_Printer_ConfigForm_NullDecorator extends HTMLPurifier_Printer { /** * Printer being decorated */ protected $obj; /** * @param $obj Printer to decorate */ public function __construct($obj) { parent::__construct(); $this->obj = $obj; } public function render($ns, $directive, $value, $name, $config) { if (is_array($config) && isset($config[0])) { $gen_config = $config[0]; $config = $config[1]; } else { $gen_config = $config; } $this->prepareGenerator($gen_config); $ret = ''; $ret .= $this->start('label', array('for' => "$name:Null_$ns.$directive")); $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); $ret .= $this->text(' Null/Disabled'); $ret .= $this->end('label'); $attr = array( 'type' => 'checkbox', 'value' => '1', 'class' => 'null-toggle', 'name' => "$name" . "[Null_$ns.$directive]", 'id' => "$name:Null_$ns.$directive", 'onclick' => "toggleWriteability('$name:$ns.$directive',checked)" // INLINE JAVASCRIPT!!!! ); if ($this->obj instanceof HTMLPurifier_Printer_ConfigForm_bool) { // modify inline javascript slightly $attr['onclick'] = "toggleWriteability('$name:Yes_$ns.$directive',checked);toggleWriteability('$name:No_$ns.$directive',checked)"; } if ($value === null) $attr['checked'] = 'checked'; $ret .= $this->elementEmpty('input', $attr); $ret .= $this->text(' or '); $ret .= $this->elementEmpty('br'); $ret .= $this->obj->render($ns, $directive, $value, $name, array($gen_config, $config)); return $ret; } } /** * Swiss-army knife configuration form field printer */ class HTMLPurifier_Printer_ConfigForm_default extends HTMLPurifier_Printer { public $cols = 18; public $rows = 5; public function render($ns, $directive, $value, $name, $config) { if (is_array($config) && isset($config[0])) { $gen_config = $config[0]; $config = $config[1]; } else { $gen_config = $config; } $this->prepareGenerator($gen_config); // this should probably be split up a little $ret = ''; $def = $config->def->info["$ns.$directive"]; if (is_int($def)) { $type = abs($def); } else { $type = $def->type; } if (is_array($value)) { switch ($type) { case HTMLPurifier_VarParser::LOOKUP: $array = $value; $value = array(); foreach ($array as $val => $b) { $value[] = $val; } case HTMLPurifier_VarParser::ALIST: $value = implode(PHP_EOL, $value); break; case HTMLPurifier_VarParser::HASH: $nvalue = ''; foreach ($value as $i => $v) { $nvalue .= "$i:$v" . PHP_EOL; } $value = $nvalue; break; default: $value = ''; } } if ($type === HTMLPurifier_VarParser::MIXED) { return 'Not supported'; $value = serialize($value); } $attr = array( 'name' => "$name" . "[$ns.$directive]", 'id' => "$name:$ns.$directive" ); if ($value === null) $attr['disabled'] = 'disabled'; if (isset($def->allowed)) { $ret .= $this->start('select', $attr); foreach ($def->allowed as $val => $b) { $attr = array(); if ($value == $val) $attr['selected'] = 'selected'; $ret .= $this->element('option', $val, $attr); } $ret .= $this->end('select'); } elseif ( $type === HTMLPurifier_VarParser::TEXT || $type === HTMLPurifier_VarParser::ITEXT || $type === HTMLPurifier_VarParser::ALIST || $type === HTMLPurifier_VarParser::HASH || $type === HTMLPurifier_VarParser::LOOKUP ) { $attr['cols'] = $this->cols; $attr['rows'] = $this->rows; $ret .= $this->start('textarea', $attr); $ret .= $this->text($value); $ret .= $this->end('textarea'); } else { $attr['value'] = $value; $attr['type'] = 'text'; $ret .= $this->elementEmpty('input', $attr); } return $ret; } } /** * Bool form field printer */ class HTMLPurifier_Printer_ConfigForm_bool extends HTMLPurifier_Printer { public function render($ns, $directive, $value, $name, $config) { if (is_array($config) && isset($config[0])) { $gen_config = $config[0]; $config = $config[1]; } else { $gen_config = $config; } $this->prepareGenerator($gen_config); $ret = ''; $ret .= $this->start('div', array('id' => "$name:$ns.$directive")); $ret .= $this->start('label', array('for' => "$name:Yes_$ns.$directive")); $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); $ret .= $this->text(' Yes'); $ret .= $this->end('label'); $attr = array( 'type' => 'radio', 'name' => "$name" . "[$ns.$directive]", 'id' => "$name:Yes_$ns.$directive", 'value' => '1' ); if ($value === true) $attr['checked'] = 'checked'; if ($value === null) $attr['disabled'] = 'disabled'; $ret .= $this->elementEmpty('input', $attr); $ret .= $this->start('label', array('for' => "$name:No_$ns.$directive")); $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); $ret .= $this->text(' No'); $ret .= $this->end('label'); $attr = array( 'type' => 'radio', 'name' => "$name" . "[$ns.$directive]", 'id' => "$name:No_$ns.$directive", 'value' => '0' ); if ($value === false) $attr['checked'] = 'checked'; if ($value === null) $attr['disabled'] = 'disabled'; $ret .= $this->elementEmpty('input', $attr); $ret .= $this->end('div'); return $ret; } } // vim: et sw=4 sts=4
gpl-3.0
zorbathut/frames
src/core/detail.cpp
3141
/* Copyright 2014 Mandible Games This file is part of Frames. Please see the COPYING file for detailed licensing information. Frames is dual-licensed software. It is available under both a commercial license, and also 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. Frames 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 Frames. If not, see <http://www.gnu.org/licenses/>. */ #include "frames/detail.h" #include "frames/frame.h" #include "boost/static_assert.hpp" #include <vector> #include <cstdio> #include <cstdarg> // for the undefined types BOOST_STATIC_ASSERT(sizeof(float) == sizeof(int)); namespace Frames { namespace detail { const Vector AnchorLookup[ANCHOR_COUNT] = { Vector(0.f, 0.f), // TOPLEFT Vector(0.5f, 0.f), // TOPCENTER Vector(1.f, 0.f), // TOPRIGHT Vector(0.f, 0.5f), // CENTERLEFT Vector(0.5f, 0.5f), // CENTER Vector(1.f, 0.5f), // CENTERRIGHT Vector(0.f, 1.f), // BOTTOMLEFT Vector(0.5f, 1.f), // BOTTOMCENTER Vector(1.f, 1.f), // BOTTOMRIGHT // These constants are supposed to be Nil, but they're hardcoded to fix constant initialization order issues on some compilers. Can be fixed by putting them in a single file, in theory. Vector(0.f, detail::Reinterpret<float>(0xFFF00DFF)), // LEFT Vector(0.5f, detail::Reinterpret<float>(0xFFF00DFF)), // CENTERX Vector(1.f, detail::Reinterpret<float>(0xFFF00DFF)), // RIGHT Vector(detail::Reinterpret<float>(0xFFF00DFF), 0.f), // TOP Vector(detail::Reinterpret<float>(0xFFF00DFF), 0.5f), // CENTERY Vector(detail::Reinterpret<float>(0xFFF00DFF), 1.f), // BOTTOM }; int ClampToPowerOf2(int input) { input--; input = (input >> 1) | input; input = (input >> 2) | input; input = (input >> 4) | input; input = (input >> 8) | input; input = (input >> 16) | input; return input + 1; } bool FrameOrderSorter::operator()(const Frame *lhs, const Frame *rhs) const { if (lhs->zinternalImplementationGet() != rhs->zinternalImplementationGet()) return lhs->zinternalImplementationGet() < rhs->zinternalImplementationGet(); if (lhs->zinternalLayerGet() != rhs->zinternalLayerGet()) return lhs->zinternalLayerGet() < rhs->zinternalLayerGet(); // they're the same, but we want a consistent sort that won't result in Z-fighting return lhs->m_constructionOrder < rhs->m_constructionOrder; } bool LayoutIdSorter::operator()(const Layout *lhs, const Layout *rhs) const { // this is just for the sake of a consistent sort across executions return lhs->m_constructionOrder < rhs->m_constructionOrder; } } }
gpl-3.0
regueiro/easyRepair
src/Reports/src/es/regueiro/easyrepair/reports/ClientReport.java
20947
package es.regueiro.easyrepair.reports; import es.regueiro.easyrepair.model.client.Client; import es.regueiro.easyrepair.model.client.Vehicle; import es.regueiro.easyrepair.model.shared.Address; import es.regueiro.easyrepair.model.shared.Email; import es.regueiro.easyrepair.model.shared.Phone; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.dynamicreports.jasper.builder.JasperReportBuilder; import static net.sf.dynamicreports.report.builder.DynamicReports.*; import net.sf.dynamicreports.report.builder.column.TextColumnBuilder; import net.sf.dynamicreports.report.builder.component.ComponentBuilder; import net.sf.dynamicreports.report.builder.component.HorizontalListBuilder; import net.sf.dynamicreports.report.builder.component.MultiPageListBuilder; import net.sf.dynamicreports.report.builder.component.VerticalListBuilder; import net.sf.dynamicreports.report.builder.style.StyleBuilder; import net.sf.dynamicreports.report.constant.HorizontalAlignment; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.data.JRMapCollectionDataSource; public class ClientReport { private ClientReport() { } private static JRDataSource createClientListDataSource(List<Client> list) { Collection<Map<String, ?>> myColl = new ArrayList<Map<String, ?>>(); if (list != null) { for (Client client : list) { Map<String, Object> map = new HashMap<String, Object>(); if (client.getName() != null) { map.put("name", client.getName()); } else { map.put("name", ""); } if (client.getSurname() != null) { map.put("surname", client.getSurname()); } else { map.put("surname", ""); } if (client.getClientId() != null) { map.put("clientID", client.getClientId()); } else { map.put("clientID", ""); } if (client.getNif() != null) { map.put("nif", client.getNif().getNumber()); } else { map.put("nif", ""); } if (client.getNotes() != null) { map.put("notes", client.getNotes()); } else { map.put("notes", ""); } myColl.add(map); } } JRMapCollectionDataSource dataSource = new JRMapCollectionDataSource(myColl); return dataSource; } public static JasperReportBuilder generateClientReport(Client client) { JasperReportBuilder report = report(); if (client != null) { //init styles StyleBuilder columnStyle = stl.style(es.regueiro.easyrepair.reports.Templates.columnStyle) .setBorder(stl.pen1Point()); //configure report report .setTemplate(es.regueiro.easyrepair.reports.Templates.reportTemplate) .setColumnStyle(columnStyle) //band components .title( es.regueiro.easyrepair.reports.Templates.createTitleComponent(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("CLIENTNO"), client.getClientId()), cmp.multiPageList().setStyle(stl.style(10)).add( createClientComponent(client), createAddressComponent(client), createEmailComponent(client), createPhoneComponent(client), createVehicleComponent(client))) .pageFooter( es.regueiro.easyrepair.reports.Templates.footerComponent); } return report; } public static JasperReportBuilder generateClientListReport(List<Client> list) { JasperReportBuilder report = report(); if (list != null) { //init styles StyleBuilder columnStyle = stl.style(es.regueiro.easyrepair.reports.Templates.columnStyle) .setBorder(stl.pen1Point()); StyleBuilder subtotalStyle = stl.style(columnStyle) .bold(); //init columns TextColumnBuilder<Integer> rowNumberColumn = col.reportRowNumberColumn() .setFixedColumns(2) .setHorizontalAlignment(HorizontalAlignment.CENTER); TextColumnBuilder<String> nameColumn = col.column(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NAME"), "name", type.stringType()); TextColumnBuilder<String> surnameColumn = col.column(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("SURNAME"), "surname", type.stringType()); TextColumnBuilder<String> clientIDColumn = col.column(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("CLIENTID"), "clientID", type.stringType()); TextColumnBuilder<String> nifColumn = col.column(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NIF"), "nif", type.stringType()); //configure report report .setTemplate(es.regueiro.easyrepair.reports.Templates.reportTemplate) .setColumnStyle(columnStyle) .setSubtotalStyle(subtotalStyle) //columns //band components .title( es.regueiro.easyrepair.reports.Templates.createTitleComponent(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("CLIENTLIST"), "")) .columns( rowNumberColumn, clientIDColumn, nameColumn, surnameColumn, nifColumn) .columnGrid( rowNumberColumn, clientIDColumn, nameColumn, surnameColumn, nifColumn) .pageFooter( es.regueiro.easyrepair.reports.Templates.footerComponent) .setDataSource(createClientListDataSource(list)); } return report; } private static ComponentBuilder<?, ?> createClientComponent(Client client) { HorizontalListBuilder list = cmp.horizontalList().setBaseStyle(stl.style().setTopBorder(stl.pen1Point()).setLeftPadding(10)); if (client != null) { if (client.getClientId() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("CLIENTID"), client.getClientId()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("CLIENTID"), ""); } if (client.getName() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NAME"), client.getName()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NAME"), ""); } if (client.getSurname() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("SURNAME"), client.getSurname()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("SURNAME"), ""); } if (client.getNif() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NIF"), client.getNif().getNumber()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NIF"), ""); } if (client.getNotes() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NOTES"), client.getNotes()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NOTES"), ""); } } return cmp.verticalList( cmp.text(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("CLIENT")).setStyle(es.regueiro.easyrepair.reports.Templates.boldStyle), list); } private static ComponentBuilder<?, ?> createAddressComponent(Client client) { MultiPageListBuilder mainList = cmp.multiPageList(); for (Address a : client.getAddress()) { HorizontalListBuilder list = cmp.horizontalList().setBaseStyle(stl.style().setTopBorder(stl.pen1Point()).setLeftPadding(10)); if (a.getLabel() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("LABEL"), a.getLabel()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("LABEL"), ""); } if (a.getStreet() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("STREET"), a.getStreet()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("STREET"), ""); } if (a.getCity() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("CITY"), a.getCity()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("CITY"), ""); } if (a.getProvince() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("PROVINCE"), a.getProvince()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("PROVINCE"), ""); } if (a.getPostalCode() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("POSTALCODE"), a.getPostalCode()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("POSTALCODE"), ""); } if (a.getCountry() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("COUNTRY"), a.getCountry()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("COUNTRY"), ""); } if (a.getNotes() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NOTES"), a.getNotes()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NOTES"), ""); } mainList.add(list, cmp.verticalGap(5)); } if (client.getAddress() != null && !client.getAddress().isEmpty()) { return cmp.verticalList( cmp.text(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("ADDRESS")).setStyle(es.regueiro.easyrepair.reports.Templates.boldStyle), mainList); } else { return cmp.filler(); } } private static ComponentBuilder<?, ?> createEmailComponent(Client client) { MultiPageListBuilder mainList = cmp.multiPageList(); for (Email e : client.getEmail()) { HorizontalListBuilder list = cmp.horizontalList().setBaseStyle(stl.style().setTopBorder(stl.pen1Point()).setLeftPadding(10)); if (e.getLabel() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("LABEL"), e.getLabel()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("LABEL"), ""); } if (e.getAddress() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("EMAILADDRESS"), e.getAddress()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("EMAILADDRESS"), ""); } if (e.getNotes() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NOTES"), e.getNotes()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NOTES"), ""); } mainList.add(list, cmp.verticalGap(5)); } if (client.getEmail() != null && !client.getEmail().isEmpty()) { return cmp.verticalList( cmp.text(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("EMAIL")).setStyle(es.regueiro.easyrepair.reports.Templates.boldStyle), mainList); } else { return cmp.filler(); } } private static ComponentBuilder<?, ?> createPhoneComponent(Client client) { MultiPageListBuilder mainList = cmp.multiPageList(); for (Phone p : client.getPhone()) { HorizontalListBuilder list = cmp.horizontalList().setBaseStyle(stl.style().setTopBorder(stl.pen1Point()).setLeftPadding(10)); if (p.getLabel() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("LABEL"), p.getLabel()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("LABEL"), ""); } if (p.getNumber() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NUMBER"), p.getNumber()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NUMBER"), ""); } if (p.getNotes() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NOTES"), p.getNotes()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NOTES"), ""); } mainList.add(list, cmp.verticalGap(5)); } if (client.getPhone() != null && !client.getPhone().isEmpty()) { return cmp.verticalList( cmp.text(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("PHONE")).setStyle(es.regueiro.easyrepair.reports.Templates.boldStyle), mainList); } else { return cmp.filler(); } } private static ComponentBuilder<?, ?> createVehicleComponent(Client client) { MultiPageListBuilder mainList = cmp.multiPageList(); for (Vehicle v : client.getVehicles()) { HorizontalListBuilder list = cmp.horizontalList().setBaseStyle(stl.style().setTopBorder(stl.pen1Point()).setLeftPadding(10)); if (v.getRegistration() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("REGISTRATION"), v.getRegistration()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("REGISTRATION"), ""); } if (v.getMake() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("MAKE"), v.getMake()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("MAKE"), ""); } if (v.getModel() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("MODEL"), v.getModel()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("MODEL"), ""); } if (v.getYear() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("YEAR"), v.getYear()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("YEAR"), ""); } if (v.getVin() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("VIN"), v.getVin()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("VIN"), ""); } if (v.getColour() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("COLOUR"), v.getColour()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("COLOUR"), ""); } if (v.getType() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("TYPE"), v.getType()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("TYPE"), ""); } if (v.getFuel() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("FUEL"), v.getFuel()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("FUEL"), ""); } if (v.getInsuranceCompany() != null && v.getInsuranceCompany().getName() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("INSURANCECOMPANY"), v.getInsuranceCompany().getName()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("INSURANCECOMPANY"), ""); } if (v.getInsuranceNumber() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("INSURANCENUMBER"), v.getInsuranceNumber()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("INSURANCENUMBER"), ""); } if (v.getNotes() != null) { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NOTES"), v.getNotes()); } else { addAttribute(list, java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("NOTES"), ""); } mainList.add(list, cmp.verticalGap(5)); } if (client.getVehicles() != null && !client.getVehicles().isEmpty()) { return cmp.verticalList( cmp.text(java.util.ResourceBundle.getBundle("es/regueiro/easyrepair/reports/Bundle").getString("VEHICLE")).setStyle(es.regueiro.easyrepair.reports.Templates.boldStyle), mainList); } else { return cmp.filler(); } } private static void addAttribute(HorizontalListBuilder list, String label, String value) { if (value != null) { list.add(cmp.text(label + ":").setFixedColumns(15).setStyle(es.regueiro.easyrepair.reports.Templates.boldStyle), cmp.text(value)).newRow(); } } }
gpl-3.0
duaneloh/Dragonfly
utils/py_src/read_config.py
8584
'''Module containing various functions used to parse configuration files''' from __future__ import print_function import logging import os from collections import OrderedDict from six.moves import configparser import numpy as np class MultiOrderedDict(OrderedDict): def __init__(self): super(MultiOrderedDict, self).__init__() def __setitem__(self, key, value): if isinstance(value, list) and key in self: self[key].extend(value) else: super(MultiOrderedDict, self).__setitem__(key, value) def get_param(config_file, section, tag): '''Get config file parameter Use get_filename() for getting file names rather than this general function ''' config = configparser.ConfigParser() config.read(config_file) return config.get(section, tag) def get_multi_params(config_file, section, tag): '''Gets parameter defined multiple times Returns list of all values if more than one ''' config = configparser.RawConfigParser(dict_type=MultiOrderedDict) config.read(config_file) return config.get(section, tag) def get_filename(config_file, section, tag): '''Get filename from config file Resolves ::: symlinks ''' param = get_param(config_file, section, tag) if ":::" in param: [subsec, subtag] = param.split(":::") param = get_filename(config_file, subsec, subtag) return param def get_detector_config(config_file, show=False): '''Get detector parameters from config file Generates and returns a params dictionary ''' config = configparser.ConfigParser() config.read(config_file) params = OrderedDict() params['wavelength'] = config.getfloat('parameters', 'lambda') params['detd'] = config.getfloat('parameters', 'detd') detstr = config.get('parameters', 'detsize').split(' ') if len(detstr) == 1: params['dets_x'] = int(detstr[0]) params['dets_y'] = int(detstr[0]) params['detsize'] = int(detstr[0]) else: params['dets_x'] = int(detstr[0]) params['dets_y'] = int(detstr[1]) params['detsize'] = max(params['dets_x'], params['dets_y']) params['pixsize'] = config.getfloat('parameters', 'pixsize') params['stoprad'] = config.getfloat('parameters', 'stoprad') params['polarization'] = config.get('parameters', 'polarization') # Optional arguments try: params['ewald_rad'] = config.getfloat('parameters', 'ewald_rad') except configparser.NoOptionError: params['ewald_rad'] = params['detd'] / params['pixsize'] try: params['mask_fname'] = config.get('make_detector', 'in_mask_file') except (configparser.NoOptionError, configparser.NoSectionError): params['mask_fname'] = None try: detcstr = config.get('make_detector', 'center').split(' ') if len(detstr) == 1: params['detc_x'] = int(detcstr[0]) params['detc_y'] = int(detcstr[0]) else: params['detc_x'] = int(detcstr[0]) params['detc_y'] = int(detcstr[1]) except (configparser.NoOptionError, configparser.NoSectionError): params['detc_x'] = (params['dets_x']-1)/2. params['detc_y'] = (params['dets_y']-1)/2. if show: for key, val in params.items(): #logging.info('{:<15}:{:>10}'.format(key, val)) logging.info('%15s:%-10s', key, str(val)) return params def compute_q_params(det_dist, dets_x, dets_y, pix_size, in_wavelength, ewald_rad, show=False): """ Resolution computed in inverse Angstroms, crystallographer's convention In millimeters: det_dist, pix_size In Angstroms: in_wavelength In pixels: dets_x, dets_y """ params = OrderedDict() half_x = pix_size * int((dets_x-1)/2) half_y = pix_size * int((dets_y-1)/2) params['max_angle'] = np.arctan(np.sqrt(half_x**2 + half_y**2) / det_dist) params['min_angle'] = np.arctan(pix_size / det_dist) params['q_max'] = 2. * np.sin(0.5 * params['max_angle']) / in_wavelength params['q_sep'] = 2. * np.sin(0.5 * params['min_angle']) / in_wavelength\ * (det_dist / ewald_rad / pix_size) params['fov_in_A'] = 1. / params['q_sep'] params['half_p_res'] = 0.5 / params['q_max'] if show: for key, val in params.items(): logging.info('%15s:%10.4f', key, val) logging.info('%15s:%10.4f', 'voxel-length or reciprocal volume', params['fov_in_A']/params['half_p_res']) return params def compute_polarization(polarization, polx, poly, norm): '''Returns polarization given pixel coordinates and type Parameters: polarization: Can be 'x', 'y' or 'none' polx, poly: x and y coordinates of pixel norm: Distance of pixel from interaction point ''' if polarization.lower() == 'x': return 1. - (polx**2)/(norm**2) elif polarization.lower() == 'y': return 1. - (poly**2)/(norm**2) elif polarization.lower() == 'none': return 1. - (polx**2 + poly**2)/(2*norm**2) logging.info('Please set the polarization direction as x, y or none!') return None def read_gui_config(gui, section): ''' Read config file parameters needed for GUI operation ''' # Defaults gui.polar_params = ['5', '60', '2.', '10.'] gui.class_fname = 'my_classes.dat' gui.stack_size = 0 # Photons file list try: pfile = get_filename(gui.config_file, section, 'in_photons_file') print('Using in_photons_file: %s' % pfile) gui.photons_list = [pfile] except configparser.NoOptionError: plist = get_filename(gui.config_file, section, 'in_photons_list') print('Using in_photons_list: %s' % plist) with open(plist, 'r') as fptr: gui.photons_list = [line.rstrip() for line in fptr.readlines()] gui.photons_list = [line for line in gui.photons_list if line] gui.num_files = len(gui.photons_list) # Detector file list try: dfile = get_filename(gui.config_file, section, 'in_detector_file') print('Using in_detector_file: %s' % dfile) gui.det_list = [dfile] except configparser.NoOptionError: dlist = get_filename(gui.config_file, section, 'in_detector_list') print('Using in_detector_list: %s' % dlist) with open(dlist, 'r') as fptr: gui.det_list = [line.rstrip() for line in fptr.readlines()] gui.det_list = [line for line in gui.det_list if line] if len(gui.det_list) > 1 and len(gui.det_list) != len(gui.photons_list): raise ValueError('Different number of detector and photon files') # Only used with old detector file try: prm = get_detector_config(gui.config_file) gui.ewald_rad = prm['ewald_rad'] gui.detd = prm['detd']/prm['pixsize'] except (configparser.NoOptionError, configparser.NoSectionError): gui.ewald_rad = None gui.detd = None # Output folder try: output_folder = get_filename(gui.config_file, section, 'output_folder') except configparser.NoOptionError: output_folder = 'data/' gui.output_folder = os.path.realpath(output_folder) # For specific sections if section == 'emc': # Frame blacklist try: gui.blacklist = np.loadtxt(get_filename(gui.config_file, 'emc', 'blacklist_file'), dtype='u1') except configparser.NoOptionError: gui.blacklist = None # Log file gui.log_fname = get_filename(gui.config_file, 'emc', 'log_file') # Need scaling try: gui.need_scaling = bool(int(get_param(gui.config_file, 'emc', 'need_scaling'))) except configparser.NoOptionError: gui.need_scaling = False elif section == 'classifier': # Polar conversion parameters try: gui.polar_params = get_param(gui.config_file, 'classifier', 'polar_params').split() except configparser.NoOptionError: gui.polar_params = ['5', '60', '2.', '10.'] # Class list file try: gui.class_fname = get_filename(gui.config_file, 'classifier', 'in_class_file') except configparser.NoOptionError: gui.class_fname = 'my_classes.dat' # Check whether slices try: gui.stack_size = int(get_param(gui.config_file, 'classifier', 'stack_size')) except configparser.NoOptionError: gui.stack_size = 0
gpl-3.0
janus57/PHPBoost_v3c
kernel/framework/io/filesystem/folder.class.php
3280
<?php import('io/filesystem/file_system_element'); import('io/filesystem/file'); class Folder extends FileSystemElement { function Folder($path, $whenopen = OPEN_AFTER) { parent::FileSystemElement(rtrim($path, '/')); if (@file_exists($this->path)) { if (!@is_dir($this->path)) { return false; } if ($whenopen == OPEN_NOW) { $this->open(); } } else if (!@mkdir($this->path)) { return false; } return true; } function open() { parent::open(); $this->files = $this->folders = array(); if ($dh = @opendir($this->path)) { while (!is_bool($fse_name = readdir($dh))) { if ($fse_name == '.' || $fse_name == '..') { continue; } if (is_file($this->path . '/' . $fse_name)) { $this->files[] = new File($this->path . '/' . $fse_name); } else { $this->folders[] = new Folder($this->path . '/' . $fse_name); } } closedir($dh); } } function get_files($regex = '') { parent::get(); $ret = array(); if (empty($regex)) { foreach ($this->files as $file) { $ret[] = $file; } } else { foreach ($this->files as $file) { if (preg_match($regex, $file->get_name())) { $ret[] = $file; } } } return $ret; } function get_folders($regex = '') { parent::get(); if (empty($regex)) { $ret = array(); foreach ($this->folders as $folder) { $ret[] = $folder; } return $ret; } else { $ret = array(); foreach ($this->folders as $folder) { if (preg_match($regex, $folder->get_name())) { $ret[] = $folder; } } return $ret; } } function get_first_folder() { parent::get(); if (isset($this->folders[0])) { return $this->folders[0]; } else { return null; } } function get_all_content() { return array_merge($this->get_files(), $this->get_folders()); } function delete() { $this->open(); $fs = array_merge($this->files, $this->folders); foreach ($fs as $fse) { $fse->delete(); } if (!@rmdir($this->path)) { return false; } return true; } ## Private Attributes ## var $files = array(); var $folders = array(); } ?>
gpl-3.0
yongs2/mts-project
mts/src/main/java/com/devoteam/srit/xmlloader/core/coding/binary/BooleanField.java
1933
/* * Copyright 2012 Devoteam http://www.devoteam.com * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * * This file is part of Multi-Protocol Test Suite (MTS). * * Multi-Protocol Test Suite (MTS) 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. * * Multi-Protocol Test Suite (MTS) 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 Multi-Protocol Test Suite (MTS). * If not, see <http://www.gnu.org/licenses/>. * */ package com.devoteam.srit.xmlloader.core.coding.binary; import gp.utils.arrays.Array; import gp.utils.arrays.SupArray; import org.dom4j.Element; import com.devoteam.srit.xmlloader.core.utils.Utils; /** * * @author indiaye */ public class BooleanField extends FieldAbstract { public BooleanField() { } public BooleanField(Element rootXML) { super(rootXML); this.length = 1; } @Override public void setValue(String value, int offset, SupArray array) throws Exception { this.offset = offset; boolean bool = Utils.parseBoolean(value, this.name); if (bool) { array.setBit(offset, 1); } else { array.setBit(offset, 0); } } @Override public String getValue(Array array) throws Exception { return Integer.toString(array.getBits(this.offset, this.length)); } @Override public FieldAbstract clone() { BooleanField newField = new BooleanField(); newField.copyToClone(this); return newField; } }
gpl-3.0
adhokshajmishra/positron
positron/emulator/register.hpp
979
#ifndef REGISTER_H #define REGISTER_H #include <cstdint> #include <stdexcept> #include <type_traits> enum RegisterName { EAX = 0, EBX, ECX, EDX, ESP, EBP, EIP, FLG, DR0, DR1, DR2, DR3, DR4, DR5, DR6, DR7, DR8, DR9, DR10, DR11, DR12, DR13, DR14, DR15, CR0, CR1, CR2, CR3, CR4, CR5, CR6, CR7 }; class Register { private: uint32_t data; public: Register(); template<typename T> T get() { if (std::is_integral<T>::value) { return static_cast<T>(data); } else { std::runtime_error e("Requested data type is not integral."); throw e; } } template<typename T> void set(T& value) { if (std::is_integral<T>::value) { data = static_cast<uint32_t>(value); } else { std::runtime_error e("Requested data type is not integral."); throw e; } } }; #endif // REGISTER_H
gpl-3.0
seung-lab/znn-release
zi/vl/detail/householder.hpp
11929
// // Copyright (C) 2010 Aleksandar Zlateski <[email protected]> // ---------------------------------------------------------- // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #ifndef ZI_VL_DETAIL_HOUSEHOLDER_HPP #define ZI_VL_DETAIL_HOUSEHOLDER_HPP 1 #include <zi/utility/non_copyable.hpp> #include <zi/vl/mat.hpp> #include <zi/vl/detail/enable_if.hpp> #include <vector> #include <iostream> namespace zi { namespace vl { template< class T, std::size_t N > inline T left_householder_iteration( mat< T, N >& A, mat< T, N >& U, const std::size_t i ) { static vec< T, N > d; T l = static_cast< T >( 0 ); T s = static_cast< T >( 0 ); for ( std::size_t j = i; j < N; ++j ) { d[ j ] = A.at( j, i ); s += std::abs( d[ j ] ); } if ( s <= std::numeric_limits< T >::epsilon() ) { return 0; } T sinv = static_cast< T >( 1 ) / s; for ( std::size_t j = i; j < N; ++j ) { d[ j ] *= sinv; l += d[ j ] * d[ j ]; } T dl = std::sqrt( l ); if ( d[ i ] > 0 ) { dl = -dl; } l -= d[ i ] * dl; d[ i ] -= dl; l = static_cast< T >( 1 ) / l; for ( std::size_t j = i + 1; j < N; ++j ) { T dr = static_cast< T >( 0 ); for ( std::size_t k = i; k < N; ++k ) { dr += d[ k ] * A.at( k, j ); } dr *= l; for ( std::size_t k = i; k < N; ++k ) { A.at( k, j ) -= dr * d[ k ]; } } for ( std::size_t j = 0; j < N; ++j ) { T dr = static_cast< T >( 0 ); for ( std::size_t k = i; k < N; ++k ) { dr += d[ k ] * U.at( j, k ); } dr *= l; for ( std::size_t k = i; k < N; ++k ) { U.at( j, k ) -= dr * d[ k ]; } } std::cout << "A = \n" << A << "\n----------------\n" << "d * s = " << d << " ::: " << (s*dl) << " :: " << s << " :: " << dl << "\n" << "d = " << d << " :: " << dot( d, d ) << "\n\n"; return s * dl; } template< class T, std::size_t N > inline T right_householder_iteration( mat< T, N >& A, mat< T, N >& V, const std::size_t i ) { static vec< T, N > d; T l = static_cast< T >( 0 ); T s = static_cast< T >( 0 ); for ( std::size_t j = i + 1; j < N; ++j ) { d[ j ] = A.at( i, j ); s += std::abs( d[ j ] ); } if ( s <= std::numeric_limits< T >::epsilon() ) { return 0; } T sinv = static_cast< T >( 1 ) / s; for ( std::size_t j = i + 1; j < N; ++j ) { d[ j ] *= sinv; l += d[ j ] * d[ j ]; } T dl = std::sqrt( l ); if ( d[ i + 1 ] > 0 ) { dl = -dl; } l = d[ i + 1 ] * dl - l; d[ i + 1 ] -= dl; l = static_cast< T >( 1 ) / l; for ( std::size_t j = i + 1; j < N; ++j ) { T dr = static_cast< T >( 0 ); for ( std::size_t k = i + 1; k < N; ++k ) { dr += d[ k ] * A.at( j, k ); } dr *= l; for ( std::size_t k = i + 1; k < N; ++k ) { A.at( j, k ) += dr * d[ k ]; } } for ( std::size_t j = 0; j < N; ++j ) { T dr = static_cast< T >( 0 ); for ( std::size_t k = i + 1; k < N; ++k ) { dr += d[ k ] * V.at( j, k ); } dr *= l; for ( std::size_t k = i + 1; k < N; ++k ) { V.at( j, k ) += dr * d[ k ]; } } return s * dl; } template< class T, std::size_t N, std::size_t M > inline typename detail::enable_if_c< ( M+1 == N ), typename detail::enable_if< is_floating_point< T >, bool >::type >::type bidiagonalize( mat< T, N >& A, mat< T, N >& U, mat< T, N >& V, vec< T, N >& diagonal, vec< T, M >& super_diagonal ) { U = mat< T, N >::eye; V = mat< T, N >::eye; for ( std::size_t i = 0; i < N; ++i ) { diagonal[ i ] = left_householder_iteration( A, U, i ); if ( i < N - 1 ) { super_diagonal[ i ] = right_householder_iteration( A, V, i ); } std::cout << "after iteration: " << i << "\n============\n" << ( U * A * trans( V ) ) << "\n====\n" << super_diagonal << "\n\n"; } A = mat< T, N >::zero; for ( std::size_t i = 0; i < N; ++i ) { A.at( i, i ) = diagonal[ i ]; if ( i < N - 1 ) { A.at( i, i+1 ) = super_diagonal[ i ]; } } return true; } template< class T, std::size_t N > inline bool householder2( mat< T, N >& Q, mat< T, N >& R, typename detail::enable_if< is_floating_point< T > >::type* = 0 ) { Q = mat< T, N >::eye; for ( std::size_t i = 0; i < 1; ++i ) { std::cout << "iter " << i << " got back " << left_householder_iteration( R, Q, i ); std::cout << " and r[i][i] = " << R.at( i, i ) << "\n\n"; } return true; } template< class T, std::size_t N > inline bool householder3( mat< T, N >& Q, mat< T, N >& R, typename detail::enable_if< is_floating_point< T > >::type* = 0 ) { Q = mat< T, N >::eye; for ( std::size_t i = 0; i < N - 1; ++i ) { std::cout << "iter " << i << " got back " << right_householder_iteration( R, Q, i ); std::cout << " and r[i][i + 1] = " << R.at( i, i + 1 ) << "\n----------\n" << Q << "\n--------\n " << R << "\n\n"; } return true; } template< class T, std::size_t N > inline bool householder( mat< T, N >& Q, mat< T, N >& R, bool init_q_to_eye = true, typename detail::enable_if< is_floating_point< T > >::type* = 0 ) { vec< T, N > d; Q = mat< T, N >::eye; if ( init_q_to_eye ) { Q = mat< T, N >::eye; } for ( std::size_t i = 0; i < N-1; ++i ) { T l = static_cast< T >( 0 ); for ( std::size_t j = i; j < N; ++j ) { d[ j ] = R.at( j, i ); l += d[ j ] * d[ j ]; } if ( l <= std::numeric_limits< T >::epsilon() ) { return false; } T dl = std::sqrt( l ); l += l - d[ i ] * dl * 2; d[ i ] -= dl; if ( l <= std::numeric_limits< T >::epsilon() ) { return false; } l = static_cast< T >( 2 ) / l; //R.at( i, i ) = d[ i ]; for ( std::size_t j = i; j < N; ++j ) { T dr = static_cast< T >( 0 ); for ( std::size_t k = i; k < N; ++k ) { dr += d[ k ] * R.at( k, j ); } dr *= l; for ( std::size_t k = i; k < N; ++k ) { R.at( k, j ) -= dr * d[ k ]; } } for ( std::size_t j = 0; j < N; ++j ) { T dr = static_cast< T >( 0 ); for ( std::size_t k = i; k < N; ++k ) { dr += d[ k ] * Q.at( j, k ); } dr *= l; for ( std::size_t k = i; k < N; ++k ) { Q.at( j, k ) -= dr * d[ k ]; } } } return true; } template< class T, std::size_t N > inline bool left_householder( mat< T, N >& R, mat< T, N >& Q, bool init_q_to_eye = true, typename detail::enable_if< is_floating_point< T > >::type* = 0 ) { vec< T, N > d; if ( init_q_to_eye ) { Q = mat< T, N >::eye; } for ( std::size_t i = 0; i < N-1; ++i ) { T l = static_cast< T >( 0 ); for ( std::size_t j = i; j < N; ++j ) { d[ j ] = R.at( i, j ); l += d[ j ] * d[ j ]; } if ( l <= std::numeric_limits< T >::epsilon() ) { return false; } T dl = std::sqrt( l ); l -= d[ i ] * dl; d[ i ] -= dl; if ( l <= std::numeric_limits< T >::epsilon() ) { return false; } l = static_cast< T >( 1 ) / l; for ( std::size_t j = i; j < N; ++j ) { T dr = static_cast< T >( 0 ); for ( std::size_t k = i; k < N; ++k ) { dr += d[ k ] * R.at( j, k ); } dr *= l; for ( std::size_t k = i; k < N; ++k ) { R.at( j, k ) -= dr * d[ k ]; } } for ( std::size_t j = 0; j < N; ++j ) { T dr = static_cast< T >( 0 ); for ( std::size_t k = i; k < N; ++k ) { dr += d[ k ] * Q.at( k, j ); } dr *= l; for ( std::size_t k = i; k < N; ++k ) { Q.at( k, j ) -= dr * d[ k ]; } } } return true; } template< class T, std::size_t N > inline bool householder_inverse( mat< T, N >& A, typename detail::enable_if< is_floating_point< T > >::type* = 0 ) { mat< T, N > Q1; mat< T, N > Q2 = mat< T, N >::eye; transpose( A ); if ( !left_householder( A, Q1 ) ) { return false; } vec< T, N > d; std::cout << A << "\n-------------OLDA\n"; std::cout << Q1 * A << "\n-------------\n"; for ( std::size_t idx = 0, i = 0; i < N-1; ++i, ++idx ) { T l = A.at( i, i ); if ( std::fabs( l ) <= std::numeric_limits< T >::epsilon() ) { return false; } l = static_cast< T >( 1 ) / l; for ( std::size_t j = i + 1; j < N; ++j ) { T dq = A.at( j, i ) * l; A.at( j, i ) = 0; for ( std::size_t k = 0; k < N; ++k ) { Q2.at( k, j ) += Q2.at( k, i ) * dq; } } } std::cout << A << "\n-------------A\n"; std::cout << Q2 << "\n-------------Q2\n"; std::cout << ( Q2 * A) << "\n-------------inv( q2 ) a\n"; std::cout << ( Q1 * ( trans( Q2 * A ) ) ) << "\n-------------\n"; return true; } template< class T, std::size_t N > inline void householder_just_R( mat< T, N >& R, typename detail::enable_if< is_floating_point< T > >::type* = 0 ) { vec< T, N > d; for ( std::size_t i = 0; i < N-1; ++i ) { T l = static_cast< T >( 0 ); for ( std::size_t j = i; j < N; ++j ) { d[ j ] = R.at( j, i ); l += d[ j ] * d[ j ]; } if ( l > std::numeric_limits< T >::epsilon() ) { T dl = std::sqrt( l ); l += l - d[ i ] * dl * 2; d[ i ] -= dl; if ( l > std::numeric_limits< T >::epsilon() ) { l = static_cast< T >( 2 ) / l; for ( std::size_t j = i; j < N; ++j ) { T dr = static_cast< T >( 0 ); for ( std::size_t k = i; k < N; ++k ) { dr += d[ k ] * R.at( k, j ); } dr *= l; for ( std::size_t k = i; k < N; ++k ) { R.at( k, j ) -= dr * d[ k ]; } } } } } } } // namespace vl } // namespace zi #endif
gpl-3.0
simonpatrick/stepbystep-java
java8samples/src/main/java/io/hedwing/java8samples/designpattern/observer/Aliens.java
329
package io.hedwing.java8samples.designpattern.observer; // BEGIN Aliens public class Aliens implements LandingObserver { @Override public void observeLanding(String name) { if (name.contains("Apollo")) { System.out.println("They're distracted, lets invade earth!"); } } } // END Aliens
gpl-3.0
magic3org/magic3
widgets/admin_main/include/container/admin_mainSearchwordlogWidgetContainer.php
19674
<?php /** * コンテナクラス * * PHP versions 5 * * LICENSE: This source file is licensed under the terms of the GNU General Public License. * * @package Magic3 Framework * @author 株式会社 毎日メディアサービス * @copyright Copyright 2016-2021 株式会社 毎日メディアサービス. * @license http://www.gnu.org/copyleft/gpl.html GPL License * @version SVN: $Id$ * @link http://www.m-media.co.jp */ require_once($gEnvManager->getCurrentWidgetContainerPath() . '/admin_mainConditionBaseWidgetContainer.php'); require_once($gEnvManager->getCurrentWidgetDbPath() . '/admin_mainDb.php'); require_once($gEnvManager->getCurrentWidgetDbPath() . '/admin_serverDb.php'); class admin_mainSearchwordlogWidgetContainer extends admin_mainConditionBaseWidgetContainer { private $db; // DB接続オブジェクト private $serverDb; // DB接続オブジェクト private $serialNo; // シリアルNo private $serialArray = array(); // 表示されているコンテンツシリアル番号 private $clientIp; // クライアントのIPアドレス private $path; // アクセスパス private $logOrder; // 検索語の表示順 private $logOrderArray; // 検索語の表示順タイプ private $showMessage; // メッセージ画面かどうか private $message; // 表示メッセージ private $server; // 指定サーバ const DEFAULT_LIST_COUNT = 30; // 最大リスト表示数 const LINK_PAGE_COUNT = 10; // リンクページ数 const FLAG_ICON_DIR = '/images/system/flag/'; // 国旗アイコンディレクトリ const BROWSER_ICON_DIR = '/images/system/browser/'; // ブラウザアイコンディレクトリ const ICON_SIZE = 16; // アイコンのサイズ // const DEFAULT_LOG_LEVEL = '0'; // デフォルトのログレベル // const DEFAULT_LOG_STATUS = '1'; // デフォルトのログステータス const DEFAULT_LOG_ORDER = '0'; // デフォルトの検索語表示順 const DEFAULT_ACCESS_PATH = 'index'; // デフォルトのアクセスパス(PC用アクセスポイント) const ACCESS_PATH_ALL = '_all'; // アクセスパスすべて選択 const ACCESS_PATH_OTHER = '_other'; // アクセスパスその他 /** * コンストラクタ */ function __construct() { // 親クラスを呼び出す parent::__construct(); // DB接続オブジェクト作成 $this->db = new admin_mainDb(); $this->serverDb = new admin_serverDb(); // 検索語の表示順タイプ $this->logOrderArray = array( array( 'name' => '最新', 'value' => '0'), array( 'name' => '頻度高', 'value' => '1')); } /** * テンプレートファイルを設定 * * _assign()でデータを埋め込むテンプレートファイルのファイル名を返す。 * 読み込むディレクトリは、「自ウィジェットディレクトリ/include/template」に固定。 * * @param RequestManager $request HTTPリクエスト処理クラス * @param object $param 任意使用パラメータ。そのまま_assign()に渡る * @return string テンプレートファイル名。テンプレートライブラリを使用しない場合は空文字列「''」を返す。 */ function _setTemplate($request, &$param) { // サーバ指定されている場合は接続先DBを変更 $this->server = $request->trimValueOf(M3_REQUEST_PARAM_SERVER); if (!empty($this->server)){ // 設定データを取得 $ret = $this->serverDb->getServerById($this->server, $row); if ($ret){ $dbDsn = $row['ts_db_connect_dsn']; // DB接続情報 $dbAccount = $row['ts_db_account']; // DB接続アカウント $dbPassword = $row['ts_db_password'];// DB接続パスワード // テスト用DBオブジェクト作成 $ret = $this->db->openLocalDb($dbDsn, $dbAccount, $dbPassword);// 接続先を変更 } if (!$ret){ // サーバに接続できない場合 $this->showMessage = true; // メッセージ画面かどうか $this->message = 'サーバに接続できません'; return 'message.tmpl.html'; } } $task = $request->trimValueOf('task'); if ($task == 'searchwordlog_detail'){ // 詳細画面 return 'searchwordlog_detail.tmpl.html'; } else { // 一覧画面 return 'searchwordlog.tmpl.html'; } } /** * テンプレートにデータ埋め込む * * _setTemplate()で指定したテンプレートファイルにデータを埋め込む。 * * @param RequestManager $request HTTPリクエスト処理クラス * @param object $param 任意使用パラメータ。_setTemplate()と共有。 * @param なし */ function _assign($request, &$param) { if ($this->showMessage){ // メッセージ画面かどうか $this->setMsg(self::MSG_APP_ERR, $this->message); return; } $task = $request->trimValueOf('task'); if ($task == 'searchwordlog_detail'){ // 詳細画面 return $this->createDetail($request); } else { // 一覧画面 return $this->createList($request); } } /** * 一覧画面作成 * * @param RequestManager $request HTTPリクエスト処理クラス * @param なし */ function createList($request) { $this->clientIp = $this->gRequest->trimServerValueOf('REMOTE_ADDR'); // クライアントのIPアドレス $act = $request->trimValueOf('act'); $this->path = $request->trimValueOf('path'); // アクセスパス if (empty($this->path)) $this->path = self::DEFAULT_ACCESS_PATH; $this->logOrder = $request->trimValueOf('logorder');// 検索語の表示順 if ($this->logOrder == '') $this->logOrder = self::DEFAULT_LOG_ORDER; // 表示条件 $maxListCount = $request->trimIntValueOf('viewcount', '0'); if (empty($maxListCount)) $maxListCount = self::DEFAULT_LIST_COUNT; // 表示項目数 $pageNo = $request->trimIntValueOf(M3_REQUEST_PARAM_PAGE_NO, '1'); // ページ番号 // 表示するログのタイプを設定 $pathParam = $this->path; if ($pathParam == self::ACCESS_PATH_ALL){ $pathParam = NULL; } else if ($pathParam == self::ACCESS_PATH_OTHER){ // その他のパス $pathParam = ''; } switch ($this->logOrder){ case 0: // 最新からログを取得 default: $this->tmpl->setAttribute('show_last_log', 'visibility', 'visible');// 最新から検索語を表示 // 総数を取得 $totalCount = $this->db->getSearchWordLogCount($pathParam); break; case 1: // 頻度高 $this->tmpl->setAttribute('show_sum_log', 'visibility', 'visible');// 検索頻度順に検索語を表示 // 総数を取得 $totalCount = $this->db->getSearchWordSumCount($pathParam); break; } /* // 表示するページ番号の修正 $pageCount = (int)(($totalCount -1) / $viewCount) + 1; // 総ページ数 if ($pageNo < 1) $pageNo = 1; if ($pageNo > $pageCount) $pageNo = $pageCount; $startNo = ($pageNo -1) * $viewCount +1; // 先頭の行番号 $endNo = $pageNo * $viewCount > $totalCount ? $totalCount : $pageNo * $viewCount;// 最後の行番号 $this->startNo = $startNo; // 先頭の項目番号 */ // ページング計算 $this->calcPageLink($pageNo, $totalCount, $maxListCount); /* // ページング用リンク作成 $pageLink = ''; if ($pageCount > 1){ // ページが2ページ以上のときリンクを作成 for ($i = 1; $i <= $pageCount; $i++){ if ($i > self::MAX_PAGE_COUNT) break; // 最大ページ数以上のときは終了 if ($i == $pageNo){ $link = '&nbsp;' . $i; } else { $link = '&nbsp;<a href="#" onclick="selpage(\'' . $i . '\');return false;">' . $i . '</a>'; } $pageLink .= $link; } }*/ // ページングリンク作成 $pageLink = $this->createPageLink($pageNo, self::LINK_PAGE_COUNT, ''/*リンク作成用(未使用)*/, 'selectPage($1);return false;'); // アクセスパスメニュー、表示順選択メニュー作成 $this->createPathMenu(); $this->createLogOrderMenu(); $this->tmpl->addVar("_widget", "page_link", $pageLink); $this->tmpl->addVar("_widget", "page", $pageNo); // ページ番号 $this->tmpl->addVar("_widget", "view_count", $maxListCount); // 最大表示項目数 // $this->tmpl->addVar("search_range", "start_no", $startNo); // $this->tmpl->addVar("search_range", "end_no", $endNo); // if ($totalCount > 0) $this->tmpl->setAttribute('search_range', 'visibility', 'visible');// 検出範囲を表示 // アクセスログURL $accessLogUrl = '?task=accesslog_detail&openby=simple'; if (!empty($this->server)) $accessLogUrl .= '&_server=' . $this->server; $this->tmpl->addVar("_widget", "access_log_url", $accessLogUrl); // 運用ログを取得 switch ($this->logOrder){ case 0: default: $this->db->getSearchWordLogList($maxListCount, $pageNo, $pathParam, array($this, 'logListLoop')); if (count($this->serialArray) == 0) $this->tmpl->setAttribute('loglist', 'visibility', 'hidden'); // ログがないときは非表示 $this->tmpl->addVar("_widget", "detail_disabled", 'disabled'); // 詳細画面遷移なし break; case 1: // 頻度高 $this->db->getSearchWordSumList($maxListCount, $pageNo, $pathParam, array($this, 'logListSumLoop')); if (count($this->serialArray) == 0) $this->tmpl->setAttribute('loglist_sum', 'visibility', 'hidden'); // ログがないときは非表示 break; } $this->tmpl->addVar("_widget", "serial_list", implode(',', $this->serialArray));// 表示項目のシリアル番号を設定 } /** * 詳細画面作成 * * @param RequestManager $request HTTPリクエスト処理クラス * @return なし */ function createDetail($request) { $act = $request->trimValueOf('act'); $word = $request->trimValueOf('word'); // 比較語 $this->path = $request->trimValueOf('path'); // アクセスパス if (empty($this->path)) $this->path = self::DEFAULT_ACCESS_PATH; $this->logOrder = $request->trimValueOf('logorder');// 検索語の表示順 if ($this->logOrder == '') $this->logOrder = self::DEFAULT_LOG_ORDER; $savedPageNo = $request->trimValueOf('page'); // ページ番号 // 表示条件 $maxListCount = $request->trimIntValueOf('viewcount', '0'); if (empty($maxListCount)) $maxListCount = self::DEFAULT_LIST_COUNT; // 表示項目数 $pageNo = $request->trimIntValueOf('page_', '1'); // ページ番号 // 総数を取得 $pathParam = $this->path; if ($pathParam == self::ACCESS_PATH_ALL){ $pathParam = NULL; } else if ($pathParam == self::ACCESS_PATH_OTHER){ // その他のパス $pathParam = ''; } $totalCount = $this->db->getSearchWordLogCountByWord($word, $pathParam); /* // 表示するページ番号の修正 $pageCount = (int)(($totalCount -1) / $viewCount) + 1; // 総ページ数 if ($pageNo < 1) $pageNo = 1; if ($pageNo > $pageCount) $pageNo = $pageCount; $startNo = ($pageNo -1) * $viewCount +1; // 先頭の行番号 $endNo = $pageNo * $viewCount > $totalCount ? $totalCount : $pageNo * $viewCount;// 最後の行番号 $this->startNo = $startNo; // 先頭の項目番号*/ // ページング計算 $this->calcPageLink($pageNo, $totalCount, $maxListCount); /* // ページング用リンク作成 $pageLink = ''; if ($pageCount > 1){ // ページが2ページ以上のときリンクを作成 for ($i = 1; $i <= $pageCount; $i++){ if ($i > self::MAX_PAGE_COUNT) break; // 最大ページ数以上のときは終了 if ($i == $pageNo){ $link = '&nbsp;' . $i; } else { $link = '&nbsp;<a href="#" onclick="selpage(\'' . $i . '\');return false;">' . $i . '</a>'; } $pageLink .= $link; } }*/ // ページングリンク作成 $pageLink = $this->createPageLink($pageNo, self::LINK_PAGE_COUNT, ''/*リンク作成用(未使用)*/, 'selectPage($1);return false;'); $this->tmpl->addVar("_widget", "page_link", $pageLink); // $this->tmpl->addVar("_widget", "total_count", $totalCount); $this->tmpl->addVar("_widget", "page_", $pageNo); // ページ番号 $this->tmpl->addVar("_widget", "view_count", $viewCount); // 最大表示項目数 // $this->tmpl->addVar("search_range", "start_no", $startNo); // $this->tmpl->addVar("search_range", "end_no", $endNo); // if ($totalCount > 0) $this->tmpl->setAttribute('search_range', 'visibility', 'visible');// 検出範囲を表示 // 前ウィンドウから引き継いだパラメータ $this->tmpl->addVar("_widget", "log_order", $this->logOrder); $this->tmpl->addVar("_widget", "path", $this->path); $this->tmpl->addVar("_widget", "compare_word", $word); $this->tmpl->addVar("_widget", "page", $savedPageNo); // アクセスログURL $accessLogUrl = '?task=accesslog_detail&openby=simple'; if (!empty($this->server)) $accessLogUrl .= '&_server=' . $this->server; $this->tmpl->addVar("_widget", "access_log_url", $accessLogUrl); // 運用ログを取得 $this->db->getSearchWordLogListByWord($word, $maxListCount, $pageNo, $pathParam, array($this, 'logListLoop')); if (count($this->serialArray) == 0) $this->tmpl->setAttribute('loglist', 'visibility', 'hidden'); // ログがないときは非表示 } /** * 検索語一覧取得したデータをテンプレートに設定する * * @param int $index 行番号(0~) * @param array $fetchedRow フェッチ取得した行 * @param object $param 未使用 * @return bool true=処理続行の場合、false=処理終了の場合 */ function logListLoop($index, $fetchedRow, $param) { $agent = $fetchedRow['al_user_agent']; // アクセスユーザの国を取得 $countryCode = ''; if (!empty($fetchedRow['al_accept_language'])) $countryCode = $this->gInstance->getAnalyzeManager()->getBrowserCountryCode($fetchedRow['al_accept_language']); $countryImg = ''; if (!empty($countryCode)){ $iconTitle = $countryCode; $iconUrl = $this->gEnv->getRootUrl() . self::FLAG_ICON_DIR . $countryCode . '.png'; $countryImg = '<img src="' . $this->getUrl($iconUrl) . '" border="0" alt="' . $iconTitle . '" title="' . $iconTitle . '" />'; } // ブラウザ、プラットフォームの情報を取得 $browserTypeInfo = $this->gInstance->getAnalyzeManager()->getBrowserType($agent); $browserImg = ''; if (!empty($browserTypeInfo)){ $iconFile = $browserTypeInfo['icon']; if (!empty($iconFile)){ $iconTitle = $browserTypeInfo['name']; $iconUrl = $this->gEnv->getRootUrl() . self::BROWSER_ICON_DIR . $iconFile; $browserImg = '<img src="' . $this->getUrl($iconUrl) . '" rel="m3help" alt="' . $iconTitle . '" title="' . $iconTitle . '" />'; } } // アクセスログ番号 $accessLog = ''; if (!empty($fetchedRow['sw_access_log_serial'])) $accessLog = $this->convertToDispString($fetchedRow['sw_access_log_serial']); $row = array( 'index' => $index, // 行番号 'word' => $this->convertToDispString($fetchedRow['sw_word']), // 語句 'browser' => $browserImg, // ブラウザ 'country' => $countryImg, // 国画像 'access_log' => $accessLog, // アクセスログ番号 'user' => $this->convertToDispString($fetchedRow['lu_name']), // ユーザ 'dt' => $this->convertToDispDateTime($fetchedRow['al_dt']), // 出力日時 'selected' => $selected // 項目選択用ラジオボタン ); $this->tmpl->addVars('loglist', $row); $this->tmpl->parseTemplate('loglist', 'a'); // 表示中のコンテンツIDを保存 $this->serialArray[] = $fetchedRow['sw_serial']; return true; } /** * 検索語一覧取得したデータをテンプレートに設定する * * @param int $index 行番号(0~) * @param array $fetchedRow フェッチ取得した行 * @param object $param 未使用 * @return bool true=処理続行の場合、false=処理終了の場合 */ function logListSumLoop($index, $fetchedRow, $param) { // 最新の検索語ログを取得 $word = $fetchedRow['sw_basic_word']; $ret = $this->db->getSearchWordLogByCompareWord($word, $row); $row = array( 'index' => $index, // 行番号 'word' => $this->convertToDispString($row['sw_word']), // 語句 'compare_word' => $this->convertToDispString($word), // 比較語 'count' => $this->convertToDispString($fetchedRow['ct']), // 検索回数 'country' => $countryImg, // 国画像 'access_log' => $accessLog, // アクセスログ番号 'user' => $this->convertToDispString($row['lu_name']), // ユーザ 'dt' => $this->convertToDispDateTime($row['al_dt']), // 出力日時 'selected' => $selected // 項目選択用ラジオボタン ); $this->tmpl->addVars('loglist_sum', $row); $this->tmpl->parseTemplate('loglist_sum', 'a'); // 表示中のコンテンツIDを保存 $this->serialArray[] = $no; return true; } /** * アクセスパスメニュー作成 * * @return なし */ function createPathMenu() { $selected = ''; if ($this->path == self::ACCESS_PATH_ALL){// アクセスパスすべて選択 $selected = 'selected'; } $row = array( 'value' => self::ACCESS_PATH_ALL, // アクセスパス 'name' => 'すべて表示', // 表示文字列 'selected' => $selected // 選択中かどうか ); $this->tmpl->addVars('path_list', $row); $this->tmpl->parseTemplate('path_list', 'a'); $this->db->getPageIdList(array($this, 'pageIdLoop'), 0/*ページID*/); $selected = ''; if ($this->path == self::ACCESS_PATH_OTHER){// アクセスパスその他 $selected = 'selected'; } $row = array( 'value' => self::ACCESS_PATH_OTHER, // アクセスパス 'name' => 'その他', // 表示文字列 'selected' => $selected // 選択中かどうか ); $this->tmpl->addVars('path_list', $row); $this->tmpl->parseTemplate('path_list', 'a'); } /** * 表示順選択メニュー作成 * * @return なし */ function createLogOrderMenu() { for ($i = 0; $i < count($this->logOrderArray); $i++){ $value = $this->logOrderArray[$i]['value']; $name = $this->logOrderArray[$i]['name']; $selected = ''; if ($value == $this->logOrder) $selected = 'selected'; $row = array( 'value' => $value, // 表示順 'name' => $name, // 表示順名 'selected' => $selected // 選択中かどうか ); $this->tmpl->addVars('logorder_list', $row); $this->tmpl->parseTemplate('logorder_list', 'a'); } } /** * ページID、取得したデータをテンプレートに設定する * * @param int $index 行番号(0~) * @param array $fetchedRow フェッチ取得した行 * @param object $param 未使用 * @return bool true=処理続行の場合、false=処理終了の場合 */ function pageIdLoop($index, $fetchedRow, $param) { // 開発モードのときはすべて表示、開発モードでないときはフロント画面用アクセスポイントのみ取得 if (!$this->developMode && !$fetchedRow['pg_frontend']) return true; $selected = ''; if ($fetchedRow['pg_path'] == $this->path){ $selected = 'selected'; } $name = $this->convertToDispString($fetchedRow['pg_name']); // ページ名 $row = array( 'value' => $this->convertToDispString($fetchedRow['pg_path']), // アクセスパス 'name' => $name, // ページ名 'selected' => $selected // 選択中かどうか ); $this->tmpl->addVars('path_list', $row); $this->tmpl->parseTemplate('path_list', 'a'); return true; } } ?>
gpl-3.0
guardianproject/ObscuraCam
app/src/main/java/org/witness/obscuracam/ui/ImageRegion.java
12876
package org.witness.obscuracam.ui; import android.content.res.Resources; import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.Log; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import org.witness.obscuracam.photo.filters.BlurObscure; import org.witness.obscuracam.photo.filters.ConsentTagger; import org.witness.obscuracam.photo.filters.CrowdPixelizeObscure; import org.witness.obscuracam.photo.filters.MaskObscure; import org.witness.obscuracam.photo.filters.PixelizeObscure; import org.witness.obscuracam.photo.filters.RegionProcesser; import org.witness.obscuracam.photo.filters.SolidObscure; import org.witness.obscuracam.ObscuraApp; import org.witness.sscphase1.R; public class ImageRegion { public static final String LOGTAG = "SSC.ImageRegion"; // Rect for this when unscaled public RectF mBounds; // Start point for touch events PointF mStartPoint = null; public static final int REDACT = 0; // PaintSquareObscure public static final int PIXELATE = 1; // PixelizeObscure public static final int BG_PIXELATE = 2; // BlurObscure public static final int MASK = 3; // MaskObscure public static final int CONSENT = 4; // PixelizeObscure public static final int BLUR = 5; // PixelizeObscure public static final int EQUALAIS = 6; // PixelizeObscure boolean selected = false; public static final int CORNER_UPPER_LEFT = 1; public static final int CORNER_LOWER_LEFT = 2; public static final int CORNER_UPPER_RIGHT = 3; public static final int CORNER_LOWER_RIGHT = 4; public static final int CORNER_LEFT = 5; public static final int CORNER_RIGHT = 6; public static final int CORNER_UPPER = 7; public static final int CORNER_LOWER = 8; public static final int CORNER_NONE = -1; /* Add each ObscureMethod to this list and update the * createObscuredBitmap method in ImageEditor */ int mObscureType = PIXELATE; public final Drawable unidentifiedBorder, identifiedBorder; public Drawable imageRegionBorder; // The ImageEditor object that contains us ImageEditor mImageEditor; RegionProcesser mRProc; private final static float MIN_MOVE = 5f; private final static float CORNER_MAX = 50f; private int handleTouchSlop; private int cornerMode = -1; public RegionProcesser getRegionProcessor() { return mRProc; } public void setRegionProcessor(RegionProcesser rProc) { mRProc = rProc; } public void setCornerMode (float x, float y) { float[] points = {x,y, mBounds.left, mBounds.top, mBounds.right, mBounds.bottom}; mImageEditor.getMatrixInverted().mapPoints(points); double radiusSquared = mImageEditor.getMatrixInverted().mapRadius(handleTouchSlop); radiusSquared = radiusSquared * radiusSquared; // float cSize = CORNER_MAX; // cSize = iMatrix.mapRadius(cSize); if (inLeftHandle(points[0], points[1], radiusSquared)) { cornerMode = CORNER_LEFT; return; } else if (inRightHandle(points[0], points[1], radiusSquared)) { cornerMode = CORNER_RIGHT; return; } else if (inTopHandle(points[0], points[1], radiusSquared)) { cornerMode = CORNER_UPPER; return; } else if (inBottomHandle(points[0], points[1], radiusSquared)) { cornerMode = CORNER_LOWER; return; } // else if (Math.abs(mBounds.left-points[0])<cSize // && Math.abs(mBounds.top-points[1])<cSize // ) // { // cornerMode = CORNER_UPPER_LEFT; // return; // } // else if (Math.abs(mBounds.left-points[0])<cSize // && Math.abs(mBounds.bottom-points[1])<cSize // ) // { // cornerMode = CORNER_LOWER_LEFT; // return; // } // else if (Math.abs(mBounds.right-points[0])<cSize // && Math.abs(mBounds.top-points[1])<cSize // ) // { // cornerMode = CORNER_UPPER_RIGHT; // return; // } // else if (Math.abs(mBounds.right-points[0])<cSize // && Math.abs(mBounds.bottom-points[1])<cSize // ) // { // cornerMode = CORNER_LOWER_RIGHT; // return; // } // cornerMode = CORNER_NONE; } private boolean inLeftHandle(float x, float y, double radiusSquared) { float midY = mBounds.top + (mBounds.bottom - mBounds.top) / 2; double dx = Math.pow(mBounds.left - x, 2); double dy = Math.pow(midY - y, 2); return ((dx + dy) < radiusSquared); } private boolean inRightHandle(float x, float y, double radiusSquared) { float midY = mBounds.top + (mBounds.bottom - mBounds.top) / 2; double dx = Math.pow(mBounds.right - x, 2); double dy = Math.pow(midY - y, 2); return ((dx + dy) < radiusSquared); } private boolean inTopHandle(float x, float y, double radiusSquared) { float midX = mBounds.left + (mBounds.right - mBounds.left) / 2; double dx = Math.pow(midX - x, 2); double dy = Math.pow(mBounds.top - y, 2); return ((dx + dy) < radiusSquared); } private boolean inBottomHandle(float x, float y, double radiusSquared) { float midX = mBounds.left + (mBounds.right - mBounds.left) / 2; double dx = Math.pow(midX - x, 2); double dy = Math.pow(mBounds.bottom - y, 2); return ((dx + dy) < radiusSquared); } public boolean containsPoint(float x, float y) { float[] points = {x,y}; mImageEditor.getMatrixInverted().mapPoints(points); double radiusSquared = mImageEditor.getMatrixInverted().mapRadius(handleTouchSlop); radiusSquared = radiusSquared * radiusSquared; x = points[0]; y = points[1]; return mBounds.contains(x, y) || inLeftHandle(x, y, radiusSquared) || inRightHandle(x, y, radiusSquared) || inTopHandle(x, y, radiusSquared) || inBottomHandle(x, y, radiusSquared); } /* For touch events, whether or not to show the menu */ boolean moved = false; int fingerCount = 0; public ImageRegion( ImageEditor imageEditor, float left, float top, float right, float bottom, Matrix matrix) { super(); // Handle Resources r = imageEditor.getResources(); handleTouchSlop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ImageEditor.SELECTION_HANDLE_TOUCH_RADIUS, r.getDisplayMetrics()); // Set the mImageEditor that this region belongs to to the one passed in mImageEditor = imageEditor; // set the borders for tags in Non-Edit mode identifiedBorder = imageEditor.getResources().getDrawable(R.drawable.border_idtag); unidentifiedBorder = imageEditor.getResources().getDrawable(R.drawable.border); mBounds = new RectF(left, top, right, bottom); //set default processor this.setRegionProcessor(new PixelizeObscure()); } boolean isSelected () { return selected; } void setSelected (boolean _selected) { selected = _selected; } private void updateBounds(float left, float top, float right, float bottom) { //Log.i(LOGTAG, "updateBounds: " + left + "," + top + "," + right + "," + bottom); mBounds.set(left, top, right, bottom); //updateLayout(); } public RectF getBounds () { return mBounds; } public boolean onTouch(View v, MotionEvent event) { fingerCount = event.getPointerCount(); // Log.v(LOGTAG,"onTouch: fingers=" + fingerCount); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: moved = false; mStartPoint = new PointF(event.getX(),event.getY()); return true; case MotionEvent.ACTION_POINTER_UP: Log.v(LOGTAG, "second finger removed - pointer up!"); return moved; case MotionEvent.ACTION_UP: mImageEditor.setRealtimePreview(true); mImageEditor.forceUpdateDisplayImage(); //mTmpBounds = null; return moved; case MotionEvent.ACTION_MOVE: if (fingerCount > 1) { float[] points = {event.getX(0), event.getY(0), event.getX(1), event.getY(1)}; mImageEditor.getMatrixInverted().mapPoints(points); mStartPoint = new PointF(points[0],points[1]); RectF newBox = new RectF(); newBox.left = Math.min(points[0],points[2]); newBox.top = Math.min(points[1],points[3]); newBox.right = Math.max(points[0],points[2]); newBox.bottom = Math.max(points[1],points[3]); moved = true; if (newBox.left != newBox.right && newBox.top != newBox.bottom) { updateBounds(newBox.left, newBox.top, newBox.right, newBox.bottom); } } else if (fingerCount == 1) { if (Math.abs(mStartPoint.x- event.getX()) > MIN_MOVE) { moved = true; float[] points = {mStartPoint.x, mStartPoint.y, event.getX(), event.getY()}; mImageEditor.getMatrixInverted().mapPoints(points); float diffX = points[0]-points[2]; float diffY = points[1]-points[3]; float left = 0, top = 0, right = 0, bottom = 0; if (cornerMode == CORNER_NONE) { left = mBounds.left-diffX; top = mBounds.top-diffY; right = mBounds.right-diffX; bottom = mBounds.bottom-diffY; } else { if (cornerMode == CORNER_LEFT || cornerMode == CORNER_UPPER_LEFT || cornerMode == CORNER_LOWER_LEFT) { left = mBounds.left - diffX; } else { left = mBounds.left; } if (cornerMode == CORNER_RIGHT || cornerMode == CORNER_UPPER_RIGHT || cornerMode == CORNER_LOWER_RIGHT) { right = mBounds.right - diffX; } else { right = mBounds.right; } if (cornerMode == CORNER_UPPER || cornerMode == CORNER_UPPER_LEFT || cornerMode == CORNER_UPPER_RIGHT) { top = mBounds.top-diffY; } else { top = mBounds.top; } if (cornerMode == CORNER_LOWER || cornerMode == CORNER_LOWER_LEFT || cornerMode == CORNER_LOWER_RIGHT) { bottom = mBounds.bottom-diffY; } else { bottom = mBounds.bottom; } } if ((left+CORNER_MAX) > right || (top+CORNER_MAX) > bottom) return false; //updateBounds(Math.min(left, right), Math.min(top,bottom), Math.max(left, right), Math.max(top, bottom)); updateBounds(left, top, right, bottom); mStartPoint = new PointF(event.getX(),event.getY()); } else { moved = false; } } mImageEditor.updateDisplayImage(); return true; /* case MotionEvent.ACTION_OUTSIDE: Log.v(LOGTAG,"ACTION_OUTSIDE"); mImageEditor.doRealtimePreview = true; mImageEditor.updateDisplayImage(); return true; case MotionEvent.ACTION_CANCEL: Log.v(LOGTAG,"ACTION_CANCEL"); mImageEditor.doRealtimePreview = true; mImageEditor.updateDisplayImage(); return true; default: Log.v(LOGTAG, "DEFAULT: " + (event.getAction() & MotionEvent.ACTION_MASK)); mImageEditor.doRealtimePreview = true; mImageEditor.updateDisplayImage(); return true;*/ } return false; } public void setObscureType(int obscureType) { mObscureType = obscureType; updateRegionProcessor(obscureType); } private void updateRegionProcessor (int obscureType) { switch (obscureType) { case ImageRegion.BG_PIXELATE: Log.v(ObscuraApp.TAG,"obscureType: BGPIXELIZE"); setRegionProcessor(new CrowdPixelizeObscure()); break; case ImageRegion.MASK: Log.v(ObscuraApp.TAG,"obscureType: ANON"); if (mRProc != null && mRProc instanceof MaskObscure) { ((MaskObscure)mRProc).rotateMask(); } else setRegionProcessor(new MaskObscure(mImageEditor.getApplicationContext(), mImageEditor.getPainter())); break; case ImageRegion.REDACT: Log.v(ObscuraApp.TAG,"obscureType: SOLID"); setRegionProcessor(new SolidObscure()); break; case ImageRegion.PIXELATE: Log.v(ObscuraApp.TAG,"obscureType: PIXELIZE"); setRegionProcessor(new PixelizeObscure()); break; case ImageRegion.BLUR: Log.v(ObscuraApp.TAG,"obscureType: NONE/BLUR"); setRegionProcessor(new BlurObscure(mImageEditor.getPainter())); break; } if(getRegionProcessor().getClass() == ConsentTagger.class) imageRegionBorder = identifiedBorder; else imageRegionBorder = unidentifiedBorder; } }
gpl-3.0
smogpill/dataspace
src/simt_cl/simtManager_cl_gl_win.cpp
1781
/* Copyright (C) 2010-2013 Jounayd Id Salah https://github.com/smogpill/dataspace. This file is part of the Dataspace project. Dataspace 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. Dataspace 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 Dataspace. If not, see <http://www.gnu.org/licenses/>. */ #include "simtPCH_cl.h" #include "simt_cl/simtDefault_cl.h" #include "simt_cl/simtManager_cl.h" #include "render_gl/renContext_gl.h" #include "simt_cl/simtErrorCodes_cl.h" //------------------------------------------------------- coResult simtManager_cl::s_createContextFromRenderContext (cl_context& _out, cl_device_id _deviceId, renContext& _renderContext, simtManager& _simtManager) { _out = nullptr; renContext_gl& renderContext = static_cast<renContext_gl&>(_renderContext); const renContext_gl::RenderingContext& renderingContext = renderContext.getRenderingContext(); const cl_context_properties props[] = { CL_GL_CONTEXT_KHR, (cl_context_properties)renderingContext.m_hglrc, CL_WGL_HDC_KHR, (cl_context_properties)renderingContext.m_hdc, 0 }; cl_int res_cl; cl_context context = clCreateContext(props, 1, &_deviceId, simtManager_cl::s_errorCallback, &_simtManager, &res_cl); coTRY(context, "clCreateContext(): "<<simtErrorCodes_cl::sGetErrorDesc(res_cl)); _out = context; return coSUCCESS; }
gpl-3.0
nickbattle/vdmj
examples/v2c/src/main/java/examples/v2c/tr/expressions/TRIfExpression.java
1492
/******************************************************************************* * * Copyright (c) 2020 Nick Battle. * * Author: Nick Battle * * This file is part of VDMJ. * * VDMJ 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. * * VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>. * SPDX-License-Identifier: GPL-3.0-or-later * ******************************************************************************/ package examples.v2c.tr.expressions; public class TRIfExpression extends TRExpression { private static final long serialVersionUID = 1L; private final TRExpression ifExp; private final TRExpression thenExp; private final TRExpression elseExp; public TRIfExpression(TRExpression ifExp, TRExpression thenExp, TRExpression elseExp) { this.ifExp = ifExp; this.thenExp = thenExp; this.elseExp = elseExp; } @Override public String translate() { return "(" + ifExp.translate() + ") ? " + thenExp.translate() + " : " + elseExp.translate(); } }
gpl-3.0
AmazengProject/AmazeFileManager
app/src/main/java/com/amaze/filemanager/ui/ZipObjectParcelable.java
1878
package com.amaze.filemanager.ui; import android.os.Parcel; import android.os.Parcelable; import java.util.zip.ZipEntry; /** * Created by Arpit on 11-12-2014. */ public class ZipObjectParcelable implements Parcelable { private boolean directory; private ZipEntry entry; private String name; private long date, size; public ZipObjectParcelable(ZipEntry entry, long date, long size, boolean directory) { this.directory = directory; this.entry = entry; if (entry != null) { name = entry.getName(); this.date = date; this.size = size; } } public ZipEntry getEntry() { return entry; } public boolean isDirectory() { return directory; } public String getName() { return name; } public long getSize() { return size; } public long getTime() { return date; } @Override public int describeContents() { return 0; } public void writeToParcel(Parcel p1, int p2) { p1.writeString(name); p1.writeLong(size); p1.writeLong(date); p1.writeInt(isDirectory() ? 1 : 0); } public static final Parcelable.Creator<ZipObjectParcelable> CREATOR = new Parcelable.Creator<ZipObjectParcelable>() { public ZipObjectParcelable createFromParcel(Parcel in) { return new ZipObjectParcelable(in); } public ZipObjectParcelable[] newArray(int size) { return new ZipObjectParcelable[size]; } }; public ZipObjectParcelable(Parcel im) { name = im.readString(); size = im.readLong(); date = im.readLong(); int i = im.readInt(); directory = i != 0; entry = new ZipEntry(name); } }
gpl-3.0
holloway/docvert-python3
core/pipeline_type/debug.py
3212
# -*- coding: utf-8 -*- import lxml.etree from . import pipeline_item import core.docvert_exception class Debug(pipeline_item.pipeline_stage): def stage(self, pipeline_value): def get_value(data): if hasattr(data, "read"): data.seek(0) return data.read() return data if isinstance(pipeline_value, lxml.etree._Element) or isinstance(pipeline_value, lxml.etree._XSLTResultTree): pipeline_value = lxml.etree.tostring(pipeline_value) elif hasattr(pipeline_value, 'read'): pipeline_value.seek(0) pipeline_value = pipeline_value.read() if get_value(pipeline_value) is None: raise core.docvert_exception.debug_exception("Current contents of pipeline", "Debug: pipeline_value is %s" % get_value(pipeline_value), "text/plain; charset=UTF-8") try: document = lxml.etree.fromstring(get_value(pipeline_value)) except lxml.etree.XMLSyntaxError as exception: raise core.docvert_exception.debug_exception("Current contents of pipeline", "Error parsing as XML, here it is as plain text: %s\n%s" % (exception, pipeline_value), "text/plain; charset=UTF-8") help_text = "In debug mode we want to display an XML tree but if the root node is <html> or there's an HTML namespace then popular browsers will\nrender it as HTML so these have been changed. See core/pipeline_type/debug.py for the details." unit_tests = self.get_tests() if unit_tests: #help_text += "\n\nUnit tests so far in the pipeline:" help_text += "\n\nFailed unit tests so far in the pipeline:" for value in self.get_tests(): #help_text += "\n\t%s:%s" % (value["status"], value["message"]) if value["status"] == "fail": help_text += "\n\tFail: %s" % (value["message"]) content_type = 'text/xml' if "contentType" in self.attributes: content_type = self.attributes['contentType'] if "zip" in self.attributes: content_type = 'application/zip' pipeline_value = self.storage.to_zip().getvalue() if content_type == 'text/xml': help_text += "\n\nConversion files:\n\t" + "\n\t".join(list(self.storage.keys())) if hasattr(document, 'getroottree'): document = document.getroottree() if document.getroot().tag == "{http://www.w3.org/1999/xhtml}html": pipeline_value = "<root><!-- %s -->%s</root>" % (help_text, lxml.etree.tostring(document.getroot())) else: pipeline_value = "<!-- %s -->%s" % (help_text, lxml.etree.tostring(document.getroot()).decode('utf-8') ) pipeline_value = pipeline_value.replace('"http://www.w3.org/1999/xhtml"', '"XHTML_NAMESPACE_REPLACED_BY_DOCVERT_DURING_DEBUG_MODE"') xml_declaration = '<?xml version="1.0" ?>' if pipeline_value[0:5] != xml_declaration[0:5]: pipeline_value = xml_declaration + "\n" + pipeline_value raise core.docvert_exception.debug_xml_exception("Current contents of pipeline", pipeline_value, content_type)
gpl-3.0
jkiddo/jolivia
jolivia.protocol/src/main/java/org/dyndns/jkiddo/dmap/chunks/audio/extension/CollectionDescription.java
499
package org.dyndns.jkiddo.dmap.chunks.audio.extension; import org.dyndns.jkiddo.dmp.DMAPAnnotation; import org.dyndns.jkiddo.dmp.IDmapProtocolDefinition.DmapChunkDefinition; import org.dyndns.jkiddo.dmp.chunks.StringChunk; @DMAPAnnotation(type=DmapChunkDefinition.aecp) public class CollectionDescription extends StringChunk { public CollectionDescription() { this(""); } public CollectionDescription(String string) { super("aecp","com.apple.itunes.collection-description",string); } }
gpl-3.0
oliverde8/OWeb
v0.3/OWeb_src/OWeb/defaults/models/articles/Artciles.php
10896
<?php /** * @author Oliver de Cramer (oliverde8 at gmail.com) * @copyright GNU GENERAL PUBLIC LICENSE * Version 3, 29 June 2007 * * PHP version 5.3 and above * * LICENSE: This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 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/}. */ namespace Model\articles; use Model\articles\Categories; use OWeb\utils\Singleton; /** * Description of Artciles * * @author De Cramer Oliver */ class Artciles extends Singleton{ private $ext_connection; private $categories; private $articles = array(); static public function getInstance(){ $class = self::getInstanceNull(); if($class == null){ $obj = new Artciles(Categories::getInstance()); self::setInstance($obj); return $obj; } } function __construct(Categories $cat) { $this->ext_connection = \OWeb\manage\Extensions::getInstance()->getExtension('db\Connection'); $this->categories = $cat; } public function getArticle($id){ if(isset($this->articles[$id])) return $this->articles[$id]; else{ try{ $connection = $this->ext_connection->get_Connection(); $prefix = $this->ext_connection->get_prefix(); $sql = $connection->prepare("SELECT * FROM " . $prefix . "article_article aa, " . $prefix . "article_content ac WHERE ac.article_id = id_article AND id_article = :id"); if($sql->execute(array(':id'=>$id)) && $result = $sql->fetchObject()){ $article = new \Model\articles\Article ( $result->id_article, $result->type, $result->img, $result->published == 1, $result->pdate, $this->categories->getElement($result->category_id) ); $this->articles[$id] = $article; $article->addLanguage($result->article_lang, $result->title, $result->content); while($result = $sql->fetchObject()){ $article->addLanguage($result->article_lang, $result->title, $result->content); } $sql = "SELECT * FROM " . $prefix . "article_category_more WHERE article_id = $id"; if($sql = $connection->query($sql)){ while($result = $sql->fetchObject()){ $article->addCategorie($this->categories->getElement($result->category_id)); } } $sql = "SELECT * FROM " . $prefix . "article_attribute WHERE article_id = $id"; if($sql = $connection->query($sql)){ while($result = $sql->fetchObject()){ $article->addAttribute($result->name, $result->value); } } $article->setisDOne(true); return $article; }else{ throw new \Model\articles\exception\ArticleNotFound("Couldn't get Article with id : $id . SQL ERROR2", 0); } }catch(\Exception $ex){ throw new \Model\articles\exception\ArticleNotFound("Couldn't get Article with id : $id . SQL ERROR", 0, $ex); } } } public function getNbCategoryArticles(\Model\articles\CategorieElement $cat, $rec = true, $pusblished=true){ try{ $connection = $this->ext_connection->get_Connection(); $prefix = $this->ext_connection->get_prefix(); $cs = $cat->getChildrens(); if($rec && !empty($cs)){ $cat_parents = $cat->getRecuriveChildrensIds(); $sql = "SELECT COUNT(*) as nb FROM " . $prefix . "article_article aa WHERE (id_article IN (SELECT acm.article_id FROM " . $prefix . "article_category_more acm WHERE acm.category_id = ".$cat->getId()." ) OR category_id = ".$cat->getId()." OR id_article IN (SELECT acm.article_id FROM " . $prefix . "article_category_more acm WHERE acm.category_id IN ($cat_parents)) OR category_id IN ($cat_parents))" ." AND published = ".$pusblished ? '1' : '0'; //return; }else $sql = "SELECT COUNT(*) as nb FROM " . $prefix . "article_article aa WHERE (id_article IN (SELECT acm.article_id FROM " . $prefix . "article_category_more acm WHERE acm.category_id = ".$cat->getId()." ) OR category_id = ".$cat->getId().")" . " AND published = ".$pusblished ? '1' : '0'; if($sql = $connection->query($sql)){ if($result = $sql->fetchObject()){ return $result->nb; } } }catch(\Exception $ex){ throw new \Model\articles\exception\ArticleNotFound("Couldn't get Nb Articles of Category : ".$cat->getId()." . SQL ERROR", 0, $ex); } } public function getCategoryArticles(\Model\articles\CategorieElement $cat, $start, $nbElement, $rec = true, $pusblished=true){ try{ $connection = $this->ext_connection->get_Connection(); $prefix = $this->ext_connection->get_prefix(); $cs = $cat->getChildrens(); if($rec && !empty($cs)){ $cat_parents = $cat->getRecuriveChildrensIds(); $sql2 = "SELECT id_article FROM " . $prefix . "article_article aa WHERE (id_article IN (SELECT acm.article_id FROM " . $prefix . "article_category_more acm WHERE acm.category_id = ".$cat->getId()." ) OR category_id = ".$cat->getId()." OR id_article IN (SELECT acm.article_id FROM " . $prefix . "article_category_more acm WHERE acm.category_id IN ($cat_parents)) OR category_id IN ($cat_parents))" . " AND published = ".($pusblished ? '1' : '0')." ORDER BY pdate DESC LIMIT $start, $nbElement"; //return; }else $sql2 = "SELECT id_article FROM " . $prefix . "article_article aa WHERE (id_article IN (SELECT acm.article_id FROM " . $prefix . "article_category_more acm WHERE acm.category_id = ".$cat->getId()." ) OR category_id = ".$cat->getId() . ") AND published = ".($pusblished ? '1' : '0')." ORDER BY pdate DESC LIMIT $start, $nbElement"; //$sql = $connection->prepare($sql); $article_ids = ""; if($sql = $connection->query($sql2)){ while($result = $sql->fetchObject()){ $article_ids .= $result->id_article." ,"; } $article_ids = substr($article_ids, 0, strlen($article_ids)-1); } if($article_ids == "") return array(); $sql2 = "SELECT * FROM " . $prefix . "article_article aa, " . $prefix . "article_content ac WHERE ac.article_id = id_article AND id_article IN ($article_ids) ORDER BY pdate DESC"; if($sql = $connection->query($sql2)){ $articles = array(); while($result = $sql->fetchObject()){ if(isset($this->articles[$result->id_article]) && !isset($articles[$result->id_article])) $articles[$result->id_article] = $this->articles[$result->id_article]; else if(!isset($articles[$result->id_article])){ $articles[$result->id_article] = new \Model\articles\Article ( $result->id_article, $result->type, $result->img, $result->published == 1, $result->pdate, $this->categories->getElement($result->category_id) ); $this->articles[$result->id_article] = $articles[$result->id_article]; } if(!$articles[$result->id_article]->isDone()){ $articles[$result->id_article]->addLanguage($result->article_lang, $result->title, $result->content); } } $sql2 = "SELECT * FROM " . $prefix . "article_category_more WHERE article_id IN ( $article_ids) "; if($sql = $connection->query($sql2)){ while($result = $sql->fetchObject()){ if(!$articles[$result->article_id]->isDone()) $articles[$result->article_id]->addCategorie($this->categories->getElement($result->category_id)); } } $sql2 = "SELECT * FROM " . $prefix . "article_attribute WHERE article_id IN ( $article_ids) "; if($sql = $connection->query($sql2)){ while($result = $sql->fetchObject()){ if(!$articles[$result->article_id]->isDone()) $articles[$result->article_id]->addAttribute($result->name, $result->value); } } if(is_array($articles)) foreach ($articles as $article) $article->setisDOne (true); return $articles; }else{ throw new \Model\articles\exception\ArticleNotFound("Couldn't get Articles of Category : ".$cat->getId()." . SQL ERROR2".$sql2, 0); } }catch(\Exception $ex){ throw new \Model\articles\exception\ArticleNotFound("Couldn't get Articles of Category : ".$cat->getId()." . SQL ERROR", 0, $ex); } } public function getArticleByNameCategory($name, \Model\articles\CategorieElement $cat){ $connection = $this->ext_connection->get_Connection(); $prefix = $this->ext_connection->get_prefix(); $sql = "SELECT * FROM " . $prefix . "article_article aa, " . $prefix . "article_content ac WHERE ac.article_id = id_article AND ac.title = ".$connection->quote($name)." AND (aa.category_id = ".$cat->getId()." OR id_article IN (SELECT acm.article_id FROM " . $prefix . "article_category_more acm WHERE acm.category_id = ".$cat->getId()." ))"; if($sql = $connection->query($sql)){ $result = $sql->fetchObject(); $article = new \Model\articles\Article ( $result->id_article, $result->type, $result->img, $result->published == 1, $result->pdate, $this->categories->getElement($result->category_id) ); $this->articles[$result->id_article] = $article; $id = $result->id_article; $article->addLanguage($result->article_lang, $result->title, $result->content); while($result = $sql->fetchObject()){ $article->addLanguage($result->article_lang, $result->title, $result->content); } $sql = "SELECT * FROM " . $prefix . "article_category_more WHERE article_id = $id"; if($sql = $connection->query($sql)){ while($result = $sql->fetchObject()){ $article->addCategorie($this->categories->getElement($result->category_id)); } } $sql = "SELECT * FROM " . $prefix . "article_attribute WHERE article_id = $id"; if($sql = $connection->query($sql)){ while($result = $sql->fetchObject()){ $article->addAttribute($result->name, $result->value); } } $article->setisDOne(true); return $article; } } } ?>
gpl-3.0
storri/libreverse
reverse/io/input/file_readers/windows_pe/amd_ia_64_exception_table_entry.cpp
3281
/* AMD_IA_64_Exception_Table_Entry.cpp Copyright (C) 2008 Stephen Torri This file is part of Libreverse. Libreverse 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, or (at your option) any later version. Libreverse 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 <reverse/io/byte_converter.hpp> #include <reverse/io/input/file_readers/windows_pe/amd_ia_64_exception_table_entry.hpp> #include <reverse/io/input/file_readers/windows_pe/pe_file.hpp> #include <reverse/trace.hpp> #include <boost/format.hpp> #include <sstream> namespace reverse { namespace io { namespace input { namespace file_readers { namespace windows_pe { amd_ia_64_exception_table_entry::amd_ia_64_exception_table_entry() : m_begin_address ( 0 ), m_end_address ( 0 ), m_unwind_information ( 0 ) { trace::write_trace ( trace_area::io, trace_level::detail, "Inside AMD_IA_64_Exception_Table_Entry () constructor" ); } void amd_ia_64_exception_table_entry::read_entry ( boost::shared_ptr < pe_file > file_ptr ) { trace::write_trace ( trace_area::io, trace_level::detail, "Entering AMD_IA_64_Exception_Table_Entry::read_Entry" ); file_ptr->read_amd_ia_64_exception ( this->shared_from_this() ); trace::write_trace ( trace_area::io, trace_level::detail, "Exiting AMD_IA_64_Exception_Table_Entry::read_Entry" ); } std::string amd_ia_64_exception_table_entry::to_string (void) { trace::write_trace ( trace_area::io, trace_level::detail, "Entering AMD_IA_64_Exception_Table_Entry::to_String" ); std::stringstream output; output << boost::format(" begin address.....: 0x%|1X|") % m_begin_address << std::endl << boost::format(" end address.......: 0x%|1X|") % m_end_address << std::endl << boost::format(" unwind information: 0x%|1X|") % m_unwind_information << std::endl; trace::write_trace ( trace_area::io, trace_level::detail, "Exiting AMD_IA_64_Exception_Table_Entry::to_String" ); return output.str(); } void amd_ia_64_exception_table_entry::convert () { trace::write_trace ( trace_area::io, trace_level::detail, "Entering AMD_IA_64_Exception_Table_Entry::convert" ); // NOTE: Itanium can be either little-endian or big endian so we have to check io::byte_converter::convert ( m_begin_address ); io::byte_converter::convert ( m_end_address ); io::byte_converter::convert ( m_unwind_information ); trace::write_trace ( trace_area::io, trace_level::detail, "Exiting AMD_IA_64_Exception_Table_Entry::convert" ); } } // namespace windows_pe } // namespace file_readers } // namespace input } // namespace io } // namespace reverse
gpl-3.0
abhijitsarkar/java
xml/jaxp-basic/src/main/java/name/abhijitsarkar/xml/jaxp/dom/MyDOMParser.java
2837
package name.abhijitsarkar.xml.jaxp.dom; import java.io.File; import java.io.InputStream; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import name.abhijitsarkar.xml.jaxp.MyErrorHandler; import name.abhijitsarkar.xml.jaxp.sax.MySAXParser; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class MyDOMParser { private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; public static void main(String[] args) throws Exception { MyDOMParser myParser = new MyDOMParser(); myParser.parseWithoutValidation(); myParser.parseWithValidation(); } public void parseWithoutValidation() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); InputStream is = MyDOMParser.class.getResourceAsStream("/po_good.xml"); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); printNodeInfo(doc.getDocumentElement()); is.close(); } public void parseWithValidation() throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); URL schema = MySAXParser.class.getResource("/po.xsd"); dbf.setAttribute(JAXP_SCHEMA_SOURCE, new File(schema.toURI())); InputStream is = MyDOMParser.class.getResourceAsStream("/po_bad.xml"); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(new MyErrorHandler()); Document doc = db.parse(is); printNodeInfo(doc.getDocumentElement()); is.close(); } private void printNodeInfo(Node node) { short nodeType = node.getNodeType(); switch (nodeType) { case Node.ELEMENT_NODE: Element elem = (Element) node; NamedNodeMap attributeMap = elem.getAttributes(); int numAttr = attributeMap.getLength(); System.out.printf("Element %s has %d attributes\n", elem.getNodeName(), numAttr); Attr attr = null; for (int i = 0; i < numAttr; i++) { attr = (Attr) attributeMap.item(i); System.out.printf("Attribute[%d] -> [name=%s, value=%s]\n", i, attr.getName(), attr.getValue()); } NodeList childNodes = elem.getChildNodes(); int numChildren = childNodes.getLength(); for (int i = 0; i < numChildren; i++) { printNodeInfo(childNodes.item(i)); } break; case Node.TEXT_NODE: System.out.println("text: \"" + node.getNodeValue().trim() + "\""); break; default: } } }
gpl-3.0
briancappello/PyTradeLib
pytradelib/downloader.py
831
import asyncio from aiohttp import ClientSession, ClientResponse, ClientResponseError from .utils import chunk async def bulk_download(urls, handle_resp, batch_size=8): if not isinstance(urls, (list, tuple)): urls = [urls] async def dl(session, url): async with session.get(url) as r: data, error = await handle_resp(r) if error: return url, error return url, data async def dl_all(): results = [] async with ClientSession() as session: for batch in chunk(urls, batch_size): tasks = [dl(session, url) for url in batch] batch_results = await asyncio.gather(*tasks, return_exceptions=False) results.extend(batch_results) return results return await dl_all()
gpl-3.0
Victor-Haefner/polyvr
src/addons/Algorithms/VRPyGraphLayout.cpp
788
#include "VRPyGraphLayout.h" #include "core/scripting/VRPyBaseT.h" using namespace OSG; simpleVRPyType(GraphLayout, New_ptr); PyMethodDef VRPyGraphLayout::methods[] = { {"setGraph", PyWrap( GraphLayout, setGraph, "Set graph", void, GraphPtr ) }, {"setAlgorithm", PyWrapOpt( GraphLayout, setAlgorithm, "Set pipeline algorithms - setAlgorithm( str algorithm, int position )\n\talgorithm: 'SPRINGS', 'OCCUPANCYMAP'", "0", void, string, int ) }, {"setParameters", PyWrap( GraphLayout, setRadius, "Set parameters, radius", void, float ) }, {"fixNode", PyWrap( GraphLayout, fixNode, "Fix a node, making it static", void, int ) }, {"compute", PyWrapOpt( GraphLayout, compute, "Compute N steps, steps, threshold", "0.1", void, int, float ) }, {NULL} /* Sentinel */ };
gpl-3.0
bigwhirled/elmsln
core/_nondrupal/piwik/plugins/CustomVariables/CustomVariables.php
4355
<?php /** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * */ namespace Piwik\Plugins\CustomVariables; use Piwik\ArchiveProcessor; use Piwik\Piwik; use Piwik\Tracker\Cache; use Piwik\Tracker; class CustomVariables extends \Piwik\Plugin { /** * @see Piwik\Plugin::getListHooksRegistered */ public function getListHooksRegistered() { return array( 'API.getSegmentDimensionMetadata' => 'getSegmentsMetadata', 'Live.getAllVisitorDetails' => 'extendVisitorDetails' ); } public function install() { Model::install(); } public function uninstall() { Model::uninstall(); } public function extendVisitorDetails(&$visitor, $details) { $customVariables = array(); $maxCustomVariables = self::getMaxCustomVariables(); for ($i = 1; $i <= $maxCustomVariables; $i++) { if (!empty($details['custom_var_k' . $i])) { $customVariables[$i] = array( 'customVariableName' . $i => $details['custom_var_k' . $i], 'customVariableValue' . $i => $details['custom_var_v' . $i], ); } } $visitor['customVariables'] = $customVariables; } /** * There are also some hardcoded places in JavaScript * @return int */ public static function getMaxLengthCustomVariables() { return 200; } public static function getMaxCustomVariables() { $cache = Cache::getCacheGeneral(); $cacheKey = 'CustomVariables.MaxNumCustomVariables'; if (!array_key_exists($cacheKey, $cache)) { $maxCustomVar = 0; foreach (Model::getScopes() as $scope) { $model = new Model($scope); $highestIndex = $model->getHighestCustomVarIndex(); if ($highestIndex > $maxCustomVar) { $maxCustomVar = $highestIndex; } } $cache[$cacheKey] = $maxCustomVar; Cache::setCacheGeneral($cache); } return $cache[$cacheKey]; } public function getSegmentsMetadata(&$segments) { $maxCustomVariables = self::getMaxCustomVariables(); for ($i = 1; $i <= $maxCustomVariables; $i++) { $segments[] = array( 'type' => 'dimension', 'category' => 'CustomVariables_CustomVariables', 'name' => Piwik::translate('CustomVariables_ColumnCustomVariableName') . ' ' . $i . ' (' . Piwik::translate('CustomVariables_ScopeVisit') . ')', 'segment' => 'customVariableName' . $i, 'sqlSegment' => 'log_visit.custom_var_k' . $i, ); $segments[] = array( 'type' => 'dimension', 'category' => 'CustomVariables_CustomVariables', 'name' => Piwik::translate('CustomVariables_ColumnCustomVariableValue') . ' ' . $i . ' (' . Piwik::translate('CustomVariables_ScopeVisit') . ')', 'segment' => 'customVariableValue' . $i, 'sqlSegment' => 'log_visit.custom_var_v' . $i, ); $segments[] = array( 'type' => 'dimension', 'category' => 'CustomVariables_CustomVariables', 'name' => Piwik::translate('CustomVariables_ColumnCustomVariableName') . ' ' . $i . ' (' . Piwik::translate('CustomVariables_ScopePage') . ')', 'segment' => 'customVariablePageName' . $i, 'sqlSegment' => 'log_link_visit_action.custom_var_k' . $i, ); $segments[] = array( 'type' => 'dimension', 'category' => 'CustomVariables_CustomVariables', 'name' => Piwik::translate('CustomVariables_ColumnCustomVariableValue') . ' ' . $i . ' (' . Piwik::translate('CustomVariables_ScopePage') . ')', 'segment' => 'customVariablePageValue' . $i, 'sqlSegment' => 'log_link_visit_action.custom_var_v' . $i, ); } } }
gpl-3.0
corumcorp/redsentir
redsentir/static/juego/frameworks/cocos2d-html5/cocos2d/core/event-manager/CCEventManager.js
40896
/**************************************************************************** Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2015 Chukong Technologies Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ (function () { /** * @ignore */ cc._EventListenerVector = cc.Class.extend({ _fixedListeners: null, _sceneGraphListeners: null, gt0Index: 0, ctor: function () { this._fixedListeners = []; this._sceneGraphListeners = []; }, size: function () { return this._fixedListeners.length + this._sceneGraphListeners.length; }, empty: function () { return (this._fixedListeners.length === 0) && (this._sceneGraphListeners.length === 0); }, push: function (listener) { if (listener._getFixedPriority() === 0) this._sceneGraphListeners.push(listener); else this._fixedListeners.push(listener); }, clearSceneGraphListeners: function () { this._sceneGraphListeners.length = 0; }, clearFixedListeners: function () { this._fixedListeners.length = 0; }, clear: function () { this._sceneGraphListeners.length = 0; this._fixedListeners.length = 0; }, getFixedPriorityListeners: function () { return this._fixedListeners; }, getSceneGraphPriorityListeners: function () { return this._sceneGraphListeners; } }); function __getListenerID (event) { var eventType = cc.Event, getType = event._type; if (getType === eventType.ACCELERATION) return cc._EventListenerAcceleration.LISTENER_ID; if (getType === eventType.CUSTOM) return event._eventName; if (getType === eventType.KEYBOARD) return cc._EventListenerKeyboard.LISTENER_ID; if (getType === eventType.MOUSE) return cc._EventListenerMouse.LISTENER_ID; if (getType === eventType.FOCUS) return cc._EventListenerFocus.LISTENER_ID; if (getType === eventType.TOUCH) { // Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. // return UNKNOWN instead. cc.log(cc._LogInfos.__getListenerID); } return ""; } /** * <p> * cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching. <br/> * <br/> * The EventListener list is managed in such way so that event listeners can be added and removed <br/> * while events are being dispatched. * </p> * @class * @name cc.eventManager */ cc.eventManager = /** @lends cc.eventManager# */{ //Priority dirty flag DIRTY_NONE: 0, DIRTY_FIXED_PRIORITY: 1 << 0, DIRTY_SCENE_GRAPH_PRIORITY: 1 << 1, DIRTY_ALL: 3, _listenersMap: {}, _priorityDirtyFlagMap: {}, _nodeListenersMap: {}, _nodePriorityMap: {}, _globalZOrderNodeMap: {}, _toAddedListeners: [], _toRemovedListeners: [], _dirtyNodes: [], _inDispatch: 0, _isEnabled: false, _nodePriorityIndex: 0, _internalCustomListenerIDs: [cc.game.EVENT_HIDE, cc.game.EVENT_SHOW], _setDirtyForNode: function (node) { // Mark the node dirty only when there is an event listener associated with it. if (this._nodeListenersMap[node.__instanceId] != null) this._dirtyNodes.push(node); var _children = node.getChildren(); for(var i = 0, len = _children.length; i < len; i++) this._setDirtyForNode(_children[i]); }, /** * Pauses all listeners which are associated the specified target. * @param {cc.Node} node * @param {Boolean} [recursive=false] */ pauseTarget: function (node, recursive) { var listeners = this._nodeListenersMap[node.__instanceId], i, len; if (listeners) { for (i = 0, len = listeners.length; i < len; i++) listeners[i]._setPaused(true); } if (recursive === true) { var locChildren = node.getChildren(); for (i = 0, len = locChildren.length; i < len; i++) this.pauseTarget(locChildren[i], true); } }, /** * Resumes all listeners which are associated the specified target. * @param {cc.Node} node * @param {Boolean} [recursive=false] */ resumeTarget: function (node, recursive) { var listeners = this._nodeListenersMap[node.__instanceId], i, len; if (listeners) { for (i = 0, len = listeners.length; i < len; i++) listeners[i]._setPaused(false); } this._setDirtyForNode(node); if (recursive === true) { var locChildren = node.getChildren(); for (i = 0, len = locChildren.length; i< len; i++) this.resumeTarget(locChildren[i], true); } }, _addListener: function (listener) { if (this._inDispatch === 0) this._forceAddEventListener(listener); else this._toAddedListeners.push(listener); }, _forceAddEventListener: function (listener) { var listenerID = listener._getListenerID(); var listeners = this._listenersMap[listenerID]; if (!listeners) { listeners = new cc._EventListenerVector(); this._listenersMap[listenerID] = listeners; } listeners.push(listener); if (listener._getFixedPriority() === 0) { this._setDirty(listenerID, this.DIRTY_SCENE_GRAPH_PRIORITY); var node = listener._getSceneGraphPriority(); if (node === null) cc.log(cc._LogInfos.eventManager__forceAddEventListener); this._associateNodeAndEventListener(node, listener); if (node.isRunning()) this.resumeTarget(node); } else this._setDirty(listenerID, this.DIRTY_FIXED_PRIORITY); }, _getListeners: function (listenerID) { return this._listenersMap[listenerID]; }, _updateDirtyFlagForSceneGraph: function () { if (this._dirtyNodes.length === 0) return; var locDirtyNodes = this._dirtyNodes, selListeners, selListener, locNodeListenersMap = this._nodeListenersMap; for (var i = 0, len = locDirtyNodes.length; i < len; i++) { selListeners = locNodeListenersMap[locDirtyNodes[i].__instanceId]; if (selListeners) { for (var j = 0, listenersLen = selListeners.length; j < listenersLen; j++) { selListener = selListeners[j]; if (selListener) this._setDirty(selListener._getListenerID(), this.DIRTY_SCENE_GRAPH_PRIORITY); } } } this._dirtyNodes.length = 0; }, _removeAllListenersInVector: function (listenerVector) { if (!listenerVector) return; var selListener; for (var i = 0; i < listenerVector.length;) { selListener = listenerVector[i]; selListener._setRegistered(false); if (selListener._getSceneGraphPriority() != null) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. } if (this._inDispatch === 0) cc.arrayRemoveObject(listenerVector, selListener); else ++i; } }, _removeListenersForListenerID: function (listenerID) { var listeners = this._listenersMap[listenerID], i; if (listeners) { var fixedPriorityListeners = listeners.getFixedPriorityListeners(); var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); this._removeAllListenersInVector(sceneGraphPriorityListeners); this._removeAllListenersInVector(fixedPriorityListeners); // Remove the dirty flag according the 'listenerID'. // No need to check whether the dispatcher is dispatching event. delete this._priorityDirtyFlagMap[listenerID]; if (!this._inDispatch) { listeners.clear(); } delete this._listenersMap[listenerID]; } var locToAddedListeners = this._toAddedListeners, listener; for (i = 0; i < locToAddedListeners.length;) { listener = locToAddedListeners[i]; if (listener && listener._getListenerID() === listenerID) cc.arrayRemoveObject(locToAddedListeners, listener); else ++i; } }, _sortEventListeners: function (listenerID) { var dirtyFlag = this.DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap; if (locFlagMap[listenerID]) dirtyFlag = locFlagMap[listenerID]; if (dirtyFlag !== this.DIRTY_NONE) { // Clear the dirty flag first, if `rootNode` is null, then set its dirty flag of scene graph priority locFlagMap[listenerID] = this.DIRTY_NONE; if (dirtyFlag & this.DIRTY_FIXED_PRIORITY) this._sortListenersOfFixedPriority(listenerID); if (dirtyFlag & this.DIRTY_SCENE_GRAPH_PRIORITY) { var rootNode = cc.director.getRunningScene(); if (rootNode) this._sortListenersOfSceneGraphPriority(listenerID, rootNode); else locFlagMap[listenerID] = this.DIRTY_SCENE_GRAPH_PRIORITY; } } }, _sortListenersOfSceneGraphPriority: function (listenerID, rootNode) { var listeners = this._getListeners(listenerID); if (!listeners) return; var sceneGraphListener = listeners.getSceneGraphPriorityListeners(); if (!sceneGraphListener || sceneGraphListener.length === 0) return; // Reset priority index this._nodePriorityIndex = 0; this._nodePriorityMap = {}; this._visitTarget(rootNode, true); // After sort: priority < 0, > 0 listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes); }, _sortEventListenersOfSceneGraphPriorityDes: function (l1, l2) { var locNodePriorityMap = cc.eventManager._nodePriorityMap, node1 = l1._getSceneGraphPriority(), node2 = l2._getSceneGraphPriority(); if (!l2 || !node2 || !locNodePriorityMap[node2.__instanceId]) return -1; else if (!l1 || !node1 || !locNodePriorityMap[node1.__instanceId]) return 1; return locNodePriorityMap[l2._getSceneGraphPriority().__instanceId] - locNodePriorityMap[l1._getSceneGraphPriority().__instanceId]; }, _sortListenersOfFixedPriority: function (listenerID) { var listeners = this._listenersMap[listenerID]; if (!listeners) return; var fixedListeners = listeners.getFixedPriorityListeners(); if (!fixedListeners || fixedListeners.length === 0) return; // After sort: priority < 0, > 0 fixedListeners.sort(this._sortListenersOfFixedPriorityAsc); // FIXME: Should use binary search var index = 0; for (var len = fixedListeners.length; index < len;) { if (fixedListeners[index]._getFixedPriority() >= 0) break; ++index; } listeners.gt0Index = index; }, _sortListenersOfFixedPriorityAsc: function (l1, l2) { return l1._getFixedPriority() - l2._getFixedPriority(); }, _onUpdateListeners: function (listeners) { var fixedPriorityListeners = listeners.getFixedPriorityListeners(); var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); var i, selListener, idx, toRemovedListeners = this._toRemovedListeners; if (sceneGraphPriorityListeners) { for (i = 0; i < sceneGraphPriorityListeners.length;) { selListener = sceneGraphPriorityListeners[i]; if (!selListener._isRegistered()) { cc.arrayRemoveObject(sceneGraphPriorityListeners, selListener); // if item in toRemove list, remove it from the list idx = toRemovedListeners.indexOf(selListener); if(idx !== -1) toRemovedListeners.splice(idx, 1); } else ++i; } } if (fixedPriorityListeners) { for (i = 0; i < fixedPriorityListeners.length;) { selListener = fixedPriorityListeners[i]; if (!selListener._isRegistered()) { cc.arrayRemoveObject(fixedPriorityListeners, selListener); // if item in toRemove list, remove it from the list idx = toRemovedListeners.indexOf(selListener); if(idx !== -1) toRemovedListeners.splice(idx, 1); } else ++i; } } if (sceneGraphPriorityListeners && sceneGraphPriorityListeners.length === 0) listeners.clearSceneGraphListeners(); if (fixedPriorityListeners && fixedPriorityListeners.length === 0) listeners.clearFixedListeners(); }, frameUpdateListeners: function () { var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap; for (var selKey in locListenersMap) { if (locListenersMap[selKey].empty()) { delete locPriorityDirtyFlagMap[selKey]; delete locListenersMap[selKey]; } } var locToAddedListeners = this._toAddedListeners; if (locToAddedListeners.length !== 0) { for (var i = 0, len = locToAddedListeners.length; i < len; i++) this._forceAddEventListener(locToAddedListeners[i]); locToAddedListeners.length = 0; } if (this._toRemovedListeners.length !== 0) { this._cleanToRemovedListeners(); } }, _updateTouchListeners: function (event) { var locInDispatch = this._inDispatch; cc.assert(locInDispatch > 0, cc._LogInfos.EventManager__updateListeners); if (locInDispatch > 1) return; var listeners; listeners = this._listenersMap[cc._EventListenerTouchOneByOne.LISTENER_ID]; if (listeners) { this._onUpdateListeners(listeners); } listeners = this._listenersMap[cc._EventListenerTouchAllAtOnce.LISTENER_ID]; if (listeners) { this._onUpdateListeners(listeners); } cc.assert(locInDispatch === 1, cc._LogInfos.EventManager__updateListeners_2); var locToAddedListeners = this._toAddedListeners; if (locToAddedListeners.length !== 0) { for (var i = 0, len = locToAddedListeners.length; i < len; i++) this._forceAddEventListener(locToAddedListeners[i]); locToAddedListeners.length = 0; } if (this._toRemovedListeners.length !== 0) { this._cleanToRemovedListeners(); } }, //Remove all listeners in _toRemoveListeners list and cleanup _cleanToRemovedListeners: function () { var toRemovedListeners = this._toRemovedListeners; for (var i = 0; i < toRemovedListeners.length; i++) { var selListener = toRemovedListeners[i]; var listeners = this._listenersMap[selListener._getListenerID()]; if (!listeners) continue; var idx, fixedPriorityListeners = listeners.getFixedPriorityListeners(), sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); if (sceneGraphPriorityListeners) { idx = sceneGraphPriorityListeners.indexOf(selListener); if (idx !== -1) { sceneGraphPriorityListeners.splice(idx, 1); } } if (fixedPriorityListeners) { idx = fixedPriorityListeners.indexOf(selListener); if (idx !== -1) { fixedPriorityListeners.splice(idx, 1); } } } toRemovedListeners.length = 0; }, _onTouchEventCallback: function (listener, argsObj) { // Skip if the listener was removed. if (!listener._isRegistered) return false; var event = argsObj.event, selTouch = argsObj.selTouch; event._setCurrentTarget(listener._node); var isClaimed = false, removedIdx; var getCode = event.getEventCode(), eventCode = cc.EventTouch.EventCode; if (getCode === eventCode.BEGAN) { if (listener.onTouchBegan) { isClaimed = listener.onTouchBegan(selTouch, event); if (isClaimed && listener._registered) listener._claimedTouches.push(selTouch); } } else if (listener._claimedTouches.length > 0 && ((removedIdx = listener._claimedTouches.indexOf(selTouch)) !== -1)) { isClaimed = true; if (getCode === eventCode.MOVED && listener.onTouchMoved) { listener.onTouchMoved(selTouch, event); } else if (getCode === eventCode.ENDED) { if (listener.onTouchEnded) listener.onTouchEnded(selTouch, event); if (listener._registered) listener._claimedTouches.splice(removedIdx, 1); } else if (getCode === eventCode.CANCELLED) { if (listener.onTouchCancelled) listener.onTouchCancelled(selTouch, event); if (listener._registered) listener._claimedTouches.splice(removedIdx, 1); } } // If the event was stopped, return directly. if (event.isStopped()) { cc.eventManager._updateTouchListeners(event); return true; } if (isClaimed && listener._registered && listener.swallowTouches) { if (argsObj.needsMutableSet) argsObj.touches.splice(selTouch, 1); return true; } return false; }, _dispatchTouchEvent: function (event) { this._sortEventListeners(cc._EventListenerTouchOneByOne.LISTENER_ID); this._sortEventListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID); var oneByOneListeners = this._getListeners(cc._EventListenerTouchOneByOne.LISTENER_ID); var allAtOnceListeners = this._getListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID); // If there aren't any touch listeners, return directly. if (null === oneByOneListeners && null === allAtOnceListeners) return; var originalTouches = event.getTouches(), mutableTouches = cc.copyArray(originalTouches); var oneByOneArgsObj = {event: event, needsMutableSet: (oneByOneListeners && allAtOnceListeners), touches: mutableTouches, selTouch: null}; // // process the target handlers 1st // if (oneByOneListeners) { for (var i = 0; i < originalTouches.length; i++) { oneByOneArgsObj.selTouch = originalTouches[i]; this._dispatchEventToListeners(oneByOneListeners, this._onTouchEventCallback, oneByOneArgsObj); if (event.isStopped()) return; } } // // process standard handlers 2nd // if (allAtOnceListeners && mutableTouches.length > 0) { this._dispatchEventToListeners(allAtOnceListeners, this._onTouchesEventCallback, {event: event, touches: mutableTouches}); if (event.isStopped()) return; } this._updateTouchListeners(event); }, _onTouchesEventCallback: function (listener, callbackParams) { // Skip if the listener was removed. if (!listener._registered) return false; var eventCode = cc.EventTouch.EventCode, event = callbackParams.event, touches = callbackParams.touches, getCode = event.getEventCode(); event._setCurrentTarget(listener._node); if (getCode === eventCode.BEGAN && listener.onTouchesBegan) listener.onTouchesBegan(touches, event); else if (getCode === eventCode.MOVED && listener.onTouchesMoved) listener.onTouchesMoved(touches, event); else if (getCode === eventCode.ENDED && listener.onTouchesEnded) listener.onTouchesEnded(touches, event); else if (getCode === eventCode.CANCELLED && listener.onTouchesCancelled) listener.onTouchesCancelled(touches, event); // If the event was stopped, return directly. if (event.isStopped()) { cc.eventManager._updateTouchListeners(event); return true; } return false; }, _associateNodeAndEventListener: function (node, listener) { var listeners = this._nodeListenersMap[node.__instanceId]; if (!listeners) { listeners = []; this._nodeListenersMap[node.__instanceId] = listeners; } listeners.push(listener); }, _dissociateNodeAndEventListener: function (node, listener) { var listeners = this._nodeListenersMap[node.__instanceId]; if (listeners) { cc.arrayRemoveObject(listeners, listener); if (listeners.length === 0) delete this._nodeListenersMap[node.__instanceId]; } }, _dispatchEventToListeners: function (listeners, onEvent, eventOrArgs) { var shouldStopPropagation = false; var fixedPriorityListeners = listeners.getFixedPriorityListeners(); var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); var i = 0, j, selListener; if (fixedPriorityListeners) { // priority < 0 if (fixedPriorityListeners.length !== 0) { for (; i < listeners.gt0Index; ++i) { selListener = fixedPriorityListeners[i]; if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { shouldStopPropagation = true; break; } } } } if (sceneGraphPriorityListeners && !shouldStopPropagation) { // priority == 0, scene graph priority for (j = 0; j < sceneGraphPriorityListeners.length; j++) { selListener = sceneGraphPriorityListeners[j]; if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { shouldStopPropagation = true; break; } } } if (fixedPriorityListeners && !shouldStopPropagation) { // priority > 0 for (; i < fixedPriorityListeners.length; ++i) { selListener = fixedPriorityListeners[i]; if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) { shouldStopPropagation = true; break; } } } }, _setDirty: function (listenerID, flag) { var locDirtyFlagMap = this._priorityDirtyFlagMap; if (locDirtyFlagMap[listenerID] == null) locDirtyFlagMap[listenerID] = flag; else locDirtyFlagMap[listenerID] = flag | locDirtyFlagMap[listenerID]; }, _visitTarget: function (node, isRootNode) { var children = node.getChildren(), i = 0; var childrenCount = children.length, locGlobalZOrderNodeMap = this._globalZOrderNodeMap, locNodeListenersMap = this._nodeListenersMap; if (childrenCount > 0) { var child; // visit children zOrder < 0 for (; i < childrenCount; i++) { child = children[i]; if (child && child.getLocalZOrder() < 0) this._visitTarget(child, false); else break; } if (locNodeListenersMap[node.__instanceId] != null) { if (!locGlobalZOrderNodeMap[node.getGlobalZOrder()]) locGlobalZOrderNodeMap[node.getGlobalZOrder()] = []; locGlobalZOrderNodeMap[node.getGlobalZOrder()].push(node.__instanceId); } for (; i < childrenCount; i++) { child = children[i]; if (child) this._visitTarget(child, false); } } else { if (locNodeListenersMap[node.__instanceId] != null) { if (!locGlobalZOrderNodeMap[node.getGlobalZOrder()]) locGlobalZOrderNodeMap[node.getGlobalZOrder()] = []; locGlobalZOrderNodeMap[node.getGlobalZOrder()].push(node.__instanceId); } } if (isRootNode) { var globalZOrders = []; for (var selKey in locGlobalZOrderNodeMap) globalZOrders.push(selKey); globalZOrders.sort(this._sortNumberAsc); var zOrdersLen = globalZOrders.length, selZOrders, j, locNodePriorityMap = this._nodePriorityMap; for (i = 0; i < zOrdersLen; i++) { selZOrders = locGlobalZOrderNodeMap[globalZOrders[i]]; for (j = 0; j < selZOrders.length; j++) locNodePriorityMap[selZOrders[j]] = ++this._nodePriorityIndex; } this._globalZOrderNodeMap = {}; } }, _sortNumberAsc: function (a, b) { return a - b; }, /** * <p> * Adds a event listener for a specified event. <br/> * if the parameter "nodeOrPriority" is a node, it means to add a event listener for a specified event with the priority of scene graph. <br/> * if the parameter "nodeOrPriority" is a Number, it means to add a event listener for a specified event with the fixed priority. <br/> * </p> * @param {cc.EventListener|Object} listener The listener of a specified event or a object of some event parameters. * @param {cc.Node|Number} nodeOrPriority The priority of the listener is based on the draw order of this node or fixedPriority The fixed priority of the listener. * @note The priority of scene graph will be fixed value 0. So the order of listener item in the vector will be ' <0, scene graph (0 priority), >0'. * A lower priority will be called before the ones that have a higher value. 0 priority is forbidden for fixed priority since it's used for scene graph based priority. * The listener must be a cc.EventListener object when adding a fixed priority listener, because we can't remove a fixed priority listener without the listener handler, * except calls removeAllListeners(). * @return {cc.EventListener} Return the listener. Needed in order to remove the event from the dispatcher. */ addListener: function (listener, nodeOrPriority) { cc.assert(listener && nodeOrPriority, cc._LogInfos.eventManager_addListener_2); if (!(listener instanceof cc.EventListener)) { cc.assert(!cc.isNumber(nodeOrPriority), cc._LogInfos.eventManager_addListener_3); listener = cc.EventListener.create(listener); } else { if (listener._isRegistered()) { cc.log(cc._LogInfos.eventManager_addListener_4); return; } } if (!listener.checkAvailable()) return; if (cc.isNumber(nodeOrPriority)) { if (nodeOrPriority === 0) { cc.log(cc._LogInfos.eventManager_addListener); return; } listener._setSceneGraphPriority(null); listener._setFixedPriority(nodeOrPriority); listener._setRegistered(true); listener._setPaused(false); this._addListener(listener); } else { listener._setSceneGraphPriority(nodeOrPriority); listener._setFixedPriority(0); listener._setRegistered(true); this._addListener(listener); } return listener; }, /** * Adds a Custom event listener. It will use a fixed priority of 1. * @param {string} eventName * @param {function} callback * @return {cc.EventListener} the generated event. Needed in order to remove the event from the dispatcher */ addCustomListener: function (eventName, callback, target) { var listener = new cc._EventListenerCustom(eventName, callback, target); this.addListener(listener, 1); return listener; }, /** * Remove a listener * @param {cc.EventListener} listener an event listener or a registered node target */ removeListener: function (listener) { if (listener == null) return; var isFound, locListener = this._listenersMap; for (var selKey in locListener) { var listeners = locListener[selKey]; var fixedPriorityListeners = listeners.getFixedPriorityListeners(), sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners(); isFound = this._removeListenerInVector(sceneGraphPriorityListeners, listener); if (isFound){ // fixed #4160: Dirty flag need to be updated after listeners were removed. this._setDirty(listener._getListenerID(), this.DIRTY_SCENE_GRAPH_PRIORITY); }else{ isFound = this._removeListenerInVector(fixedPriorityListeners, listener); if (isFound) this._setDirty(listener._getListenerID(), this.DIRTY_FIXED_PRIORITY); } if (listeners.empty()) { delete this._priorityDirtyFlagMap[listener._getListenerID()]; delete locListener[selKey]; } if (isFound) break; } if (!isFound) { var locToAddedListeners = this._toAddedListeners; for (var i = 0, len = locToAddedListeners.length; i < len; i++) { var selListener = locToAddedListeners[i]; if (selListener === listener) { cc.arrayRemoveObject(locToAddedListeners, selListener); selListener._setRegistered(false); break; } } } }, _removeListenerInCallback: function (listeners, callback) { if (listeners == null) return false; for (var i = 0, len = listeners.length; i < len; i++) { var selListener = listeners[i]; if (selListener._onCustomEvent === callback || selListener._onEvent === callback) { selListener._setRegistered(false); if (selListener._getSceneGraphPriority() != null) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. } if (this._inDispatch === 0) cc.arrayRemoveObject(listeners, selListener); return true; } } return false; }, _removeListenerInVector: function (listeners, listener) { if (listeners == null) return false; for (var i = 0, len = listeners.length; i < len; i++) { var selListener = listeners[i]; if (selListener === listener) { selListener._setRegistered(false); if (selListener._getSceneGraphPriority() != null) { this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener); selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes. } if (this._inDispatch === 0) cc.arrayRemoveObject(listeners, selListener); else this._toRemovedListeners.push(selListener); return true; } } return false; }, /** * Removes all listeners with the same event listener type or removes all listeners of a node * @param {Number|cc.Node} listenerType listenerType or a node * @param {Boolean} [recursive=false] */ removeListeners: function (listenerType, recursive) { var _t = this; if (listenerType instanceof cc.Node) { // Ensure the node is removed from these immediately also. // Don't want any dangling pointers or the possibility of dealing with deleted objects.. delete _t._nodePriorityMap[listenerType.__instanceId]; cc.arrayRemoveObject(_t._dirtyNodes, listenerType); var listeners = _t._nodeListenersMap[listenerType.__instanceId], i; if (listeners) { var listenersCopy = cc.copyArray(listeners); for (i = 0; i < listenersCopy.length; i++) _t.removeListener(listenersCopy[i]); listenersCopy.length = 0; } // Bug fix: ensure there are no references to the node in the list of listeners to be added. // If we find any listeners associated with the destroyed node in this list then remove them. // This is to catch the scenario where the node gets destroyed before it's listener // is added into the event dispatcher fully. This could happen if a node registers a listener // and gets destroyed while we are dispatching an event (touch etc.) var locToAddedListeners = _t._toAddedListeners; for (i = 0; i < locToAddedListeners.length; ) { var listener = locToAddedListeners[i]; if (listener._getSceneGraphPriority() === listenerType) { listener._setSceneGraphPriority(null); // Ensure no dangling ptr to the target node. listener._setRegistered(false); locToAddedListeners.splice(i, 1); } else ++i; } if (recursive === true) { var locChildren = listenerType.getChildren(), len; for (i = 0, len = locChildren.length; i< len; i++) _t.removeListeners(locChildren[i], true); } } else { if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) _t._removeListenersForListenerID(cc._EventListenerTouchOneByOne.LISTENER_ID); else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) _t._removeListenersForListenerID(cc._EventListenerTouchAllAtOnce.LISTENER_ID); else if (listenerType === cc.EventListener.MOUSE) _t._removeListenersForListenerID(cc._EventListenerMouse.LISTENER_ID); else if (listenerType === cc.EventListener.ACCELERATION) _t._removeListenersForListenerID(cc._EventListenerAcceleration.LISTENER_ID); else if (listenerType === cc.EventListener.KEYBOARD) _t._removeListenersForListenerID(cc._EventListenerKeyboard.LISTENER_ID); else cc.log(cc._LogInfos.eventManager_removeListeners); } }, /** * Removes all custom listeners with the same event name * @param {string} customEventName */ removeCustomListeners: function (customEventName) { this._removeListenersForListenerID(customEventName); }, /** * Removes all listeners */ removeAllListeners: function () { var locListeners = this._listenersMap, locInternalCustomEventIDs = this._internalCustomListenerIDs; for (var selKey in locListeners) { if (locInternalCustomEventIDs.indexOf(selKey) === -1) this._removeListenersForListenerID(selKey); } }, /** * Sets listener's priority with fixed value. * @param {cc.EventListener} listener * @param {Number} fixedPriority */ setPriority: function (listener, fixedPriority) { if (listener == null) return; var locListeners = this._listenersMap; for (var selKey in locListeners) { var selListeners = locListeners[selKey]; var fixedPriorityListeners = selListeners.getFixedPriorityListeners(); if (fixedPriorityListeners) { var found = fixedPriorityListeners.indexOf(listener); if (found !== -1) { if (listener._getSceneGraphPriority() != null) cc.log(cc._LogInfos.eventManager_setPriority); if (listener._getFixedPriority() !== fixedPriority) { listener._setFixedPriority(fixedPriority); this._setDirty(listener._getListenerID(), this.DIRTY_FIXED_PRIORITY); } return; } } } }, /** * Whether to enable dispatching events * @param {boolean} enabled */ setEnabled: function (enabled) { this._isEnabled = enabled; }, /** * Checks whether dispatching events is enabled * @returns {boolean} */ isEnabled: function () { return this._isEnabled; }, /** * Dispatches the event, also removes all EventListeners marked for deletion from the event dispatcher list. * @param {cc.Event} event */ dispatchEvent: function (event) { if (!this._isEnabled) return; this._updateDirtyFlagForSceneGraph(); this._inDispatch++; if (!event || !event.getType) throw new Error("event is undefined"); if (event._type === cc.Event.TOUCH) { this._dispatchTouchEvent(event); this._inDispatch--; return; } var listenerID = __getListenerID(event); this._sortEventListeners(listenerID); var selListeners = this._listenersMap[listenerID]; if (selListeners) { this._dispatchEventToListeners(selListeners, this._onListenerCallback, event); this._onUpdateListeners(selListeners); } this._inDispatch--; }, _onListenerCallback: function (listener, event) { event._setCurrentTarget(listener._getSceneGraphPriority()); listener._onEvent(event); return event.isStopped(); }, /** * Dispatches a Custom Event with a event name an optional user data * @param {string} eventName * @param {*} optionalUserData */ dispatchCustomEvent: function (eventName, optionalUserData) { var ev = new cc.EventCustom(eventName); ev.setUserData(optionalUserData); this.dispatchEvent(ev); } }; })();
gpl-3.0
w3ggy/ParentControl
app/src/main/java/com/abramov/artyom/parentcontrol/ui/sms/SmsAdapter.java
1527
package com.abramov.artyom.parentcontrol.ui.sms; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.abramov.artyom.parentcontrol.R; import com.abramov.artyom.parentcontrol.domain.Sms; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class SmsAdapter extends RecyclerView.Adapter<SmsAdapter.SmsViewHolder> { private List<Sms> mSmsList; public SmsAdapter(List<Sms> smsList) { mSmsList = smsList; } @Override public SmsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_sms, parent, false); return new SmsViewHolder(view); } @Override public void onBindViewHolder(SmsViewHolder holder, int position) { holder.init(mSmsList.get(position)); } @Override public int getItemCount() { return mSmsList == null ? 0 : mSmsList.size(); } class SmsViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.sms_name) TextView mName; @BindView(R.id.sms_text) TextView mText; public SmsViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } void init(Sms sms) { mName.setText(sms.getAuthor()); mText.setText(sms.getMessage()); } } }
gpl-3.0
kyrelos/vitelco-mobile-money-wallet
app_dir/bill_management/migrations/0004_bill_bill_status.py
533
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-23 10:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bill_management', '0003_auto_20170323_0214'), ] operations = [ migrations.AddField( model_name='bill', name='bill_status', field=models.CharField(choices=[(b'unpaid', b'updaid'), (b'paid', b'paid')], default=b'unpaid', max_length=20), ), ]
gpl-3.0
icuseven/MMRDS
source-code/mmria/mmria.services/Actors/BatchProcessor.cs
27704
using System; using System.Collections.Generic; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System.Linq; using System.Text; using Akka.Actor; namespace RecordsProcessor_Worker.Actors { /* const mor_max_length = 5000; const nat_max_length = 4000; const fet_max_length = 6000; function validate_length(p_array, p_max_length) { let result = true; for(let i = 0; i < p_array.length; i++) { let item = p_array[i]; if(item.l != p_max_length) { result = false; break; } } return result; } */ public class BatchProcessor : ReceiveActor { string _id; private int my_count = -1; const int mor_max_length = 5001; const int nat_max_length = 4001; const int fet_max_length = 6001; HashSet<string> g_cdc_identifier_set = new(); IConfiguration configuration; ILogger logger; mmria.common.couchdb.DBConfigurationDetail item_db_info; protected override void PreStart() => Console.WriteLine("Process_Message started"); protected override void PostStop() => Console.WriteLine("Process_Message stopped"); private Dictionary<string, (string, mmria.common.ije.BatchItem)> batch_item_set = new (StringComparer.OrdinalIgnoreCase); private mmria.common.ije.Batch batch; public BatchProcessor() { Receive<mmria.common.ije.NewIJESet_Message>(message => { Process_Message(message); }); Receive<mmria.common.ije.BatchItem>(message => { Process_Message(message); }); Receive<mmria.common.ije.BatchRemoveDataMessage>(message => { Process_Message(message); }); } public BatchProcessor(string p_id):base() { _id = p_id; //IConfiguration p_configuration //configuration = p_configuration; //logger = p_logger; } private void Process_Message(mmria.common.ije.NewIJESet_Message message) { Console.WriteLine($"Processing Message : {message}"); var mor_set = message.mor.Split("\n"); var status_builder = new System.Text.StringBuilder(); var is_valid_file_name = false; var mor_length_is_valid = validate_length(message?.mor?.Split("\n"), mor_max_length); var nat_length_is_valid = validate_length(message?.nat?.Split("\n"), nat_max_length); var fet_length_is_valid = validate_length(message?.fet?.Split("\n"), fet_max_length); var patt = new System.Text.RegularExpressions.Regex("20[0-9]{2}_[0-2][0-9]_[0-3][0-9]_[A-Z,a-z]{2}.[mM][oO][rR]"); if (patt.Match(message.mor_file_name).Length == 0) { status_builder.AppendLine("mor file name format incorrect. File name must be in Year_Month_Day_StateCode format. (e.g. 2021_01_01_KS.mor"); } if(!mor_length_is_valid) status_builder.AppendLine("mor length is invalid."); if(!nat_length_is_valid) status_builder.AppendLine("nat length is invalid."); if(!fet_length_is_valid) status_builder.AppendLine("fet length is invalid."); var ReportingState = get_state_from_file_name(message.mor_file_name); var ImportDate = DateTime.Now; mmria.common.couchdb.ConfigurationSet db_config_set = mmria.services.vitalsimport.Program.DbConfigSet; if(db_config_set.detail_list.ContainsKey(ReportingState)) { is_valid_file_name = true; item_db_info = db_config_set.detail_list[ReportingState]; } else { status_builder.AppendLine($"Invalid reporting state {ReportingState}"); } string[] nat_list = message?.nat?.Split("\n"); string[] fet_list = message?.fet?.Split("\n"); if(nat_list == null) { nat_list = new string[0]; } if(fet_list == null) { fet_list = new string[0]; } var duplicate_count = new Dictionary<string,int>(StringComparer.OrdinalIgnoreCase); var duplicate_is_found = false; HashSet<string> ExistingRecordIds = null; if(ExistingRecordIds == null) { ExistingRecordIds = GetExistingRecordIds(); } foreach(var row in mor_set) { if(row.Length == mor_max_length) { var batch_item = Convert(row, ImportDate, message.mor_file_name, ReportingState, ExistingRecordIds); string record_id; if(batch_item_set.ContainsKey(batch_item.CDCUniqueID)) { duplicate_is_found = true; duplicate_count[batch_item.CDCUniqueID]+= 1; continue; } g_cdc_identifier_set.Add(batch_item.CDCUniqueID?.Trim()); batch_item_set.Add(batch_item.CDCUniqueID?.Trim(), (row, batch_item)); duplicate_count[batch_item.CDCUniqueID] = 1; } } if(duplicate_is_found) { status_builder.AppendLine("Invalid batch duplicates were found:"); foreach(var kvp in duplicate_count) { if(kvp.Value > 1) { status_builder.AppendLine($"duplicate {kvp.Key}: {kvp.Value}"); } } } foreach(var item in validate_AssociatedNAT(nat_list)) status_builder.AppendLine(item); foreach(var item in validate_AssociatedFET(nat_list)) status_builder.AppendLine(item); if(status_builder.Length == 0) { foreach(var kvp in batch_item_set) { var batch_tuple = kvp.Value; try { var StartBatchItemMessage = new mmria.common.ije.StartBatchItemMessage() { cdc_unique_id = batch_tuple.Item2.CDCUniqueID, record_id = batch_tuple.Item2.mmria_record_id, ImportDate = ImportDate, ImportFileName = message.mor_file_name, host_state = ReportingState, mor = batch_tuple.Item1, nat = GetAssociatedNat(nat_list, batch_tuple.Item2.CDCUniqueID?.Trim()), fet = GetAssociatedFet(fet_list, batch_tuple.Item2.CDCUniqueID?.Trim()) }; var batch_item_processor = Context.ActorOf<RecordsProcessor_Worker.Actors.BatchItemProcessor>(batch_tuple.Item2.CDCUniqueID?.Trim()); batch_item_processor.Tell(StartBatchItemMessage); } catch(Exception ex) { } } batch = new mmria.common.ije.Batch() { id = message.batch_id, date_created = DateTime.UtcNow, created_by = "vital-import", date_last_updated = DateTime.UtcNow, last_updated_by = "vital-import", Status = mmria.common.ije.Batch.StatusEnum.Validating, reporting_state = ReportingState, ImportDate = ImportDate, mor_file_name = message.mor_file_name, nat_file_name = message.nat_file_name, fet_file_name = message.fet_file_name, StatusInfo = status_builder.ToString(), record_result = Convert(batch_item_set) }; var BatchStatusMessage = new mmria.common.ije.BatchStatusMessage() { id = batch.id, status = batch.Status }; Context.ActorSelection("akka://mmria-actor-system/user/batch-supervisor").Tell(BatchStatusMessage); } else { batch = new mmria.common.ije.Batch() { id = message.batch_id, date_created = DateTime.UtcNow, created_by = "vital-import", date_last_updated = DateTime.UtcNow, last_updated_by = "vital-import", Status = mmria.common.ije.Batch.StatusEnum.BatchRejected, reporting_state = ReportingState, ImportDate = ImportDate, mor_file_name = message.mor_file_name, nat_file_name = message.nat_file_name, fet_file_name = message.fet_file_name, StatusInfo = status_builder.ToString(), record_result = Convert(batch_item_set) }; var BatchStatusMessage = new mmria.common.ije.BatchStatusMessage() { id = batch.id, status = batch.Status }; Context.ActorSelection("akka://mmria-actor-system/user/batch-supervisor").Tell(BatchStatusMessage); if(save_batch(batch)) { } Context.Stop(this.Self); } } private List<mmria.common.ije.BatchItem> Convert(Dictionary<string,(string, mmria.common.ije.BatchItem)> p_val) { List<mmria.common.ije.BatchItem> result = new(); foreach(var kvp in p_val) { result.Add(kvp.Value.Item2); } return result; } private void Process_Message(mmria.common.ije.BatchItem message) { var new_item = (batch_item_set[message.CDCUniqueID].Item1, message); batch_item_set[message.CDCUniqueID] = new_item; var current_status = batch.Status; int finished_count = 0; foreach(var item in batch_item_set) { if ( item.Value.Item2.Status == mmria.common.ije.BatchItem.StatusEnum.NewCaseAdded || item.Value.Item2.Status == mmria.common.ije.BatchItem.StatusEnum.ExistingCaseSkipped || item.Value.Item2.Status == mmria.common.ije.BatchItem.StatusEnum.ImportFailed ) { finished_count += 1; } } if(finished_count == batch_item_set.Count) { current_status = mmria.common.ije.Batch.StatusEnum.Finished; } var new_batch = new mmria.common.ije.Batch() { id = batch.id, date_created = batch.date_created, created_by = batch.created_by, date_last_updated = DateTime.UtcNow, last_updated_by = batch.last_updated_by, Status = current_status, reporting_state = batch.reporting_state, ImportDate = batch.ImportDate, mor_file_name = batch.mor_file_name, nat_file_name = batch.nat_file_name, fet_file_name = batch.fet_file_name, StatusInfo = batch.StatusInfo, record_result = Convert(batch_item_set) }; batch = new_batch; var BatchStatusMessage = new mmria.common.ije.BatchStatusMessage() { id = batch.id, status = batch.Status }; Context.ActorSelection("akka://mmria-actor-system/user/batch-supervisor").Tell(BatchStatusMessage); if ( current_status == mmria.common.ije.Batch.StatusEnum.Finished || current_status == mmria.common.ije.Batch.StatusEnum.BatchRejected ) { if(save_batch(batch)) { } Context.Stop(this.Self); } } private bool save_batch(mmria.common.ije.Batch p_batch) { bool result = false; Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings (); settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; var object_string = Newtonsoft.Json.JsonConvert.SerializeObject(batch, settings); string put_url = $"{mmria.services.vitalsimport.Program.couchdb_url}/vital_import/{p_batch.id}"; var document_curl = new mmria.getset.cURL ("PUT", null, put_url, object_string, mmria.services.vitalsimport.Program.timer_user_name, mmria.services.vitalsimport.Program.timer_value); try { var responseFromServer = document_curl.execute(); var put_result = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.model.couchdb.document_put_response>(responseFromServer); if(put_result.ok) { result = true; var new_batch = new mmria.common.ije.Batch() { id = batch.id, date_created = batch.date_created, created_by = batch.created_by, date_last_updated = DateTime.UtcNow, last_updated_by = batch.last_updated_by, Status = p_batch.Status, reporting_state = batch.reporting_state, ImportDate = batch.ImportDate, mor_file_name = batch.mor_file_name, nat_file_name = batch.nat_file_name, fet_file_name = batch.fet_file_name, StatusInfo = batch.StatusInfo, record_result = Convert(batch_item_set) }; batch = new_batch; } } catch(Exception ex) { //Console.Write("auth_session_token: {0}", auth_session_token); Console.WriteLine(ex); } return result; } private mmria.common.ije.Batch Get_batch(string _id) { mmria.common.ije.Batch result = null; string put_url = $"{mmria.services.vitalsimport.Program.couchdb_url}/vital_import/{_id}"; var document_curl = new mmria.getset.cURL ("GET", null, put_url, null, mmria.services.vitalsimport.Program.timer_user_name, mmria.services.vitalsimport.Program.timer_value); try { var responseFromServer = document_curl.execute(); result = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.ije.Batch>(responseFromServer); } catch(Exception ex) { //Console.Write("auth_session_token: {0}", auth_session_token); Console.WriteLine(ex); } return result; } private bool Delete_batch(string _id) { bool result = false; var batch = Get_batch(_id); string put_url = $"{mmria.services.vitalsimport.Program.couchdb_url}/vital_import/{_id}?rev={batch._rev}"; var document_curl = new mmria.getset.cURL ("DELETE", null, put_url, null, mmria.services.vitalsimport.Program.timer_user_name, mmria.services.vitalsimport.Program.timer_value); try { var responseFromServer = document_curl.execute(); var delete_result = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject>(responseFromServer); result = true; } catch(Exception ex) { //Console.Write("auth_session_token: {0}", auth_session_token); Console.WriteLine(ex); } return result; } private bool validate_length(IList<string> p_array, int p_max_length) { var result = true; if(p_array != null) for(var i = 0; i < p_array.Count; i++) { var item = p_array[i]; if(item.Length > 0 && item.Length != p_max_length) { result = false; break; } } return result; } IList<string> validate_AssociatedNAT(IList<string> p_array) { var result = new List<string>(); int mom_ssn_start = 2000-1; for (var i = 0; i < p_array.Count; i++) { var item = p_array[i]; if (item.Length > mom_ssn_start + 9) { var mom_ssn = item.Substring(mom_ssn_start, 9).Trim(); if (!g_cdc_identifier_set.Contains(mom_ssn)) { result.Add($"Missing Id in NAT file Line: {i+1} id: {mom_ssn}"); } } } return result; } IList<string> validate_AssociatedFET(IList<string> p_array) { var result = new List<string>(); int mom_ssn_start = 4039-1; for (var i = 0; i < p_array.Count; i++) { var item = p_array[i]; if (item.Length > mom_ssn_start + 9) { var mom_ssn = item.Substring(mom_ssn_start, 9).Trim(); if (!g_cdc_identifier_set.Contains(mom_ssn)) { result.Add($"Missing Id in FET file Line: {i+1} id: {mom_ssn}"); } } } return result; } private mmria.common.ije.BatchItem Convert ( string LineItem, DateTime ImportDate, string ImportFileName, string ReportingState, HashSet<string> ExistingRecordIds ) { /* CDCUniqueID ImportDate ImportFileName ReportingState StateOfDeathRecord DateOfDeath DateOfBirth LastName FirstName MMRIARecordID StatusDetail */ var x = mor_get_header(LineItem); string record_id = null; do { record_id = $"{ReportingState.ToUpper()}-{x["DOD_YR"]}-{GenerateRandomFourDigits().ToString()}"; } while (ExistingRecordIds.Contains(record_id)); ExistingRecordIds.Add(record_id); var result = new mmria.common.ije.BatchItem() { Status = mmria.common.ije.BatchItem.StatusEnum.InProcess, CDCUniqueID = x["SSN"]?.Trim(), mmria_record_id = record_id, ImportDate = ImportDate, ImportFileName = ImportFileName, ReportingState = ReportingState, StateOfDeathRecord = x["DSTATE"], DateOfDeath = $"{x["DOD_YR"]}-{x["DOD_MO"]}-{x["DOD_DY"]}", DateOfBirth = $"{x["DOB_YR"]}-{x["DOB_MO"]}-{x["DOB_DY"]}", LastName = x["LNAME"], FirstName = x["GNAME"]//, //MMRIARecordID = x[""], //StatusDetail = x[""] }; return result; } private string get_state_from_file_name(string p_val) { if(p_val.Length > 15) { return p_val.Substring(11, p_val.Length - 15); } else { return p_val; } } private Dictionary<string,string> mor_get_header(string row) { var result = new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase); /* DState 5 2 DOD_YR 1 4, DOD_MO 237 2, DOD_DY 239 2 DOB_YR 205 4, DOB_MO 209 2, DOD_DY 239 2 LNAME 78 50 GNAME 27 50 */ result.Add("DState",row.Substring(5-1, 2)); result.Add("DOD_YR",row.Substring(1-1, 4)); result.Add("DOD_MO",row.Substring(237-1, 2)); result.Add("DOD_DY",row.Substring(239-1, 2)); result.Add("DOB_YR",row.Substring(205-1, 4)); result.Add("DOB_MO",row.Substring(209-1, 2)); result.Add("DOB_DY",row.Substring(211-1, 2)); result.Add("LNAME",row.Substring(78-1, 50)); result.Add("GNAME",row.Substring(27-1, 50)); result.Add("SSN",row.Substring(191-1, 9)?.Trim()); return result; /* 2 home_record/state of death - DState 3 home_recode/date_of_death - DOD_YR, DOD_MO, DOD_DY 4 death_certificate/date_of_birth - DOB_YR, DOB_MO, DOD_DY 5 home_record/last_name - LNAME 6 home_record/first_name - GNAME*/ } private List<string> GetAssociatedNat(string[] p_nat_list, string p_cdc_unique_id) { var result = new List<string>(); int mom_ssn_start = 2000-1; if (p_nat_list != null) foreach (var item in p_nat_list) { if (item.Length > mom_ssn_start + 9) { var mom_ssn = item.Substring(mom_ssn_start, 9)?.Trim(); if (mom_ssn == p_cdc_unique_id) { result.Add(item); } } } return result; } private List<string> GetAssociatedFet(string[] p_fet_list, string p_cdc_unique_id) { var result = new List<string>(); int mom_ssn_start = 4039-1; if(p_fet_list != null) foreach(var item in p_fet_list) { if(item.Length > mom_ssn_start + 9) { var mom_ssn = item.Substring(mom_ssn_start, 9)?.Trim(); if(mom_ssn == p_cdc_unique_id) { result.Add(item); } } } return result; } private void Process_Message(mmria.common.ije.BatchRemoveDataMessage message) { var config_timer_user_name = mmria.services.vitalsimport.Program.timer_user_name; var config_timer_value = mmria.services.vitalsimport.Program.timer_value; var config_couchdb_url = mmria.services.vitalsimport.Program.couchdb_url; var db_prefix = ""; var batch = Get_batch(message.id); mmria.common.couchdb.ConfigurationSet db_config_set = mmria.services.vitalsimport.Program.DbConfigSet; item_db_info = db_config_set.detail_list[batch.reporting_state]; if(batch.Status != mmria.common.ije.Batch.StatusEnum.BatchRejected) { foreach(var item in batch.record_result) { // remove from db try { string request_string = $"{item_db_info.url}/{item_db_info.prefix}mmrds/_all_docs?include_docs=true"; var case_id = item.mmria_id; var case_expando = GetCaseById(item_db_info, case_id); var rev_dynamic = ((IDictionary<string,object>)case_expando)["_rev"]; string rev = null; if(rev_dynamic != null) { rev = rev_dynamic.ToString(); } if (!string.IsNullOrWhiteSpace (case_id) && !string.IsNullOrWhiteSpace(rev)) { request_string = $"{item_db_info.url}/{item_db_info.prefix}mmrds/{case_id}?rev={rev}"; var case_curl = new mmria.getset.cURL("DELETE", null, request_string, null, item_db_info.user_name, item_db_info.user_value); string responseFromServer = case_curl.execute(); // to do synchronize } } catch(Exception ex) { Console.WriteLine (ex); } } } Delete_batch(message.id); } private System.Dynamic.ExpandoObject GetCaseById(mmria.common.couchdb.DBConfigurationDetail db_info, string case_id) { try { string request_string = $"{db_info.url}/{db_info.prefix}mmrds/_all_docs?include_docs=true"; if (!string.IsNullOrWhiteSpace (case_id)) { request_string = $"{db_info.url}/{db_info.prefix}mmrds/{case_id}"; var case_curl = new mmria.getset.cURL("GET", null, request_string, null, db_info.user_name, db_info.user_value); string responseFromServer = case_curl.execute(); var result = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject> (responseFromServer); return result; } } catch(Exception ex) { Console.WriteLine (ex); } return null; } public HashSet<string> GetExistingRecordIds() { var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase); try { string request_string = $"{item_db_info.url}/{item_db_info.prefix}mmrds/_design/sortable/_view/by_date_created?skip=0&take=25000"; var case_view_curl = new mmria.getset.cURL("GET", null, request_string, null, item_db_info.user_name, item_db_info.user_value); string responseFromServer = case_view_curl.execute(); mmria.common.model.couchdb.case_view_response case_view_response = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.model.couchdb.case_view_response>(responseFromServer); foreach (mmria.common.model.couchdb.case_view_item cvi in case_view_response.rows) { result.Add(cvi.value.record_id); } } catch (Exception ex) { Console.WriteLine(ex); } return result; } private int GenerateRandomFourDigits() { int _min = 1000; int _max = 9999; Random _rdm = new Random(System.DateTime.Now.Millisecond + my_count); my_count ++; return _rdm.Next(_min, _max); } } }
gpl-3.0
ersh112356/ConversationEngine
src/engine/utils/ReplyCleaner.java
3258
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package engine.utils; import java.util.Map; /** * * @author Eran */ public class ReplyCleaner{ /** Holds a dictionary of tags. */ protected Map<String,String> dictionary; /** * The constructor. * * @param dictionary- holds a map of tags. */ public ReplyCleaner(Map<String,String> dictionary){ this.dictionary = dictionary; } /** * Replace given text with variables in the dictionary. * So 'Hi [name]' will become now 'Hi Ana'. * Optionally, [name|Tony] will become Hi Tony if not found inside the dictionary. * * @param text- the text to handle by inserting tag values. * * @return a human representation version of the text. */ public String replaceMatches(String text){ if(text==null) { return null; } final char delim = '|'; final char startDelim = '['; final char endDelim = ']'; int start = 0; int end; while((start=text.indexOf(startDelim,start))>-1) { start++; end = text.indexOf(endDelim,start); if(end>start+1) { String tag = text.substring(start,end); String replacedSection; int pos = tag.indexOf(delim); if(pos>-1) { // Default value was detected. String subtag = tag.substring(0,pos); replacedSection = dictionary.get(subtag); if(replacedSection==null) { // Use the default value. replacedSection = tag.substring(pos+1); } } else { // No default value. replacedSection = dictionary.get(tag); } if(replacedSection!=null) { String beginSection = text.substring(0,start-1); String endSection = text.substring(end+1); text = beginSection + replacedSection + endSection; } } } // Remove empty variables tags. text = clean(text); return text; } /** * Remove any empty tags. * Two types of tags are supported, simple tags in the format of [your_tag]. * And tags with a default value in the format of [your_tag|your_default_value] * * @param text- The text to clean. * * @return the text after being cleaned from empty tags. */ public String clean(String text){ // 1. Clean tasgs with a default value. // 2. Then clean the rest of simple tags. return text.replaceAll("\\[.*\\|(.*)\\]","$1").replaceAll("\\[.*\\]",""); } }
gpl-3.0
ebrelsford/v2v
vacant_to_vibrant/lots/migrations/0012_auto__add_field_lot_polygon_tied_to_parcel.py
34246
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Lot.polygon_tied_to_parcel' db.add_column(u'lots_lot', 'polygon_tied_to_parcel', self.gf('django.db.models.fields.BooleanField')(default=True), keep_default=False) def backwards(self, orm): # Deleting field 'Lot.polygon_tied_to_parcel' db.delete_column(u'lots_lot', 'polygon_tied_to_parcel') models = { u'actstream.action': { 'Meta': {'ordering': "('-timestamp',)", 'object_name': 'Action'}, 'action_object_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'action_object'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}), 'action_object_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'actor_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actor'", 'to': u"orm['contenttypes.ContentType']"}), 'actor_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'data': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'place': ('django.contrib.gis.db.models.fields.PointField', [], {'null': 'True', 'blank': 'True'}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'target_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'target'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}), 'target_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'verb': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'availableproperties.availableproperty': { 'Meta': {'object_name': 'AvailableProperty'}, 'added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'address': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'agency': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'area': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '15', 'decimal_places': '2', 'blank': 'True'}), 'asset_id': ('django.db.models.fields.CharField', [], {'max_length': '10', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'centroid': ('django.contrib.gis.db.models.fields.PointField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_seen': ('django.db.models.fields.DateTimeField', [], {}), 'mapreg': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'price': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '12', 'decimal_places': '2', 'blank': 'True'}), 'price_str': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'new and available'", 'max_length': '30'}) }, u'boundaries.boundary': { 'Meta': {'ordering': "('layer__name', 'label')", 'object_name': 'Boundary'}, 'geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'layer': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['boundaries.Layer']"}), 'simplified_geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {'null': 'True', 'blank': 'True'}) }, u'boundaries.layer': { 'Meta': {'object_name': 'Layer'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '256'}), 'source_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'landuse.landusearea': { 'Meta': {'object_name': 'LandUseArea'}, 'added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'area': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '15', 'decimal_places': '2', 'blank': 'True'}), 'category': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '15'}), 'subcategory': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'vacant_building': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}) }, u'li.location': { 'Meta': {'object_name': 'Location'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'external_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'point': ('django.contrib.gis.db.models.fields.PointField', [], {}), 'zip_code': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}) }, u'licenses.contact': { 'Meta': {'object_name': 'Contact'}, 'address1': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'address2': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'company_name': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'contact_type': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'zip_code': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}) }, u'licenses.license': { 'Meta': {'object_name': 'License'}, 'expires_month': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'expires_year': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'external_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'inactive_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'issued_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'license_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['licenses.LicenseType']"}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['li.Location']"}), 'primary_contact': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['licenses.Contact']", 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}) }, u'licenses.licensetype': { 'Meta': {'object_name': 'LicenseType'}, 'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.TextField', [], {}) }, u'lots.lot': { 'Meta': {'object_name': 'Lot'}, 'added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'address_line1': ('django.db.models.fields.CharField', [], {'max_length': '150', 'null': 'True', 'blank': 'True'}), 'address_line2': ('django.db.models.fields.CharField', [], {'max_length': '150', 'null': 'True', 'blank': 'True'}), 'available_property': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['availableproperties.AvailableProperty']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'billing_account': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['opa.BillingAccount']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'centroid': ('django.contrib.gis.db.models.fields.PointField', [], {'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'city_council_district': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'+'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['boundaries.Boundary']"}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True', 'blank': 'True'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['lots.LotGroup']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'known_use': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['lots.Use']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'known_use_certainty': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'known_use_locked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'land_use_area': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['landuse.LandUseArea']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'licenses': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['licenses.License']", 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['owners.Owner']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'parcel': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['parcels.Parcel']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'planning_district': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'+'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['boundaries.Boundary']"}), 'polygon': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {'null': 'True', 'blank': 'True'}), 'polygon_area': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '15', 'decimal_places': '2', 'blank': 'True'}), 'polygon_tied_to_parcel': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'polygon_width': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'postal_code': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'state_province': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True', 'blank': 'True'}), 'steward_inclusion_opt_in': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'tax_account': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['taxaccounts.TaxAccount']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'violations': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['violations.Violation']", 'null': 'True', 'blank': 'True'}), 'water_parcel': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['waterdept.WaterParcel']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'zoning_district': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['zoning.BaseDistrict']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}) }, u'lots.lotgroup': { 'Meta': {'object_name': 'LotGroup', '_ormbases': [u'lots.Lot']}, u'lot_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['lots.Lot']", 'unique': 'True', 'primary_key': 'True'}) }, u'lots.use': { 'Meta': {'object_name': 'Use'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '200'}), 'visible': ('django.db.models.fields.BooleanField', [], {'default': 'True'}) }, u'opa.accountowner': { 'Meta': {'object_name': 'AccountOwner'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '256'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['owners.Owner']", 'null': 'True', 'blank': 'True'}) }, u'opa.billingaccount': { 'Meta': {'object_name': 'BillingAccount'}, 'account_owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['opa.AccountOwner']", 'null': 'True', 'blank': 'True'}), 'assessment': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '20', 'decimal_places': '2', 'blank': 'True'}), 'external_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'improvement_area': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'improvement_description': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'land_area': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '20', 'decimal_places': '3', 'blank': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'mailing_address': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'mailing_city': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'mailing_country': ('django.db.models.fields.CharField', [], {'default': "'USA'", 'max_length': '40', 'null': 'True', 'blank': 'True'}), 'mailing_name': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'mailing_postal_code': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'mailing_state_province': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True', 'blank': 'True'}), 'property_address': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'sale_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}) }, u'organize.organizertype': { 'Meta': {'object_name': 'OrganizerType'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_group': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}) }, u'owners.agencycode': { 'Meta': {'object_name': 'AgencyCode'}, 'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '256'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, u'owners.alias': { 'Meta': {'object_name': 'Alias'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '256'}) }, u'owners.owner': { 'Meta': {'object_name': 'Owner'}, 'agency_codes': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['owners.AgencyCode']", 'null': 'True', 'blank': 'True'}), 'aliases': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['owners.Alias']", 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '256'}), 'owner_type': ('django.db.models.fields.CharField', [], {'default': "'private'", 'max_length': '20'}) }, u'parcels.parcel': { 'Meta': {'object_name': 'Parcel'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'basereg': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'mapreg': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'stcod': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}) }, u'phillyorganize.organizer': { 'Meta': {'object_name': 'Organizer'}, 'added': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'added_by': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'email_hash': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True', 'blank': 'True'}), 'facebook_page': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}), 'post_publicly': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'receive_text_messages': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['organize.OrganizerType']"}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, u'steward.stewardnotification': { 'Meta': {'object_name': 'StewardNotification'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'facebook_page': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'include_on_map': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'land_tenure_status': ('django.db.models.fields.CharField', [], {'default': "u'not sure'", 'max_length': '50'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}), 'share_contact_details': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'support_organization': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['organize.OrganizerType']"}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'use': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['lots.Use']"}) }, u'steward.stewardproject': { 'Meta': {'object_name': 'StewardProject'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), 'date_started': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'external_id': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'include_on_map': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'land_tenure_status': ('django.db.models.fields.CharField', [], {'default': "u'not sure'", 'max_length': '50'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'organizer': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['phillyorganize.Organizer']", 'null': 'True', 'blank': 'True'}), 'steward_notification': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['steward.StewardNotification']", 'null': 'True', 'blank': 'True'}), 'support_organization': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'use': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['lots.Use']"}) }, u'taxaccounts.taxaccount': { 'Meta': {'object_name': 'TaxAccount'}, 'amount_delinquent': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '15', 'decimal_places': '2', 'blank': 'True'}), 'billing_account': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['opa.BillingAccount']", 'null': 'True', 'blank': 'True'}), 'brt_number': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10'}), 'building_category': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'building_description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'exempt_abate_assessment': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '15', 'decimal_places': '2', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_updated': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'market_value': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '15', 'decimal_places': '2', 'blank': 'True'}), 'max_period': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'min_period': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'owner_name': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'owner_name2': ('django.db.models.fields.CharField', [], {'max_length': '256'}), 'property_address': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'property_city': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'property_postal_code': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'property_state_province': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True', 'blank': 'True'}), 'taxable_assessment': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '15', 'decimal_places': '2', 'blank': 'True'}), 'years_delinquent': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, u'violations.violation': { 'Meta': {'object_name': 'Violation'}, 'case_number': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'external_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['li.Location']"}), 'violation_datetime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'violation_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['violations.ViolationType']"}) }, u'violations.violationtype': { 'Meta': {'object_name': 'ViolationType'}, 'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}), 'full_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'li_description': ('django.db.models.fields.TextField', [], {}) }, u'waterdept.waterparcel': { 'Meta': {'object_name': 'WaterParcel'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'brt_account': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'building_code': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'building_description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'building_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'gross_area': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '20', 'decimal_places': '2', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'impervious_area': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '20', 'decimal_places': '2', 'blank': 'True'}), 'owner1': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'owner2': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'parcel_id': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'ten_code': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}) }, u'zoning.basedistrict': { 'Meta': {'object_name': 'BaseDistrict'}, 'geometry': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'zoning_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['zoning.ZoningType']"}) }, u'zoning.zoningtype': { 'Meta': {'ordering': "('code',)", 'object_name': 'ZoningType'}, 'code': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'group': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'long_code': ('django.db.models.fields.CharField', [], {'max_length': '30'}) } } complete_apps = ['lots']
gpl-3.0
Belxjander/Kirito
LibBitcoin/Explorer/include/bitcoin/explorer/commands/ek-new.hpp
8895
/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin-explorer. * * libbitcoin-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BX_EK_NEW_HPP #define BX_EK_NEW_HPP #include <cstdint> #include <iostream> #include <string> #include <vector> #include <boost/program_options.hpp> #include <bitcoin/bitcoin.hpp> #include <bitcoin/explorer/command.hpp> #include <bitcoin/explorer/define.hpp> #include <bitcoin/explorer/generated.hpp> #include <bitcoin/explorer/primitives/address.hpp> #include <bitcoin/explorer/primitives/base16.hpp> #include <bitcoin/explorer/primitives/base2.hpp> #include <bitcoin/explorer/primitives/base58.hpp> #include <bitcoin/explorer/primitives/base64.hpp> #include <bitcoin/explorer/primitives/base85.hpp> #include <bitcoin/explorer/primitives/btc.hpp> #include <bitcoin/explorer/primitives/btc160.hpp> #include <bitcoin/explorer/primitives/byte.hpp> #include <bitcoin/explorer/primitives/cert_key.hpp> #include <bitcoin/explorer/primitives/ec_private.hpp> #include <bitcoin/explorer/primitives/encoding.hpp> #include <bitcoin/explorer/primitives/endorsement.hpp> #include <bitcoin/explorer/primitives/hashtype.hpp> #include <bitcoin/explorer/primitives/hd_key.hpp> #include <bitcoin/explorer/primitives/header.hpp> #include <bitcoin/explorer/primitives/input.hpp> #include <bitcoin/explorer/primitives/language.hpp> #include <bitcoin/explorer/primitives/output.hpp> #include <bitcoin/explorer/primitives/raw.hpp> #include <bitcoin/explorer/primitives/script.hpp> #include <bitcoin/explorer/primitives/signature.hpp> #include <bitcoin/explorer/primitives/transaction.hpp> #include <bitcoin/explorer/primitives/wrapper.hpp> #include <bitcoin/explorer/utility.hpp> /********* GENERATED SOURCE CODE, DO NOT EDIT EXCEPT EXPERIMENTALLY **********/ namespace libbitcoin { namespace explorer { namespace commands { /** * Various localizable strings. */ #define BX_EK_NEW_SHORT_SEED \ "The seed is less than 192 bits long." /** * Class to implement the ek-new command. */ class BCX_API ek_new : public command { public: /** * The symbolic (not localizable) command name, lower case. */ static const char* symbol() { return "ek-new"; } /** * The member symbolic (not localizable) command name, lower case. */ virtual const char* name() { return ek_new::symbol(); } /** * The localizable command category name, upper case. */ virtual const char* category() { return "KEY_ENCRYPTION"; } /** * The localizable command description. */ virtual const char* description() { return "Create an encrypted private key from an intermediate passphrase token (BIP38)."; } /** * Load program argument definitions. * A value of -1 indicates that the number of instances is unlimited. * @return The loaded program argument definitions. */ virtual arguments_metadata& load_arguments() { return get_argument_metadata() .add("TOKEN", 1) .add("SEED", 1); } /** * Load parameter fallbacks from file or input as appropriate. * @param[in] input The input stream for loading the parameters. * @param[in] The loaded variables. */ virtual void load_fallbacks(std::istream& input, po::variables_map& variables) { const auto raw = requires_raw_input(); load_input(get_seed_argument(), "SEED", variables, input, raw); } /** * Load program option definitions. * BUGBUG: see boost bug/fix: svn.boost.org/trac/boost/ticket/8009 * @return The loaded program option definitions. */ virtual options_metadata& load_options() { using namespace po; options_description& options = get_option_metadata(); options.add_options() ( BX_HELP_VARIABLE ",h", value<bool>()->zero_tokens(), "Get a description and instructions for this command." ) ( BX_CONFIG_VARIABLE ",c", value<boost::filesystem::path>(), "The path to the configuration settings file." ) ( "uncompressed,u", value<bool>(&option_.uncompressed)->zero_tokens(), "Use the uncompressed public key format." ) ( "version,v", value<primitives::byte>(&option_.version)->default_value(0), "The desired payment address version." ) ( "TOKEN", value<bc::wallet::ek_token>(&argument_.token)->required(), "The intermediate passphrase token." ) ( "SEED", value<primitives::base16>(&argument_.seed), "The Base16 entropy for the new encrypted private key. Must be at least 192 bits in length (only the first 192 bits are used). If not specified the seed is read from STDIN." ); return options; } /** * Set variable defaults from configuration variable values. * @param[in] variables The loaded variables. */ virtual void set_defaults_from_config(po::variables_map& variables) { const auto& option_version = variables["version"]; const auto& option_version_config = variables["wallet.pay_to_public_key_hash_version"]; if (option_version.defaulted() && !option_version_config.defaulted()) { option_.version = option_version_config.as<primitives::byte>(); } } /** * Invoke the command. * @param[out] output The input stream for the command execution. * @param[out] error The input stream for the command execution. * @return The appropriate console return code { -1, 0, 1 }. */ virtual console_result invoke(std::ostream& output, std::ostream& cerr); /* Properties */ /** * Get the value of the TOKEN argument. */ virtual bc::wallet::ek_token& get_token_argument() { return argument_.token; } /** * Set the value of the TOKEN argument. */ virtual void set_token_argument( const bc::wallet::ek_token& value) { argument_.token = value; } /** * Get the value of the SEED argument. */ virtual primitives::base16& get_seed_argument() { return argument_.seed; } /** * Set the value of the SEED argument. */ virtual void set_seed_argument( const primitives::base16& value) { argument_.seed = value; } /** * Get the value of the uncompressed option. */ virtual bool& get_uncompressed_option() { return option_.uncompressed; } /** * Set the value of the uncompressed option. */ virtual void set_uncompressed_option( const bool& value) { option_.uncompressed = value; } /** * Get the value of the version option. */ virtual primitives::byte& get_version_option() { return option_.version; } /** * Set the value of the version option. */ virtual void set_version_option( const primitives::byte& value) { option_.version = value; } private: /** * Command line argument bound variables. * Uses cross-compiler safe constructor-based zeroize. * Zeroize for unit test consistency with program_options initialization. */ struct argument { argument() : token(), seed() { } bc::wallet::ek_token token; primitives::base16 seed; } argument_; /** * Command line option bound variables. * Uses cross-compiler safe constructor-based zeroize. * Zeroize for unit test consistency with program_options initialization. */ struct option { option() : uncompressed(), version() { } bool uncompressed; primitives::byte version; } option_; }; } // namespace commands } // namespace explorer } // namespace libbitcoin #endif
gpl-3.0
gizmo75rus/HCS
HCS/Properties/AssemblyInfo.cs
1951
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Управление общими сведениями о сборке осуществляется с помощью // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("HCS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HCS")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми // для COM-компонентов. Если требуется обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("3af820fd-6776-4c74-aa76-f918e60fe456")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номера сборки и редакции по умолчанию // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-3.0
CapsAdmin/pac3
lua/pac3/core/client/base_part.lua
35794
local pac = pac local pairs = pairs local ipairs = ipairs local table = table local Vector = Vector local Angle = Angle local Color = Color local NULL = NULL local SysTime = SysTime local LocalToWorld = LocalToWorld local function SETUP_CACHE_FUNC(tbl, func_name) local old_func = tbl[func_name] local cached_key = "cached_" .. func_name local cached_key2 = "cached_" .. func_name .. "_2" local last_key = "last_" .. func_name .. "_framenumber" tbl[func_name] = function(self, a,b,c,d,e) if self[last_key] ~= pac.FrameNumber or self[cached_key] == nil then self[cached_key], self[cached_key2] = old_func(self, a,b,c,d,e) self[last_key] = pac.FrameNumber end return self[cached_key], self[cached_key2] end end local PART = {} PART.ClassName = "base" PART.Internal = true function PART:__tostring() return string.format("%s[%s][%s][%i]", self.Type, self.ClassName, self.Name, self.Id) end local pac_hide_disturbing = GetConVar("pac_hide_disturbing") pac.GetSet(PART, "BoneIndex") pac.GetSet(PART, "PlayerOwner", NULL) pac.GetSet(PART, "Owner", NULL) pac.StartStorableVars() pac.SetPropertyGroup(PART, "generic") pac.GetSet(PART, "Name", "") pac.GetSet(PART, "Hide", false) pac.GetSet(PART, "OwnerName", "self") pac.GetSet(PART, "EditorExpand", false, {hidden = true}) pac.GetSet(PART, "UniqueID", "", {hidden = true}) pac.GetSet(PART, "IsDisturbing", false, { editor_friendly = "IsExplicit", description = "Marks this content as NSFW, and makes it hidden for most of players who have pac_hide_disturbing set to 1" }) pac.SetPropertyGroup(PART, "orientation") pac.GetSet(PART, "Bone", "head") pac.GetSet(PART, "Position", Vector(0,0,0)) pac.GetSet(PART, "Angles", Angle(0,0,0)) pac.GetSet(PART, "EyeAngles", false) pac.GetSet(PART, "PositionOffset", Vector(0,0,0)) pac.GetSet(PART, "AngleOffset", Angle(0,0,0)) pac.SetupPartName(PART, "AimPart", {editor_panel = "aimpartname"}) pac.SetupPartName(PART, "Parent") pac.SetPropertyGroup(PART, "appearance") pac.GetSet(PART, "Translucent", false) pac.GetSet(PART, "IgnoreZ", false) pac.GetSet(PART, "NoTextureFiltering", false) pac.GetSet(PART, "BlendMode", "", {enums = { none = "one;zero;one;zero", alpha = "src_alpha;one_minus_src_alpha;one;one_minus_src_alpha", multiplicative = "dst_color;zero;dst_color;zero", premultiplied = "one;one_src_minus_alpha;one;one_src_minus_alpha", additive = "src_alpha;one;src_alpha;one", }}) pac.GetSet(PART, "DrawOrder", 0) pac.EndStorableVars() PART.AllowSetupPositionFrameSkip = true local blend_modes = { zero = 0, one = 1, dst_color = 2, one_minus_dst_color = 3, src_alpha = 4, one_minus_src_alpha = 5, dst_alpha = 6, one_minus_dst_alpha = 7, src_alpha_saturate = 8, src_color = 9, one_minus_src_color = 10, } function PART:SetBlendMode(str) str = str:lower():gsub("%s+", ""):gsub(",", ";"):gsub("blend_", "") self.BlendMode = str local tbl = str:Split(";") local src_color local dst_color local src_alpha local dst_alpha if tbl[1] then src_color = blend_modes[tbl[1]] end if tbl[2] then dst_color = blend_modes[tbl[2]] end if tbl[3] then src_alpha = blend_modes[tbl[3]] end if tbl[4] then dst_alpha = blend_modes[tbl[4]] end if src_color and dst_color then self.blend_override = {src_color, dst_color, src_alpha, dst_alpha, tbl[5]} else self.blend_override = nil end end function PART:SetUniqueID(id) if self.owner_id then pac.RemoveUniqueIDPart(self.owner_id, self.UniqueID) end self.UniqueID = id if self.owner_id then pac.SetUniqueIDPart(self.owner_id, id, self) end end function PART:PreInitialize() self.Children = {} self.Children2 = {} self.modifiers = {} self.RootPart = NULL self.DrawOrder = 0 self.hide_disturbing = false self.event_hide_registry = {} self.cached_pos = Vector(0,0,0) self.cached_ang = Angle(0,0,0) end function PART:GetNiceName() return self.ClassName end function PART:RemoveOnNULLOwner(b) self.remove_on_null_owner = b end function PART:GetName() if self.Name == "" then -- recursive call guard if self.last_nice_name_frame and self.last_nice_name_frame == FrameNumber() then return self.last_nice_name end self.last_nice_name_frame = FrameNumber() local nice = self:GetNiceName() local num local count = 0 if self:HasParent() then for _, val in ipairs(self:GetParent():GetChildren()) do if val:GetNiceName() == nice then count = count + 1 if val == self then num = count end end end end if num and count > 1 and num > 1 then nice = nice:Trim() .. " (" .. num - 1 .. ")" end self.last_nice_name = nice return nice end return self.Name end function PART:GetEnabled() local enabled = self:IsEnabled() if self.last_enabled == enabled then return enabled end -- changed if self.last_enabled == nil then self.last_enabled = enabled else self.last_enabled = enabled if enabled then self:CallRecursive("OnShow") else self:CallRecursive("OnHide") end end return enabled end do -- modifiers PART.HandleModifiersManually = false function PART:AddModifier(part) self:RemoveModifier(part) table.insert(self.modifiers, part) end function PART:RemoveModifier(part) for i, v in ipairs(self.modifiers) do if v == part then table.remove(self.modifiers, i) break end end end function PART:ModifiersPreEvent(event) if #self.modifiers > 0 then for _, part in ipairs(self.modifiers) do if not part:IsHidden() then if not part.pre_draw_events then part.pre_draw_events = {} end if not part.pre_draw_events[event] then part.pre_draw_events[event] = "Pre" .. event end if part[part.pre_draw_events[event]] then part[part.pre_draw_events[event]](part) end end end end end function PART:ModifiersPostEvent(event) if #self.modifiers > 0 then for _, part in ipairs(self.modifiers) do if not part:IsHidden() then if not part.post_draw_events then part.post_draw_events = {} end if not part.post_draw_events[event] then part.post_draw_events[event] = "Post" .. event end if part[part.post_draw_events[event]] then part[part.post_draw_events[event]](part) end end end end end end do -- owner function PART:SetPlayerOwner(ply) self.PlayerOwner = ply if ply:IsValid() then self.owner_id = ply:IsPlayer() and ply:UniqueID() or ply:EntIndex() end if not self:HasParent() then self:CheckOwner() end self:SetUniqueID(self:GetUniqueID()) end function PART:SetOwnerName(name) self.OwnerName = name self:CheckOwner() end function PART:CheckOwner(ent, removed) self = self:GetRootPart() local prev_owner = self:GetOwner() if self.Duplicate then ent = pac.HandleOwnerName(self:GetPlayerOwner(), self.OwnerName, ent, self, function(e) return e.pac_duplicate_attach_uid ~= self.UniqueID end) or NULL if ent ~= prev_owner and ent:IsValid() then local tbl = self:ToTable(true) tbl.self.OwnerName = "self" pac.SetupENT(ent) ent:SetShowPACPartsInEditor(false) ent:AttachPACPart(tbl) ent:CallOnRemove("pac_remove_outfit_" .. tbl.self.UniqueID, function() ent:RemovePACPart(tbl) end) if self:GetPlayerOwner() == pac.LocalPlayer then ent:SetPACDrawDistance(0) end ent.pac_duplicate_attach_uid = self.UniqueID end else if removed and prev_owner == ent then self:SetOwner(NULL) self.temp_hidden = true return end if not removed and self.OwnerName ~= "" then ent = pac.HandleOwnerName(self:GetPlayerOwner(), self.OwnerName, ent, self) or NULL if ent ~= prev_owner then self:SetOwner(ent) self.temp_hidden = false return true end end end end function PART:SetOwner(ent) if IsValid(self.last_owner) and self.last_owner ~= ent then self:CallRecursive("OnHide", true) end self.last_owner = self.Owner self.Owner = ent or NULL pac.RunNextFrame(self:GetRootPart().Id .. "_hook_render", function() if self:IsValid() then self:HookEntityRender() end end) end -- always return the root owner function PART:GetPlayerOwner() if not self.PlayerOwner then return self:GetOwner(true) or NULL end return self.PlayerOwner end function PART:GetOwner(root) if self.owner_override then return self.owner_override end if root then return self:GetRootPart():GetOwner() end local parent = self:GetParent() if parent:IsValid() then if self.ClassName ~= "event" and parent.is_model_part and parent.Entity:IsValid() then return parent.Entity end return parent:GetOwner() end return self.Owner or NULL end --SETUP_CACHE_FUNC(PART, "GetOwner") end function PART:SetIsDisturbing(val) self.IsDisturbing = val self.hide_disturbing = pac_hide_disturbing:GetBool() and val end do -- parenting function PART:GetChildren() return self.Children end function PART:GetChildrenList() if not self.children_list then self:BuildChildrenList() end return self.children_list end local function add_children_to_list(parent, list, drawOrder) for _, child in ipairs(parent:GetChildren()) do table.insert(list, {child, child.DrawOrder + drawOrder}) add_children_to_list(child, list, drawOrder + child.DrawOrder) end end function PART:BuildChildrenList() local child = {} self.children_list = child local tableToSort = {} add_children_to_list(self, tableToSort, self.DrawOrder) table.sort(tableToSort, function(a, b) return a[2] < b[2] end) for i, data in ipairs(tableToSort) do child[#child + 1] = data[1] end end function PART:CreatePart(name) local part = pac.CreatePart(name, self:GetPlayerOwner()) if not part then return end part:SetParent(self) return part end function PART:SetParent(part) if not part or not part:IsValid() then self:UnParent() return false else return part:AddChild(self) end end function PART:BuildParentList() if not self:HasParent() then return end self.parent_list = {} local temp = self:GetParent() table.insert(self.parent_list, temp) for _ = 1, 100 do local parent = temp:GetParent() if not parent:IsValid() then break end table.insert(self.parent_list, parent) temp = parent end self.RootPart = temp for _, part in ipairs(self:GetChildren()) do part:BuildParentList() end end function PART:AddChild(part) if not part or not part:IsValid() then self:UnParent() return end if self == part or part:HasChild(self) then return false end part:UnParent() part.Parent = self if not part:HasChild(self) then self.Children2[part] = part table.insert(self.Children, part) end self:InvalidateChildrenList() part.ParentName = self:GetName() part.ParentUID = self:GetUniqueID() self:ClearBone() part:ClearBone() part:OnParent(self) self:OnChildAdd(part) if self:HasParent() then self:GetParent():SortChildren() end part:SortChildren() self:SortChildren() self:BuildParentList() part:BuildParentList() pac.CallHook("OnPartParent", self, part) part.shown_from_rendering = true part:SetKeyValueRecursive("last_hidden", nil) part:SetKeyValueRecursive("last_hidden_by_event", nil) return part.Id end do local sort = function(a, b) return a.DrawOrder < b.DrawOrder end function PART:SortChildren() table.sort(self.Children, sort) end end function PART:HasParent() return self.Parent:IsValid() end function PART:HasChildren() return self.Children[1] ~= nil end function PART:HasChild(part) return self.Children2[part] ~= nil end function PART:RemoveChild(part) self.Children2[part] = nil for i, val in ipairs(self:GetChildren()) do if val == part then self:InvalidateChildrenList() table.remove(self.Children, i) part:OnUnParent(self) break end end end function PART:GetRootPart() if not self:HasParent() then return self end if not self.RootPart:IsValid() then self:BuildParentList() end return self.RootPart end SETUP_CACHE_FUNC(PART, "GetRootPart") do local function doRecursiveCall(childrens, func, profileName, profileNameChildren, ...) for i, child in ipairs(childrens) do local sysTime = SysTime() child[func](child, func, ...) child[profileName] = SysTime() - sysTime sysTime = SysTime() doRecursiveCall(child:GetChildren(), func, profileName, profileNameChildren, ...) child[profileNameChildren] = SysTime() - sysTime end end function PART:CallRecursiveProfiled(func, ...) local profileName = func .. 'Runtime' local profileNameChildren = func .. 'RuntimeChildren' if self[func] then local sysTime = SysTime() self[func](self, ...) self[profileName] = SysTime() - sysTime end local sysTime = SysTime() doRecursiveCall(self:GetChildren(), func, profileName, profileNameChildren, ...) self[profileNameChildren] = SysTime() - sysTime end function PART:CallRecursive(func, ...) if self[func] then self[func](self, ...) end local child = self:GetChildrenList() for i = 1, #child do if child[i][func] then child[i][func](child[i], ...) end end end function PART:CallRecursiveExclude(func, ...) local child = self:GetChildrenList() for i = 1, #child do if child[i][func] then child[i][func](child[i], ...) end end end function PART:SetKeyValueRecursive(key, val) self[key] = val local child = self:GetChildrenList() for i = 1, #child do child[i][key] = val end end function PART:SetHide(b) self.Hide = b self:SetKeyValueRecursive("hidden", b) end function PART:RemoveEventHide(object) self.event_hide_registry[object] = nil end function PART:SetEventHide(b, object) object = object or self -- this can and will produce undefined behavior (like skipping keys) -- but still, it will do the job at cleaning up at least a part of table for k, v in pairs(self.event_hide_registry) do if not IsValid(k) then self.event_hide_registry[k] = nil end end self.event_hide_registry[object] = b self.event_hidden = self:CalculateEventHidden() if self.event_hidden ~= b then self.shown_from_rendering = nil end end function PART:FlushFromRenderingState(newState) self.shown_from_rendering = nil end function PART:IsDrawHidden() return self.draw_hidden end function PART:CalculateEventHidden() for k, v in pairs(self.event_hide_registry) do if v then return true end end return false end function PART:IsEventHidden(object, invert) if object then if invert then for k, v in pairs(self.event_hide_registry) do if k ~= object and v then return true end end return false end return self.event_hide_registry[object] == true end if self.event_hidden == nil then self.event_hidden = self:CalculateEventHidden() end return self.event_hidden end function PART:IsHiddenInternal() return self.hidden end function PART:IsHidden() if self.draw_hidden or self.temp_hidden or self.hidden or self.hide_disturbing or self:IsEventHidden() then return true, self:IsEventHidden() end if not self:HasParent() then return false end if not self.parent_list then self:BuildParentList() end for _, parent in ipairs(self.parent_list) do if parent.draw_hidden or parent.temp_hidden or parent.hidden or parent.event_hidden then return true, parent:IsEventHidden() end end return false end SETUP_CACHE_FUNC(PART, "IsHidden") end function PART:InvalidateChildrenList() self.children_list = nil if self.parent_list then for _, part in ipairs(self.parent_list) do part.children_list = nil end end end function PART:RemoveChildren() self:InvalidateChildrenList() for i, part in ipairs(self:GetChildren()) do part:Remove(true) self.Children[i] = nil self.Children2[part] = nil end end function PART:DeattachChildren() self:InvalidateChildrenList() for i, part in ipairs(self:GetChildren()) do if part.owner_id and part.UniqueID then pac.RemoveUniqueIDPart(part.owner_id, part.UniqueID) end pac.RemovePart(part) end end function PART:UnParent() local parent = self:GetParent() if parent:IsValid() then parent:RemoveChild(self) end self:ClearBone() self:OnUnParent(parent) self.Parent = NULL self.ParentName = "" self.ParentUID = "" self:CallRecursive("OnHide") end end do -- bones function PART:SetBone(var) self.Bone = var self:ClearBone() end function PART:ClearBone() self.BoneIndex = nil self.TriedToFindBone = nil local owner = self:GetOwner() if owner:IsValid() then owner.pac_bones = nil end end function PART:GetModelBones(owner) return pac.GetModelBones(owner or self:GetOwner()) end function PART:GetRealBoneName(name, owner) owner = owner or self:GetOwner() local bones = self:GetModelBones(owner) if owner:IsValid() and bones and bones[name] and not bones[name].is_special then return bones[name].real end return name end end do -- serializing function PART:AddStorableVar(var) self.StorableVars = self.StorableVars or {} self.StorableVars[var] = var end function PART:GetStorableVars() self.StorableVars = self.StorableVars or {} return self.StorableVars end function PART:Clear() self:RemoveChildren() end function PART:IsBeingWorn() return self.isBeingWorn end function PART:SetIsBeingWorn(status) self.isBeingWorn = status return self end function PART:OnWorn() -- override end function PART:OnOutfitLoaded() -- override end function PART:PostApplyFixes() -- override end do local function SetTable(self, tbl) self.supress_part_name_find = true self.delayed_variables = self.delayed_variables or {} -- this needs to be set first self:SetUniqueID(tbl.self.UniqueID or util.CRC(tostring(tbl.self))) for key, value in pairs(tbl.self) do -- these arent needed because parent system uses the tree structure local cond = key ~= "ParentUID" and key ~= "ParentName" and key ~= "UniqueID" and (key ~= "AimPartName" and not (pac.PartNameKeysToIgnore and pac.PartNameKeysToIgnore[key]) or key == "AimPartName" and table.HasValue(pac.AimPartNames, value)) if cond then if self["Set" .. key] then if key == "Material" then table.insert(self.delayed_variables, {key = key, val = value}) end self["Set" .. key](self, value) elseif key ~= "ClassName" then pac.dprint("settable: unhandled key [%q] = %q", key, tostring(value)) end end end for _, value in pairs(tbl.children) do local part = pac.CreatePart(value.self.ClassName, self:GetPlayerOwner()) part:SetIsBeingWorn(self:IsBeingWorn()) part:SetParent(self) part:SetTable(value) end end local function make_copy(tbl, pepper) if pepper == true then pepper = tostring(math.random()) end for key, val in pairs(tbl.self) do if key == "UniqueID" or key:sub(-3) == "UID" then tbl.self[key] = util.CRC(val .. pepper) print(tbl.self[key], val, pepper, "!!") end end for _, child in ipairs(tbl.children) do make_copy(child, pepper) end return tbl end function PART:SetTable(tbl, copy_id) if copy_id then tbl = make_copy(table.Copy(tbl), copy_id) end local ok, err = xpcall(SetTable, ErrorNoHalt, self, tbl) if not ok then pac.Message(Color(255, 50, 50), "SetTable failed: ", err) end end end function PART:ToTable() local tbl = {self = {ClassName = self.ClassName}, children = {}} for _, key in pairs(self:GetStorableVars()) do local var = self[key] and self["Get" .. key](self) or self[key] var = pac.class.Copy(var) or var if key == "Name" and self[key] == "" then var = "" end -- these arent needed because parent system uses the tree structure if key ~= "ParentUID" and key ~= "ParentName" and var ~= self.DefaultVars[key] then tbl.self[key] = var end end for _, part in ipairs(self:GetChildren()) do if not self.is_valid or self.is_deattached then else table.insert(tbl.children, part:ToTable()) end end return tbl end function PART:ToSaveTable() if self:GetPlayerOwner() ~= LocalPlayer() then return end local tbl = {self = {ClassName = self.ClassName}, children = {}} for _, key in pairs(self:GetStorableVars()) do local var = self[key] and self["Get" .. key](self) or self[key] var = pac.class.Copy(var) or var if key == "Name" and self[key] == "" then var = "" end -- these arent needed because parent system uses the tree structure if key ~= "ParentUID" and key ~= "ParentName" then tbl.self[key] = var end end for _, part in ipairs(self:GetChildren()) do if not self.is_valid or self.is_deattached then else table.insert(tbl.children, part:ToSaveTable()) end end return tbl end do -- undo do local function SetTable(self, tbl) self.supress_part_name_find = true self.delayed_variables = self.delayed_variables or {} -- this needs to be set first self:SetUniqueID(tbl.self.UniqueID or util.CRC(tostring(tbl.self))) for key, value in pairs(tbl.self) do if self["Set" .. key] then if key == "Material" then table.insert(self.delayed_variables, {key = key, val = value}) end self["Set" .. key](self, value) elseif key ~= "ClassName" then pac.dprint("settable: unhandled key [%q] = %q", key, tostring(value)) end end for _, value in pairs(tbl.children) do local part = pac.CreatePart(value.self.ClassName, self:GetPlayerOwner()) part:SetUndoTable(value) part:SetParent(self) end end function PART:SetUndoTable(tbl) local ok, err = xpcall(SetTable, ErrorNoHalt, self, tbl) if not ok then pac.Message(Color(255, 50, 50), "SetUndoTable failed: ", err) end end end function PART:ToUndoTable() if self:GetPlayerOwner() ~= LocalPlayer() then return end local tbl = {self = {ClassName = self.ClassName}, children = {}} for _, key in pairs(self:GetStorableVars()) do if not pac.PartNameKeysToIgnore[key] then if key == "Name" and self.Name == "" then -- TODO: seperate debug name and name !!! continue end tbl.self[key] = pac.class.Copy(self["Get" .. key](self)) end end for _, part in ipairs(self:GetChildren()) do if not self.is_valid or self.is_deattached then else table.insert(tbl.children, part:ToUndoTable()) end end return tbl end end function PART:GetVars() local tbl = {} for _, key in pairs(self:GetStorableVars()) do tbl[key] = pac.class.Copy(self[key]) end return tbl end function PART:Clone() local part = pac.CreatePart(self.ClassName, self:GetPlayerOwner()) if not part then return end part:SetTable(self:ToTable(), true) part:SetParent(self:GetParent()) return part end end function PART:CallEvent(event, ...) self:OnEvent(event, ...) for _, part in ipairs(self:GetChildren()) do part:CallEvent(event, ...) end end do -- events function PART:Initialize() end function PART:OnRemove() end function PART:IsDeattached() return self.is_deattached end function PART:Deattach() if not self.is_valid or self.is_deattached then return end self.is_deattached = true self.PlayerOwner_ = self.PlayerOwner if self:GetPlayerOwner() == pac.LocalPlayer then pac.CallHook("OnPartRemove", self) end self:CallRecursive("OnHide") self:CallRecursive("OnRemove") if self.owner_id and self.UniqueID then pac.RemoveUniqueIDPart(self.owner_id, self.UniqueID) end pac.RemovePart(self) self.is_valid = false self:DeattachChildren() end function PART:DeattachFull() self:Deattach() if self:HasParent() then self:GetParent():RemoveChild(self) end end function PART:Attach(parent) if not self.is_deattached then return self:SetParent(parent) end self.is_deattached = false self.is_valid = true self:CallRecursive("OnShow") self:SetParent(parent) if self.SetPlayerOwner then self:SetPlayerOwner(self.PlayerOwner_) end timer.Simple(0.1, function() if self:IsValid() and self.show_in_editor ~= false and self.PlayerOwner_ == pac.LocalPlayer then pac.CallHook("OnPartCreated", self) end end) pac.AddPart(self) end function PART:Remove(skip_removechild) self:Deattach() if not skip_removechild and self:HasParent() then self:GetParent():RemoveChild(self) end self:RemoveChildren() end function PART:OnStore() end function PART:OnRestore() end function PART:OnThink() end function PART:OnBuildBonePositions() end function PART:OnParent() end function PART:OnChildAdd() end function PART:OnUnParent() end function PART:OnHide() end function PART:OnShow() end function PART:OnSetOwner(ent) end function PART:OnEvent(event, ...) end end do -- drawing. this code is running every frame PART.cached_pos = Vector(0, 0, 0) PART.cached_ang = Angle(0, 0, 0) function PART:DrawChildren(event, pos, ang, draw_type, drawAll) if drawAll then for i, child in ipairs(self:GetChildrenList()) do child:Draw(pos, ang, draw_type, true) end else for i, child in ipairs(self:GetChildren()) do child:Draw(pos, ang, draw_type) end end end --function PART:Draw(pos, ang, draw_type, isNonRoot) function PART:Draw(pos, ang, draw_type) -- Think takes care of polling this if not self.last_enabled then return end if self:IsHidden() then return end if self.OnDraw and ( draw_type == "viewmodel" or draw_type == "hands" or ((self.Translucent == true or self.force_translucent == true) and draw_type == "translucent") or ((self.Translucent == false or self.force_translucent == false) and draw_type == "opaque") ) then local sysTime = SysTime() pos, ang = self:GetDrawPosition() self.cached_pos = pos self.cached_ang = ang if not self.PositionOffset:IsZero() or not self.AngleOffset:IsZero() then pos, ang = LocalToWorld(self.PositionOffset, self.AngleOffset, pos, ang) end if not self.HandleModifiersManually then self:ModifiersPreEvent('OnDraw', draw_type) end if self.IgnoreZ then cam.IgnoreZ(true) end if self.blend_override then render.OverrideBlendFunc(true, self.blend_override[1], self.blend_override[2], self.blend_override[3], self.blend_override[4] ) if self.blend_override[5] then render.OverrideAlphaWriteEnable(true, self.blend_override[5] == "write_alpha") end if self.blend_override[6] then render.OverrideColorWriteEnable(true, self.blend_override[6] == "write_color") end end if self.NoTextureFiltering then render.PushFilterMin(TEXFILTER.POINT) render.PushFilterMag(TEXFILTER.POINT) end self:OnDraw(self:GetOwner(), pos, ang) if self.NoTextureFiltering then render.PopFilterMin() render.PopFilterMag() end if self.blend_override then render.OverrideBlendFunc(false) if self.blend_override[5] then render.OverrideAlphaWriteEnable(false) end if self.blend_override[6] then render.OverrideColorWriteEnable(false) end end if self.IgnoreZ then cam.IgnoreZ(false) end if not self.HandleModifiersManually then self:ModifiersPostEvent('OnDraw', draw_type) end self.selfDrawTime = SysTime() - sysTime end -- if not isNonRoot then -- for i, child in ipairs(self:GetChildrenList()) do -- child:Draw(pos, ang, draw_type, true) -- end -- end local sysTime = SysTime() for _, child in ipairs(self:GetChildren()) do child:Draw(pos, ang, draw_type) end if draw_type == "translucent" then self.childrenTranslucentDrawTime = SysTime() - sysTime elseif draw_type == "opaque" then self.childrenOpaqueDrawTime = SysTime() - sysTime end end function PART:GetDrawPosition(bone_override, skip_cache) if not self.AllowSetupPositionFrameSkip or pac.FrameNumber ~= self.last_drawpos_framenum or not self.last_drawpos or skip_cache then self.last_drawpos_framenum = pac.FrameNumber local owner = self:GetOwner() if owner:IsValid() then local pos, ang = self:GetBonePosition(bone_override, skip_cache) pos, ang = LocalToWorld( self.Position or Vector(), self.Angles or Angle(), pos or owner:GetPos(), ang or owner:GetAngles() ) ang = self:CalcAngles(ang) or ang self.last_drawpos = pos self.last_drawang = ang return pos, ang end end return self.last_drawpos, self.last_drawang end function PART:GetBonePosition(bone_override, skip_cache) if not self.AllowSetupPositionFrameSkip or pac.FrameNumber ~= self.last_bonepos_framenum or not self.last_bonepos or skip_cache then self.last_bonepos_framenum = pac.FrameNumber local owner = self:GetOwner() local parent = self:GetParent() if parent:IsValid() and parent.ClassName == "jiggle" then if skip_cache then if parent.Translucent then parent:Draw(nil, nil, "translucent") else parent:Draw(nil, nil, "opaque") end end return parent.pos, parent.ang end local pos, ang if parent:IsValid() and not parent.NonPhysical then local ent = parent.Entity or NULL if ent:IsValid() then -- if the parent part is a model, get the bone position of the parent model if ent.pac_bone_affected ~= FrameNumber() then ent:InvalidateBoneCache() end pos, ang = pac.GetBonePosAng(ent, bone_override or self.Bone) else -- else just get the origin of the part -- unless we've passed it from parent pos, ang = parent:GetDrawPosition() end elseif owner:IsValid() then -- if there is no parent, default to owner bones owner:InvalidateBoneCache() pos, ang = pac.GetBonePosAng(owner, self.Bone) end self.last_bonepos = pos self.last_boneang = ang return pos, ang end return self.last_bonepos, self.last_boneang end -- since this is kind of like a hack I choose to have upper case names to avoid name conflicts with parts -- the editor can use the keys as friendly names pac.AimPartNames = { ["local eyes"] = "LOCALEYES", ["player eyes"] = "PLAYEREYES", ["local eyes yaw"] = "LOCALEYES_YAW", ["local eyes pitch"] = "LOCALEYES_PITCH", } function PART:CalcAngles(ang) local owner = self:GetOwner(true) if pac.StringFind(self.AimPartName, "LOCALEYES_YAW", true, true) then ang = (pac.EyePos - self.cached_pos):Angle() ang.p = 0 return self.Angles + ang end if pac.StringFind(self.AimPartName, "LOCALEYES_PITCH", true, true) then ang = (pac.EyePos - self.cached_pos):Angle() ang.y = 0 return self.Angles + ang end if pac.StringFind(self.AimPartName, "LOCALEYES", true, true) then return self.Angles + (pac.EyePos - self.cached_pos):Angle() end if pac.StringFind(self.AimPartName, "PLAYEREYES", true, true) then local ent = owner.pac_traceres and owner.pac_traceres.Entity or NULL if ent:IsValid() then return self.Angles + (ent:EyePos() - self.cached_pos):Angle() end return self.Angles + (pac.EyePos - self.cached_pos):Angle() end if self.AimPart:IsValid() then return self.Angles + (self.AimPart.cached_pos - self.cached_pos):Angle() end if self.EyeAngles then if owner:IsPlayer() then return self.Angles + ((owner.pac_hitpos or owner:GetEyeTraceNoCursor().HitPos) - self.cached_pos):Angle() elseif owner:IsNPC() then return self.Angles + ((owner:EyePos() + owner:GetForward() * 100) - self.cached_pos):Angle() end end return ang or Angle(0,0,0) end --SETUP_CACHE_FUNC(PART, "CalcAngles") end function PART:CalcShowHide() local b, byEvent = self:IsHidden() local triggerUpdate = b ~= self.last_hidden or self.last_hidden_by_event ~= byEvent if not triggerUpdate then return end if b ~= self.last_hidden then if b then self:OnHide() else self:OnShow(self.shown_from_rendering == true or self.shown_from_rendering == FrameNumber()) end end if FrameNumber() ~= self.shown_from_rendering then self.shown_from_rendering = nil end self.last_hidden = b self.last_hidden_by_event = byEvent end function PART:HookEntityRender() local root = self:GetRootPart() local owner = root:GetOwner() if root.ClassName ~= "group" then return end -- FIX ME if root.last_owner:IsValid() then pac.UnhookEntityRender(root.last_owner, root) end if owner:IsValid() then pac.HookEntityRender(owner, root) end end function PART:CThink() if self.ThinkTime == 0 then if self.last_think ~= pac.FrameNumber then self:Think() self.last_think = pac.FrameNumber end elseif not self.last_think or self.last_think < pac.RealTime then self:Think() self.last_think = pac.RealTime + (self.ThinkTime or 0.1) end end function PART:Think() if not self:GetEnabled() then return end self:CalcShowHide() if not self.AlwaysThink and self:IsHidden() then return end local owner = self:GetOwner() if owner:IsValid() then if owner ~= self.last_owner then self.last_hidden = false self.last_hidden_by_event = false self.last_owner = owner end if not owner.pac_bones then self:GetModelBones() end end if self.ResolvePartNames then self:ResolvePartNames() end if self.delayed_variables then for _, data in ipairs(self.delayed_variables) do self["Set" .. data.key](self, data.val) end self.delayed_variables = nil end self:OnThink() self.supress_part_name_find = false end function PART:BuildBonePositions() if not self:IsHidden() then self:OnBuildBonePositions() end end function PART:SubmitToServer() pac.SubmitPart(self:ToTable()) end PART.is_valid = true function PART:IsValid() return self.is_valid end function PART:SetDrawOrder(num) self.DrawOrder = num if self:HasParent() then self:GetParent():SortChildren() end end pac.RegisterPart(PART)
gpl-3.0
wolfmanstout/jene
src/jene/vectornodes/MaxNode.java
711
package jene.vectornodes; import java.util.List; import jene.Node; import jene.Pixel; /** * * @author James Stout * */ public class MaxNode extends Node2Arg<double[], double[]> { protected MaxNode(List<Node<Pixel, ?>> children) { super(children); } public MaxNode(Node<Pixel, double[]> arg1, Node<Pixel, double[]> arg2) { super(arg1, arg2); } public double[] evaluate(Pixel input) { double[] a = _arg1.evaluate(input); double[] b = _arg2.evaluate(input); for(int i = 0; i<a.length; i++){ a[i] = Math.max(a[i], b[i]); } return a; } public MaxNodeFactory getFactory() { return MaxNodeFactory.INSTANCE; } @Override protected String nodeName() { return "Max"; } }
gpl-3.0
Gawdl3y/task-timer-legacy
android/TaskTimer/src/main/java/com/gawdl3y/android/actionablelistview/CheckableListView.java
3366
package com.gawdl3y.android.actionablelistview; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.Checkable; import android.widget.ListView; /** * A {@code ListView} that: * <ul> * <li>will keep check states in sync with a {@link CheckableAdapter} as long as any {@code setItemChecked} calls are made through the {@link CheckableListView}, and not the adapter</li> * <li>will check/uncheck its views that implement the {@link Checkable} interface</li> * <li>fires {@link OnListItemCheckStateChangeListener} events</li> * </ul> * @author Schuyler Cebulskie */ public class CheckableListView extends ListView implements OnListItemCheckStateChangeListener { private OnListItemCheckStateChangeListener mOnItemCheckStateChangeListener; public CheckableListView(Context context) { super(context); } public CheckableListView(Context context, AttributeSet attrs) { super(context, attrs); } public CheckableListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean performItemClick(View view, int position, long id) { boolean sooper = super.performItemClick(view, position, id); // Fire check state change event if(getChoiceMode() == CHOICE_MODE_MULTIPLE) { if(isItemChecked(position)) { onListItemChecked(view, position, id); } else { onListItemUnchecked(view, position, id); } } return sooper; } @Override public void setItemChecked(int position, boolean value) { if(getChoiceMode() == CHOICE_MODE_NONE) return; super.setItemChecked(position, value); // Update adapter if(getAdapter() != null && getAdapter() instanceof CheckableAdapter) { CheckableAdapter adapter = (CheckableAdapter) getAdapter(); if(getChoiceMode() == CHOICE_MODE_MULTIPLE) { adapter.setItemChecked(position, value); } else { adapter.getCheckStates().clear(); if(value) adapter.setItemChecked(position, true); } } } @Override public void clearChoices() { super.clearChoices(); if(getAdapter() != null && getAdapter() instanceof CheckableAdapter) ((CheckableAdapter) getAdapter()).getCheckStates().clear(); invalidateViews(); } @Override public void onListItemChecked(View view, int position, long id) { if(view instanceof Checkable) ((Checkable) view).setChecked(true); if(mOnItemCheckStateChangeListener != null) mOnItemCheckStateChangeListener.onListItemChecked(view, position, id); } @Override public void onListItemUnchecked(View view, int position, long id) { if(view instanceof Checkable) ((Checkable) view).setChecked(false); if(mOnItemCheckStateChangeListener != null) mOnItemCheckStateChangeListener.onListItemUnchecked(view, position, id); } /** * Sets the listener for listening to item check/uncheck events * @param listener The listener */ public void setOnItemCheckStateChangeListener(OnListItemCheckStateChangeListener listener) { mOnItemCheckStateChangeListener = listener; } }
gpl-3.0
SevenLines/RSign
DesignPattern.cpp
18825
//--------------------------------------------------------------------------- #pragma hdrstop #include "DesignPattern.h" #include "MainUnit.h" #include "AttachForm.h" #include <math.h> //--------------------------------------------------------------------------- #pragma package(smart_init) TDesignAttachVer1_1 DesignAttachVer1_1; TDesignAttachVer1_2 DesignAttachVer1_2; TDesignAttachVer2_1 DesignAttachVer2_1; TDesignAttachVer2_2 DesignAttachVer2_2; TDesignAttachVer3 DesignAttachVer3; TDesignMetricsPattern *MarkDesigners[1]={&DesignAttachVer3}; TDesignMetricsPattern *Designers[4]={&DesignAttachVer1_1,&DesignAttachVer1_2,&DesignAttachVer2_1,&DesignAttachVer2_2}; String DesignersName[4]={"Ïðèìûêàíèå ó êðîìêè","Ïðèìûêàíèå ó áðîâêè","Ïðèìûêàíèå ó êðîìêè è ñòîëáèêè","Ïðèìûêàíèå ó áðîâêè è ñòîëáèêè"}; const int AttachPtCount=12; const int SignalPointCount=4; AttachCodes1RK[12]={0x3100,0x3101,0x3101,0x3101,0x3101,0x37351,0x38450,0x3101,0x3101,0x3101,0x3101,0x3101}; AttachCodes1LK[12]={0x4100,0x4101,0x4101,0x4101,0x4101,0x37361,0x38460,0x4101,0x4101,0x4101,0x4101,0x4101}; AttachCodes1RB[12]={0x1100,0x1101,0x1101,0x1101,0x1101,0x37351,0x38450,0x1101,0x1101,0x1101,0x1101,0x1101}; AttachCodes1LB[12]={0x2100,0x2101,0x2101,0x2101,0x2101,0x37361,0x38460,0x2101,0x2101,0x2101,0x2101,0x2101}; //int AttachCodes1RK[10]={0x130,0x37300,0x38405,0x3100,0x37351,0x38450,0x3101,0x37300,0x38405,0x130}; //int AttachCodes1LK[10]={0x140,0x37300,0x38405,0x4100,0x37361,0x38460,0x4101,0x37300,0x38405,0x140}; //int AttachCodes1RB[10]={0x110,0x37300,0x38405,0x3100,0x37351,0x38450,0x3101,0x37300,0x38405,0x110}; //int AttachCodes1LB[10]={0x120,0x37300,0x38405,0x4100,0x37361,0x38460,0x4101,0x37300,0x38405,0x120}; const int SignalCodes1R[4]={0x510,0x37300,0x38405,0x1500}; const int SignalCodes1L[4]={0x520,0x37300,0x38405,0x2500}; const int SignalCodes2R[4]={0x1500,0x37300,0x38405,0x510}; const int SignalCodes2L[4]={0x2500,0x37300,0x38405,0x520}; __fastcall TDesignAttachVer1_1::TDesignAttachVer1_1(void) : TDesignAttachVer1() { PtCount=AttachPtCount; CodesL=AttachCodes1LK; CodesR=AttachCodes1RK; } __fastcall TDesignAttachVer1_2::TDesignAttachVer1_2(void) : TDesignAttachVer1() { PtCount=AttachPtCount; CodesL=AttachCodes1LB; CodesR=AttachCodes1RB; } __fastcall TDesignAttachVer2_1::TDesignAttachVer2_1(void) : TDesignAttachVer2() { PtCount=AttachPtCount; CodesL=AttachCodes1LK; CodesR=AttachCodes1RK; } __fastcall TDesignAttachVer2_2::TDesignAttachVer2_2(void) : TDesignAttachVer2() { PtCount=AttachPtCount; CodesL=AttachCodes1LB; CodesR=AttachCodes1RB; } bool __fastcall TDesignAttachVer1::Design(TRoadObject *Obj, TDtaSource *Data, TDictSource *Dict) { bool Res=false; TRoadAttach *Att=dynamic_cast<TRoadAttach*>(Obj); if (Att) { angle=Att->Angle; if (angle==0) angle=90; ewidth=600; bwidth=3*ewidth/2+(int)((ewidth/100)/sin(angle*M_PI/180))*100; elength=600; int ang; // Ðàñ÷åò ïàðàìåòðîâ ïî ìåòðèêå if (Att->Poly && Att->Poly->Count>=4) { int last=Att->Poly->Count-1; int pos; // Èùåì òî÷êó ñ ôèêñèðîâàííûì óãëîì îò ïðåäûäóùåé òî÷êè for (pos=1;pos<=last;pos++) if (Att->Poly->Points[pos].Code()&0x17300==0x17300 && (Att->Poly->Points[pos].Code.Leep()==5 || Att->Poly->Points[pos].Code.Leep()==6)) break; if (pos<last) { ang=abs(Att->Poly->Points[pos].BasePar1)%360000; if (ang>180000) ang=360000-ang; angle=(ang+500)/1000; elength=abs(Att->Poly->Points[pos].X-Att->Poly->Points[0].X); ewidth=abs(Att->Poly->Points[pos+1].L-Att->Poly->Points[pos].L)*sin(ang*M_PI/180000)+0.5; } bwidth=abs(Att->Poly->Points[0].L-Att->Poly->Points[last].L); } frmAttachParams->edAngle->Text=IntToStr(angle); frmAttachParams->edLength->Text=IntToStr(elength); frmAttachParams->edBegWidth->Text=IntToStr(bwidth); frmAttachParams->edEndWidth->Text=IntToStr(ewidth); if (frmAttachParams->ShowModal()==mrOk) { angle=frmAttachParams->edAngle->Text.ToInt(); elength=frmAttachParams->edLength->Text.ToInt(); bwidth=frmAttachParams->edBegWidth->Text.ToInt(); ewidth=frmAttachParams->edEndWidth->Text.ToInt(); if (!Att->Poly){ Att->Poly=new TPolyline(PtCount,0); //Data->PolyList->Add(Att->Poly); } else Att->Poly->Count=PtCount; Att->Angle=angle; const int *Codes; if (Att->Placement==apLeft) Codes=CodesL; else Codes=CodesR; // rad=dl*tan(a/2)*tan((180-a)/2)/(tan(a/2)+tan((180-a)/2)) double ta1=tan(angle*M_PI/360); double ta2=tan((180-angle)*M_PI/360); double rad=(bwidth-ewidth/sin(angle*M_PI/180))*ta1*ta2/(ta1+ta2); int last=PtCount/2-2; int sign; if (Att->Placement==apLeft) Codes=CodesL,sign=-1; else Codes=CodesR,sign=1; double maxa=1-cos((angle>90? angle:180-angle)*M_PI/180); for (int i=0;i<=last;i++) { double alf=(angle)*i*M_PI/(180*last); double x=-bwidth/2+rad*sin(alf); double y=/*elength*(1-cos(alf))/maxa*/ rad*(1-cos(alf)); Att->Poly->Points[i].Code=Codes[i]; Att->Poly->Points[i].LeepPar=0; Att->Poly->Points[i].BasePar1=x; Att->Poly->Points[i].BasePar2=sign*y; alf=(180-angle)*i*M_PI/(180*last); x=bwidth/2-rad*sin(alf); y=/*elength*(1-cos(alf))/maxa*/ rad*(1-cos(alf)); Att->Poly->Points[PtCount-1-i].Code=Codes[PtCount-1-i]; Att->Poly->Points[PtCount-1-i].LeepPar=0; Att->Poly->Points[PtCount-1-i].BasePar1=x; Att->Poly->Points[PtCount-1-i].BasePar2=sign*y; } Att->Poly->Points[last+1].Code=Codes[last+1]; Att->Poly->Points[last+1].LeepPar=0; Att->Poly->Points[last+2].Code=Codes[last+2]; Att->Poly->Points[last+2].LeepPar=0; Att->Poly->Points[last+1].BasePar1=sign*angle*1000; Att->Poly->Points[last+2].BasePar1=sign*angle*1000; // BasePar2 áóäåò ïåðåñ÷èòàíî àâòîìàòè÷åñêè äàëåå Data->Road->CalcPointsPos(Att->Poly,Att); MainForm->SendBroadCastMessage(CM_UPDATEOBJ,(int)Att,(int)Data); } } /* int W1=0; int L=Att->L; int L1=0; // L íà÷àëà çàêðóãëåíèÿ áëèæíåé äóãè int L2=0; // L íà÷àëà çàêðóãëåíèÿ äàëüíåé äóãè int L3=0; // L êîíöà çàêðóãëåíèÿ áëèæíåé äóãè int L4=0; // L êîíöà çàêðóãëåíèÿ äàëüíåé äóëè int DX1=0; // DX êîíöà çàêðóãëåíèÿ áëèæíåé äóãè (áåç çíàêà) int DX2=0; // DX êîíöà çàêðóãëåíèÿ äàëüíåé äóãè (áåç çíàêà) int SDX1,SDX2; // Òîæå ñàìîå, íî ñî çíàêîì â çàâèñèìîñòè îò íàïðàâëåíèÿ if (Att->Poly) if (Att->Poly->Count>1) { L1=Att->Poly->Points[0].L; L2=Att->Poly->Points[Att->Poly->Count-1].L; if (Att->Poly->Count==4) { DX1=abs(Att->Poly->Points[1].X-Att->Poly->Points[0].X); DX2=abs(Att->Poly->Points[2].X-Att->Poly->Points[3].X); L3=Att->Poly->Points[1].L; L4=Att->Poly->Points[2].L; } else if (Att->Poly->Count==10) { DX1=abs(Att->Poly->Points[3].X-Att->Poly->Points[0].X); DX2=abs(Att->Poly->Points[6].X-Att->Poly->Points[9].X); L3=Att->Poly->Points[3].L; L4=Att->Poly->Points[6].L; } } if (L2<L1) { int t=L2; L2=L1; L1=t; t=DX1; DX1=DX2; DX2=t; } W1=L2-L1; if (W1==0) W1=Att->Width; if (W1==0) W1=Att->DefaultWidth()*2; if ((L1==0)&&(L2==0)) { L1=L-W1/2; L2=L+W1/2; } if ((L3==0)&&(L4==0)) { L3=L1+W1/4; L4=L2-W1/4; } else if (L4<L3) { int t=L4; L4=L3; L3=t; } if ((DX1==0)&&(DX2==0)) DX1=DX2=2000; if (Att->Placement==apLeft) SDX1=-DX1,SDX2=-DX2; else SDX1=DX1,SDX2=DX2; if (!Att->Poly) { Att->Poly=new TPolyline(PtCount,0); Data->PolyList->Add(Att->Poly); } else Att->Poly->Count=PtCount; int ang=Att->Angle; if (!ang) ang=90; if (Att->Placement!=apRight) ang=-ang; ang*=1000; int backang; if (ang<=0) backang=180000+ang; else backang=-180000+ang; const int *Codes; if (Att->Placement==apLeft) Codes=CodesL; else Codes=CodesR; for (int i=0;i<PtCount;i++) { Att->Poly->Points[i].Code=Codes[i]; Att->Poly->Points[i].LeepPar=0; } // Óñòàíàâëèâàåì íå ïðèâÿçàííûå òî÷êè TRoadPoint *P=Att->Poly->Points; P[0].BasePar1=L1-L; P[0].BasePar2=0; P[9].BasePar1=L2-L; P[9].BasePar2=0; int R=DX1/tan(fabs((double)ang*M_PI/180000)); P[1].BasePar1=0; P[1].BasePar2=(L3-L1-R)/2; R=DX2/tan(fabs((double)ang*M_PI/180000)); P[8].BasePar1=180000; P[8].BasePar2=(L2-L4+R)/2; P[2].BasePar1=backang; P[2].BasePar2=DX1/2; P[7].BasePar1=backang; P[7].BasePar2=DX2/2; P[3].BasePar1=L3-L; P[3].BasePar2=SDX1; P[6].BasePar1=L4-L; P[6].BasePar2=SDX2; P[4].BasePar1=ang; P[4].BasePar2=0; P[5].BasePar1=ang; P[5].BasePar2=0; Data->Road->CalcPointsPos(Att->Poly,Att); MainForm->SendBroadCastMessage(CM_UPDATEOBJ,(int)Att,(int)Data); } else Res=TDesignMetricsPattern::Design(Obj, Data, Dict); */ return Res; } bool __fastcall TDesignAttachVer2::Design(TRoadObject *Obj, TDtaSource *Data, TDictSource *Dict) { bool Res; Res=TDesignAttachVer1::Design(Obj,Data,Dict); TRoadAttach *Att=dynamic_cast<TRoadAttach*>(Obj); if (Att) if (Att->Poly) if (Att->Poly->Count==10) { Data->DeleteChildObjects(Att); TObjMetaClass *Meta=Dict->ObjClasses->Items[ROADSIGNALCODE]; if (Meta) { TRoadSignal *Signal=(TRoadSignal*)Data->Factory->CreateRoadObj(Meta->ClassName,0,ROADSIGNALCODE); Signal->Count=6; Signal->PutPosition(Att->Poly->Points[0].L,Att->Poly->Points[3].L); Signal->Placement=(TObjPlacement)Att->Placement; Signal->Kind=skStolb; Signal->DrwClassId=Dict->SelectDrwParam(Signal,1); Att->AddChild(Signal); Signal->Poly=new TPolyline(SignalPointCount,0); //Data->PolyList->Add(Signal->Poly); Signal->Poly->Count=SignalPointCount; TRoadPoint *AttP=Att->Poly->Points; TRoadPoint *P=Signal->Poly->Points; const int *Codes; if (Signal->Placement==opLeft) Codes=SignalCodes1L; else Codes=SignalCodes1R; for (int i=0;i<SignalPointCount;i++) { P[i]=AttP[i]; P[i].Code=Codes[i]; } P[0].BasePar1-=200; P[SignalPointCount-1].BasePar1-=200; Data->Road->CalcPointsPos(Signal->Poly,Signal); Signal->UpdatePoly(); Data->Buffer->Add(Signal); Signal=(TRoadSignal*)Data->Factory->CreateRoadObj(Meta->ClassName,0,ROADSIGNALCODE); Signal->Count=6; Signal->PutPosition(Att->Poly->Points[6].L,Att->Poly->Points[9].L); Signal->Placement=(TObjPlacement)Att->Placement; Signal->Kind=skStolb; Signal->DrwClassId=Dict->SelectDrwParam(Signal,1); Att->AddChild(Signal); Signal->Poly=new TPolyline(SignalPointCount,0); //Data->PolyList->Add(Signal->Poly); Signal->Poly->Count=SignalPointCount; P=Signal->Poly->Points; if (Signal->Placement==opLeft) Codes=SignalCodes2L; else Codes=SignalCodes2R; for (int i=0;i<SignalPointCount;i++) { P[i]=AttP[PtCount-SignalPointCount+i]; P[i].Code=Codes[i]; } P[0].BasePar1+=200; P[SignalPointCount-1].BasePar1+=200; Data->Road->CalcPointsPos(Signal->Poly,Signal); Signal->UpdatePoly(); Data->Buffer->Add(Signal); Data->AddFromBufer(); MainForm->SendBroadCastMessage(CM_INSERTGROUP,0,(int)Data); } } return Res; } bool __fastcall TDesignAttachVer3::Design(TRoadObject *Obj, TDtaSource *Data, TDictSource *Dict) { bool Res=false; TRoadAttach *Att=dynamic_cast<TRoadAttach*>(Obj); TObjMetaClass *Meta=Dict->ObjClasses->Items[ROADMARKCODE]; if (Meta && Att && Att->Poly) { int last=Att->Poly->Count-1; int pos; // Èùåì òî÷êó ñ ôèêñèðîâàííûì óãëîì îò ïðåäûäóùåé òî÷êè for (pos=1;pos<=last-2;pos++) if (Att->Poly->Points[pos].Code()&0x17300==0x17300 && (Att->Poly->Points[pos].Code.Leep()==5 || Att->Poly->Points[pos].Code.Leep()==6)) break; if (pos<last) { TRoadMark *mark=(TRoadMark*)Data->Factory->CreateRoadObj(Meta->ClassName,0,ROADMARKCODE); mark->Poly=new TPolyline(pos+1,0); mark->SetDirection((Att->Placement==opRight) ? roDirect:roUnDirect); mark->SetKind(ma2_1); for (int i=0;i<pos;i++) { mark->Poly->Points[i].BasePar1=Att->Poly->Points[i].L+50; mark->Poly->Points[i].BasePar2=Att->Poly->Points[i].X; mark->Poly->Points[i].Code=(i==0?0:1); } int left=mark->Poly->Points[0].BasePar1=((Att->Poly->Points[0].L+99)/100)*100; mark->Poly->Points[pos]=Att->Poly->Points[pos]; mark->DrwClassId=Dict->SelectDrwParam(mark,ROADMARKPAGE); Data->Road->CalcPointsPos(mark->Poly,mark); mark->UpdatePoly(); Data->Buffer->Add(mark); mark=(TRoadMark*)Data->Factory->CreateRoadObj(Meta->ClassName,0,ROADMARKCODE); mark->Poly=new TPolyline(last-pos,0); mark->SetDirection((Att->Placement==opRight) ? roDirect:roUnDirect); mark->SetKind(ma2_1); for (int i=0;i<last-pos-1;i++) { mark->Poly->Points[i].BasePar1=Att->Poly->Points[last-i].L-50; mark->Poly->Points[i].BasePar2=Att->Poly->Points[last-i].X; mark->Poly->Points[i].Code=(i==0?0:1); } int right=mark->Poly->Points[0].BasePar1=((Att->Poly->Points[last].L)/100)*100; mark->Poly->Points[last-pos-1]=Att->Poly->Points[pos]; mark->DrwClassId=Dict->SelectDrwParam(mark,ROADMARKPAGE); Data->Road->CalcPointsPos(mark->Poly,mark); mark->UpdatePoly(); Data->Buffer->Add(mark); mark=(TRoadMark*)Data->Factory->CreateRoadObj(Meta->ClassName,0,ROADMARKCODE); mark->Poly=new TPolyline(3,0); mark->SetDirection((Att->Placement==opRight) ? roDirect:roUnDirect); mark->SetKind(ma1); int center=mark->Poly->Points[0].BasePar1=((Att->Poly->Points[0].L+Att->Poly->Points[last].L+100)/200)*100; mark->Poly->Points[0].BasePar2=Att->Poly->Points[0].X; mark->Poly->Points[0].Code=0; if (abs(Att->Poly->Points[pos-1].X)>abs(Att->Poly->Points[pos+2].X)) { mark->Poly->Points[1].BasePar1=Att->Poly->Points[pos-1].L+(Att->Poly->Points[pos+1].L-Att->Poly->Points[pos].L)/2; mark->Poly->Points[1].BasePar2=Att->Poly->Points[pos-1].X; } else { mark->Poly->Points[1].BasePar1=Att->Poly->Points[pos+2].L-(Att->Poly->Points[pos+1].L-Att->Poly->Points[pos].L)/2; mark->Poly->Points[1].BasePar2=Att->Poly->Points[pos+2].X; } mark->Poly->Points[1].Code=1; mark->Poly->Points[2]=Att->Poly->Points[pos]; mark->DrwClassId=Dict->SelectDrwParam(mark,ROADMARKPAGE); Data->Road->CalcPointsPos(mark->Poly,mark); mark->UpdatePoly(); Data->Buffer->Add(mark); mark=(TRoadMark*)Data->Factory->CreateRoadObj(Meta->ClassName,0,ROADMARKCODE); mark->SetDirection((Att->Placement==opRight) ? roDirect:roUnDirect); mark->SetKind(ma7); mark->K=1000; mark->Offset=0; if (Att->Placement==opRight) mark->PutPosition(left,center); else mark->PutPosition(center,right); mark->DrwClassId=Dict->SelectDrwParam(mark,ROADMARKPAGE); Data->Buffer->Add(mark); mark=(TRoadMark*)Data->Factory->CreateRoadObj(Meta->ClassName,0,ROADMARKCODE); mark->SetDirection((Att->Placement==opRight) ? roDirect:roUnDirect); mark->SetKind(ma13); mark->K=1000; mark->Offset=0; if (Att->Placement==opRight) mark->PutPosition(center,right); else mark->PutPosition(left,center); mark->DrwClassId=Dict->SelectDrwParam(mark,ROADMARKPAGE); Data->Buffer->Add(mark); Data->AddFromBufer(); MainForm->SendBroadCastMessage(CM_INSERTGROUP,0,(int)Data); Res=true; } } /* int c1=0; int c2=0; for (int i=1;i<Att->Poly->Count;i++) if (!Att->Poly->Points[i].Code.Visible()) { c1=i+1; c2=Att->Poly->Count-c1; break; } if (c1&&c2) { TObjMetaClass *Meta=Dict->ObjClasses->Items[ROADMARKCODE]; if (Meta) { TRoadMark *mark=(TRoadMark*)Data->Factory->CreateRoadObj(Meta->ClassName,0,ROADMARKCODE); mark->Poly=new TPolyline(c1,0); mark->SetDirection((Att->Placement==opRight) ? roDirect:roUnDirect); mark->SetKind(ma22); mark->Poly->Count=c1; mark->L=Att->L; mark->SetLMax(Att->LMax); for (int i=0;i<c1;i++) mark->Poly->Points[i]=Att->Poly->Points[i]; mark->DrwClassId=Dict->SelectDrwParam(mark,ROADMARKPAGE); Att->AddChild(mark); Data->Road->CalcPointsPos(mark->Poly,mark); mark->UpdatePoly(); Data->Buffer->Add(mark); Data->AddFromBufer(); MainForm->SendBroadCastMessage(CM_INSERTGROUP,0,(int)Data); Res=true; } } } */ return Res; }
gpl-3.0
geovanisouza92/api-factory
cmd/api-factory-host/main.go
1750
package main import ( "net/http" "time" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/geovanisouza92/api-factory/apifactory" ) func main() { router := chi.NewRouter() router.Use(middleware.RequestID) router.Use(middleware.RealIP) router.Use(middleware.RequestLogger(&loggingFormatter{ // analytics: ?? })) router.Use(middleware.Recoverer) router.Route("/v1/{service}/{resource}", func(r chi.Router) { r.Get("/", getHandler) r.Put("/", putHandler) r.Post("/", postHandler) r.Patch("/", patchHandler) r.Delete("/", deleteHandler) }) http.ListenAndServe(":3000", router) } func getHandler(w http.ResponseWriter, r *http.Request) {} func putHandler(w http.ResponseWriter, r *http.Request) {} func postHandler(w http.ResponseWriter, r *http.Request) {} func patchHandler(w http.ResponseWriter, r *http.Request) {} func deleteHandler(w http.ResponseWriter, r *http.Request) {} type loggingFormatter struct { tracing apifactory.TracingProvider } func (f *loggingFormatter) NewLogEntry(r *http.Request) middleware.LogEntry { ev := apifactory.TracingEvent{} ev.RequestID = middleware.GetReqID(r.Context()) ev.Scheme = "http" if r.TLS != nil { ev.Scheme = "https" } ev.Host = r.Host ev.Method = r.Method ev.RequestURI = r.RequestURI ev.Proto = r.Proto ev.RemoteAddr = r.RemoteAddr return &loggingEntry{tracing: f.tracing, ev: ev} } type loggingEntry struct { tracing apifactory.TracingProvider ev apifactory.TracingEvent } func (e *loggingEntry) Write(status, bytes int, elapsed time.Duration) { e.ev.Status = status e.ev.Bytes = bytes e.ev.Duration = int64(elapsed) e.tracing.Send(e.ev) } func (e *loggingEntry) Panic(v interface{}, stack []byte) { // TODO: }
gpl-3.0
SherlockStd/AcademyJS
src/admin/shared/models/datetime.ts
1047
interface Date { year: number month: number day: number } interface Time { hour: number minute: number second: number } export class DateTime { date: Date time: Time constructor (date?: Date, time?: Time, isoString?: any) { if (date && time) { this.date = date this.time = time } else if (isoString) { const re = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z$/i) if (re.test(isoString)) { const datetime = new Date(isoString) this.date = { year: datetime.getFullYear(), month: datetime.getMonth() + 1, day: datetime.getDate() } this.time = { hour: datetime.getHours(), minute: datetime.getMinutes(), second: 0 } } } } toISOString () { // tslint:disable-next-line:max-line-length const datestring = `${this.date.year}-${this.date.month}-${this.date.day} ${this.time.hour}:${this.time.minute}:${this.time.second}` return new Date(datestring).toISOString() } }
gpl-3.0
anandkumarpathak/mysql-rest
mysql-rest-service/src/main/java/com/andy/security/api/User.java
1172
package com.andy.security.api; import java.security.Principal; public class User implements Principal { private String uid; private String firstName; private String lastName; private String password; private String hash; public String getName() { return getFirstName() + " " + getLastName(); } public String getHash() { return hash; } public void setHash(String hash) { this.hash = hash; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return "User [uid=" + uid + ", firstName=" + firstName + ", lastName=" + lastName + ", password=" + password + ", hash=" + hash + "]"; } }
gpl-3.0
things-cx/ThingsWebApp
Things.WebApp/src/app/login/login.module.ts
640
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ReactiveFormsModule } from '@angular/forms'; import { LoginComponent } from './login/login.component'; import { LoginRoutingModule } from '../login/login-routing.module'; import { MdButtonModule, MdCardModule, MdInputModule, MdProgressSpinnerModule } from '@angular/material'; @NgModule({ imports: [ CommonModule, LoginRoutingModule, MdButtonModule, MdCardModule, MdInputModule, MdProgressSpinnerModule, ReactiveFormsModule ], declarations: [ LoginComponent ] }) export class LoginModule { }
gpl-3.0
TomasVaskevicius/bouncy-particle-sampler
third_party/stan_math/stan/math/prim/mat/meta/value_type.hpp
638
#ifndef STAN_MATH_PRIM_MAT_META_VALUE_TYPE_HPP #define STAN_MATH_PRIM_MAT_META_VALUE_TYPE_HPP #include <stan/math/prim/scal/meta/value_type.hpp> #include <Eigen/Core> namespace stan { namespace math { /** * Template metaprogram defining the type of values stored in an * Eigen matrix, vector, or row vector. * * @tparam T type of matrix. * @tparam R number of rows for matrix. * @tparam C number of columns for matrix. */ template <typename T, int R, int C> struct value_type<Eigen::Matrix<T, R, C> > { typedef typename Eigen::Matrix<T, R, C>::Scalar type; }; } } #endif
gpl-3.0
fwahyudi17/ofiskita
catalog/controller/common/cosyone_cookie.php
2632
<?php class ControllerCommonCosyoneCookie extends Controller { public function index() { // Cookie Control $data['cosyone_use_cookie'] = $this->config->get('cosyone_use_cookie'); $cosyone_cookie_text = $this->config->get('cosyone_cookie_text'); if(empty($cosyone_cookie_text[$this->language->get('code')])) { $data['cosyone_cookie_message'] = false; } else if (isset($cosyone_cookie_text[$this->language->get('code')])) { $data['cosyone_cookie_message'] = html_entity_decode($cosyone_cookie_text[$this->language->get('code')], ENT_QUOTES, 'UTF-8'); } $cosyone_cookie_button_readmore = $this->config->get('cosyone_cookie_button_readmore'); if(empty($cosyone_cookie_button_readmore[$this->language->get('code')])) { $data['cosyone_readmore_text'] = false; } else if (isset($cosyone_cookie_button_readmore[$this->language->get('code')])) { $data['cosyone_readmore_text'] = html_entity_decode($cosyone_cookie_button_readmore[$this->language->get('code')], ENT_QUOTES, 'UTF-8'); } $cosyone_cookie_button_accept = $this->config->get('cosyone_cookie_button_accept'); if(empty($cosyone_cookie_button_accept[$this->language->get('code')])) { $data['cosyone_button_accept_text'] = false; } else if (isset($cosyone_cookie_button_accept[$this->language->get('code')])) { $data['cosyone_button_accept_text'] = html_entity_decode($cosyone_cookie_button_accept[$this->language->get('code')], ENT_QUOTES, 'UTF-8'); } $data['cosyone_readmore_url'] = $this->config->get('cosyone_readmore_url'); // Old IE check $data['cosyone_use_ie'] = $this->config->get('cosyone_use_ie'); $cosyone_ie_update_text = $this->config->get('cosyone_ie_update_text'); if(empty($cosyone_ie_update_text[$this->language->get('code')])) { $data['cosyone_ie_update_message'] = false; } else if (isset($cosyone_ie_update_text[$this->language->get('code')])) { $data['cosyone_ie_update_message'] = html_entity_decode($cosyone_ie_update_text[$this->language->get('code')], ENT_QUOTES, 'UTF-8'); } $cosyone_ie_text = $this->config->get('cosyone_ie_text'); if(empty($cosyone_ie_text[$this->language->get('code')])) { $data['cosyone_ie_message'] = false; } else if (isset($cosyone_ie_text[$this->language->get('code')])) { $data['cosyone_ie_message'] = html_entity_decode($cosyone_ie_text[$this->language->get('code')], ENT_QUOTES, 'UTF-8'); } $data['cosyone_ie_url'] = $this->config->get('cosyone_ie_url'); return $this->load->view('ofisindi/template/common/cosyone_cookie.tpl', $data); } public function info() { $this->response->setOutput($this->index()); } }
gpl-3.0
jahir/volkszaehler.org
lib/Server/PPMBootstrapAdapter.php
1369
<?php /** * @author Andreas Goetz <[email protected]> * @copyright Copyright (c) 2011-2018, The volkszaehler.org project * @license https://www.gnu.org/licenses/gpl-3.0.txt GNU General Public License version 3 */ /* * This file is part of volkzaehler.org * * volkzaehler.org 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 * any later version. * * volkzaehler.org 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 volkszaehler.org. If not, see <http://www.gnu.org/licenses/>. */ namespace Volkszaehler\Server; use Volkszaehler\Router; use PHPPM\Bootstraps\BootstrapInterface; // move out of lib/server define('VZ_DIR', realpath(__DIR__ . '/../..')); require_once(VZ_DIR . '/lib/bootstrap.php'); /** * Bootstrap bridge for Router */ class PPMBootstrapAdapter implements BootstrapInterface { /** * Create middleware router */ public function getApplication() { $app = new Router(); return $app; } }
gpl-3.0
KubaKaszycki/FreeCraft
src/main/java/kk/freecraft/network/play/server/S2APacketParticles.java
4091
/* * Copyright (C) Mojang AB * All rights reserved. */ package kk.freecraft.network.play.server; import java.io.IOException; import kk.freecraft.network.INetHandler; import kk.freecraft.network.Packet; import kk.freecraft.network.PacketBuffer; import kk.freecraft.network.play.INetHandlerPlayClient; import kk.freecraft.util.EnumParticleTypes; public class S2APacketParticles implements Packet { private EnumParticleTypes field_179751_a; private float field_149234_b; private float field_149235_c; private float field_149232_d; private float field_149233_e; private float field_149230_f; private float field_149231_g; private float field_149237_h; private int field_149238_i; private boolean field_179752_j; private int[] field_179753_k; public S2APacketParticles() { } public S2APacketParticles(EnumParticleTypes p_i45977_1_, boolean p_i45977_2_, float p_i45977_3_, float p_i45977_4_, float p_i45977_5_, float p_i45977_6_, float p_i45977_7_, float p_i45977_8_, float p_i45977_9_, int p_i45977_10_, int... p_i45977_11_) { this.field_179751_a = p_i45977_1_; this.field_179752_j = p_i45977_2_; this.field_149234_b = p_i45977_3_; this.field_149235_c = p_i45977_4_; this.field_149232_d = p_i45977_5_; this.field_149233_e = p_i45977_6_; this.field_149230_f = p_i45977_7_; this.field_149231_g = p_i45977_8_; this.field_149237_h = p_i45977_9_; this.field_149238_i = p_i45977_10_; this.field_179753_k = p_i45977_11_; } /** * Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer data) throws IOException { this.field_179751_a = EnumParticleTypes.func_179342_a(data.readInt()); if (this.field_179751_a == null) { this.field_179751_a = EnumParticleTypes.BARRIER; } this.field_179752_j = data.readBoolean(); this.field_149234_b = data.readFloat(); this.field_149235_c = data.readFloat(); this.field_149232_d = data.readFloat(); this.field_149233_e = data.readFloat(); this.field_149230_f = data.readFloat(); this.field_149231_g = data.readFloat(); this.field_149237_h = data.readFloat(); this.field_149238_i = data.readInt(); int var2 = this.field_179751_a.func_179345_d(); this.field_179753_k = new int[var2]; for (int var3 = 0; var3 < var2; ++var3) { this.field_179753_k[var3] = data.readVarIntFromBuffer(); } } /** * Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer data) throws IOException { data.writeInt(this.field_179751_a.func_179348_c()); data.writeBoolean(this.field_179752_j); data.writeFloat(this.field_149234_b); data.writeFloat(this.field_149235_c); data.writeFloat(this.field_149232_d); data.writeFloat(this.field_149233_e); data.writeFloat(this.field_149230_f); data.writeFloat(this.field_149231_g); data.writeFloat(this.field_149237_h); data.writeInt(this.field_149238_i); int var2 = this.field_179751_a.func_179345_d(); for (int var3 = 0; var3 < var2; ++var3) { data.writeVarIntToBuffer(this.field_179753_k[var3]); } } public EnumParticleTypes func_179749_a() { return this.field_179751_a; } public boolean func_179750_b() { return this.field_179752_j; } public double func_149220_d() { return (double) this.field_149234_b; } public double func_149226_e() { return (double) this.field_149235_c; } public double func_149225_f() { return (double) this.field_149232_d; } public float func_149221_g() { return this.field_149233_e; } public float func_149224_h() { return this.field_149230_f; } public float func_149223_i() { return this.field_149231_g; } public float func_149227_j() { return this.field_149237_h; } public int func_149222_k() { return this.field_149238_i; } public int[] func_179748_k() { return this.field_179753_k; } public void func_180740_a(INetHandlerPlayClient p_180740_1_) { p_180740_1_.handleParticles(this); } /** * Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandler handler) { this.func_180740_a((INetHandlerPlayClient) handler); } }
gpl-3.0
danielhuson/dendroscope3
src/dendroscope/embed/EmbedderForOrderPrescribedNetwork.java
19747
/* * EmbedderForOrderPrescribedNetwork.java Copyright (C) 2020 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dendroscope.embed; import dendroscope.consensus.Cluster; import dendroscope.window.TreeViewer; import jloda.graph.Edge; import jloda.graph.Node; import jloda.graph.NodeArray; import jloda.phylo.PhyloTree; import jloda.util.ProgressSilent; import java.io.IOException; import java.util.*; /** * computes an embedding for an order-prescribed network * Daniel Huson, 6.2011 */ public class EmbedderForOrderPrescribedNetwork { private static final boolean verbose = false; /** * given a mapping of each leaf to a different position, computes an embedding of the network that respects the ordering * * @param treeViewer * @param node2pos */ public static void apply(TreeViewer treeViewer, Map<Node, Float> node2pos) throws IOException { PhyloTree tree = treeViewer.getPhyloTree(); if (tree.getRoot() != null) { if (verbose) System.err.println("Original network: " + treeViewer.getPhyloTree().toString() + ";"); // recompute the lsa layout (new LayoutUnoptimized()).apply(tree, new ProgressSilent()); // get ordering of labeled leaves Node[] orderedLabeledLeaves = computeOrderedLabeledLeaves(node2pos); // assign numbers to all subtrees obtained by disregarding all reticulate edges: NodeArray<Integer> node2SubTreeId = new NodeArray<Integer>(tree); Map<Integer, Node> subTreeId2Root = new HashMap<Integer, Node>(); int numberOfSubTrees = 0; for (Node v = tree.getFirstNode(); v != null; v = v.getNext()) { if (node2SubTreeId.get(v) == null && v.getInDegree() != 1) { computeNode2SubTreeIdRec(v, ++numberOfSubTrees, node2SubTreeId); subTreeId2Root.put(numberOfSubTrees, v); } } if (verbose) { System.err.println("Leaf to subtree:"); for (Node v = tree.getFirstNode(); v != null; v = v.getNext()) { if (v.getOutDegree() == 0) { System.err.println("Leaf " + tree.getLabel(v) + " contained in subtree: " + node2SubTreeId.get(v)); } } System.err.println("Position to subtree:"); for (int p = 0; p < orderedLabeledLeaves.length; p++) { Node v = orderedLabeledLeaves[p]; System.err.println(" Position=" + p + " has label: " + tree.getLabel(v) + ", is subtree: " + node2SubTreeId.get(v)); } } // map each reticulate node to its lsa parent Map<Node, Node> node2lsaParent = new HashMap<Node, Node>(); for (Node v = tree.getFirstNode(); v != null; v = v.getNext()) { if (tree.getNode2GuideTreeChildren().get(v) != null) { for (Node w : tree.getNode2GuideTreeChildren().get(v)) { if (w.getInDegree() > 1) node2lsaParent.put(w, v); } } } // find nested subtrees and redirect their lsa edges to aim to lca of adjacent nodes of nesting subtree processNestedSubTrees(node2SubTreeId, numberOfSubTrees, subTreeId2Root, node2lsaParent, orderedLabeledLeaves, tree); // extend node 2 pos mapping from labeled leaves to all nodes extendNode2PosRec(tree.getRoot(), node2pos); // reorder the children of each node so that they reflect computed ordering for (Node v = tree.getFirstNode(); v != null; v = v.getNext()) { reorderChildren(v, node2pos); } if (verbose) System.err.println("Reordered network: " + treeViewer.getPhyloTree().toString() + ";"); } } /** * process all nested subtrees (nested means that in the ordering of taxa there is some other subtree with leaves * boht before and after the one considered) * * @param node2SubTreeId * @param numberOfSubTrees * @param tree */ private static void processNestedSubTrees(NodeArray<Integer> node2SubTreeId, int numberOfSubTrees, Map<Integer, Node> subTreeId2Root, Map<Node, Node> node2lsaParent, Node[] orderedLabeledLeaves, PhyloTree tree) throws IOException { Integer[] first = new Integer[numberOfSubTrees + 1]; Integer[] last = new Integer[numberOfSubTrees + 1]; int pos = 0; for (Node v : orderedLabeledLeaves) { if (v != null) { int id = node2SubTreeId.get(v); // System.err.println("Leaf: " + tree.getLabel(v) + " subtreeId: " + id); if (first[id] == null) first[id] = pos; last[id] = pos; pos++; } } int count = 0; // process each subtree: for (int id = 1; id <= numberOfSubTrees; id++) { Node subTreeRoot = subTreeId2Root.get(id); Node lsaParent = node2lsaParent.get(subTreeRoot); if (lsaParent != null) { BitSet before = new BitSet(); BitSet between = new BitSet(); BitSet after = new BitSet(); int firstPos = first[id]; int lastPos = last[id]; for (int p = 0; p < orderedLabeledLeaves.length; p++) { Node v = orderedLabeledLeaves[p]; if (v != null) { int vId = node2SubTreeId.get(v); if (p < firstPos) before.set(vId); else if (p > firstPos && p < lastPos) between.set(vId); else if (p > lastPos) after.set(vId); } } if (between.intersects(before) || between.intersects(after)) System.err.println("WARNING: not nested"); before.andNot(between); after.andNot(between); BitSet spans = Cluster.intersection(before, after); if (spans.cardinality() > 0) { Node leftNode = null; Node rightNode = null; int spanId = 0; for (int p = firstPos - 1; p >= 0; p--) { Node v = orderedLabeledLeaves[p]; if (v != null) { int vId = node2SubTreeId.get(v); if (spans.get(vId)) { spanId = vId; leftNode = v; break; } } } for (int p = lastPos + 1; p < orderedLabeledLeaves.length; p++) { Node v = orderedLabeledLeaves[p]; if (v != null) { int vId = node2SubTreeId.get(v); if (vId == spanId) { rightNode = v; break; } } } if (leftNode != null && rightNode != null) { // if (++count < 19) moveLSAParentToEnclosingSubTreeNode(lsaParent, leftNode, rightNode, subTreeRoot); } } else //is not nested inside another tree { moveLSAParentToRoot(lsaParent, tree.getRoot(), subTreeRoot); } } } } /** * remove the lsa edge from lsaParent to v and reattach it so as to lead from the lca of leftNode and rightNode to v * * @param lsaParent * @param leftNode * @param rightNode * @param v */ private static void moveLSAParentToEnclosingSubTreeNode(Node lsaParent, Node leftNode, Node rightNode, Node v) throws IOException { if (v.getInDegree() == 1) throw new IOException("Not subtree root"); PhyloTree tree = (PhyloTree) lsaParent.getOwner(); if (true) { Queue<Node> queue = new LinkedList<Node>(); queue.add(v); String label = null; while (label == null && queue.size() > 0) { Node z = queue.poll(); if (tree.getLabel(z) != null) label = tree.getLabel(z); else { for (Edge e = z.getFirstOutEdge(); e != null; e = z.getNextOutEdge(e)) { Node u = e.getTarget(); if (u.getInDegree() <= 1) queue.add(u); } } } if (verbose) System.err.println("Moving parent of subtree containing '" + label + "' to LCA(" + tree.getLabel(leftNode) + "," + tree.getLabel(rightNode) + ")"); } if (!tree.getNode2GuideTreeChildren().get(lsaParent).contains(v)) throw new IOException("Not an LSA child"); tree.getNode2GuideTreeChildren().get(lsaParent).remove(v); Node lca = getLCA(leftNode, rightNode); tree.getNode2GuideTreeChildren().get(lca).add(v); } /** * remove the lsa edge from lsaParent to v and reattach it so as to lead from the root to v * * @param lsaParent * @param root * @param v */ private static void moveLSAParentToRoot(Node lsaParent, Node root, Node v) throws IOException { PhyloTree tree = (PhyloTree) lsaParent.getOwner(); if (true) { Queue<Node> queue = new LinkedList<Node>(); queue.add(v); String label = null; while (label == null && queue.size() > 0) { Node z = queue.poll(); if (tree.getLabel(z) != null) label = tree.getLabel(z); else { for (Edge e = z.getFirstOutEdge(); e != null; e = z.getNextOutEdge(e)) { Node u = e.getTarget(); if (u.getInDegree() <= 1) queue.add(u); } } } if (verbose) System.err.println("Moving parent of subtree containing '" + label + "' to root"); } if (!tree.getNode2GuideTreeChildren().get(lsaParent).contains(v)) throw new IOException("Not an LSA child"); tree.getNode2GuideTreeChildren().get(lsaParent).remove(v); tree.getNode2GuideTreeChildren().get(root).add(v); } /** * gets the lca of two nodes * * @param a * @param b * @return lca(a, b) */ private static Node getLCA(Node a, Node b) throws IOException { Set<Node> aboveA = new HashSet<Node>(); while (true) { aboveA.add(a); if (a.getInDegree() != 1) break; a = a.getFirstInEdge().getSource(); } while (true) { if (aboveA.contains(b)) return b; if (b.getInDegree() != 1) break; b = b.getFirstInEdge().getSource(); } if (!aboveA.contains(b)) throw new IOException("Failed to determine LCA in tree"); return ((PhyloTree) b.getOwner()).getRoot(); } /** * extend the node2pos ordering to all nodes of the tree * * @param v * @param node2pos */ public static void extendNode2PosRec(Node v, Map<Node, Float> node2pos) { if (node2pos.get(v) == null) { float pos = Integer.MAX_VALUE; for (Node w : getLSAChildren(v)) { extendNode2PosRec(w, node2pos); pos = Math.min(node2pos.get(w), pos); } // todo: if leaf without label, need to compute a better value using reticulate edges... node2pos.put(v, pos); } } /** * get all children in tree, or LSA tree of network * * @param v * @return all children */ private static List<Node> getLSAChildren(Node v) { List<Node> targetNodes = null; if (((PhyloTree) v.getOwner()).getNode2GuideTreeChildren().get(v) != null) targetNodes = ((PhyloTree) v.getOwner()).getNode2GuideTreeChildren().get(v); List<Node> list = new LinkedList<Node>(); if (targetNodes == null) { for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { if (!v.getOwner().isSpecial(e)) list.add(e.getTarget()); } } else { for (Node w : targetNodes) { list.add(w); } } return list; } /** * list labeled leafr nodes in order of appearance * * @param node2pos * @return */ private static Node[] computeOrderedLabeledLeaves(Map<Node, Float> node2pos) { SortedMap<Float, Node> pos2node = new TreeMap<Float, Node>(); for (Node v : node2pos.keySet()) { pos2node.put(node2pos.get(v), v); } Node[] array = new Node[pos2node.size()]; int i = 0; for (Float f : pos2node.keySet()) { array[i++] = pos2node.get(f); } return array; } /** * recursively number each subtree in the forest obtained by ignoring all reticulate edges * * @param v * @param subTreeId */ private static void computeNode2SubTreeIdRec(Node v, int subTreeId, NodeArray<Integer> node2SubTreeId) { if (node2SubTreeId.get(v) == null) { node2SubTreeId.put(v, subTreeId); for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { Node w = e.getTarget(); if (w.getInDegree() == 1) // e not a reticulate edge { computeNode2SubTreeIdRec(w, subTreeId, node2SubTreeId); } } } } /** * reorder the lsa children of a node * * @param v * @param node2pos */ private static void reorderChildren(Node v, final Map<Node, Float> node2pos) { List<Node> lsaChildren = ((PhyloTree) v.getOwner()).getNode2GuideTreeChildren().get(v); if (lsaChildren != null) { SortedSet<Node> nodes = new TreeSet<Node>(new Comparator<Node>() { public int compare(Node w1, Node w2) { float pos1 = node2pos.get(w1); float pos2 = node2pos.get(w2); if (pos1 < pos2) return -1; else if (pos1 > pos2) return 1; else if (w1.getId() < w2.getId()) return -1; else if (w1.getId() > w2.getId()) return 1; else return 0; } }); nodes.addAll(lsaChildren); lsaChildren.clear(); lsaChildren.addAll(nodes); } SortedSet<Edge> edges = new TreeSet<Edge>(new Comparator<Edge>() { public int compare(Edge e1, Edge e2) { Node w1 = e1.getTarget(); Node w2 = e2.getTarget(); float pos1 = node2pos.get(w1); float pos2 = node2pos.get(w2); if (pos1 < pos2) return -1; else if (pos1 > pos2) return 1; else if (w1.getId() < w2.getId()) return -1; else if (w1.getId() > w2.getId()) return 1; else return 0; } }); for (Edge e : v.adjacentEdges()) { edges.add(e); } v.rearrangeAdjacentEdges(edges); } /** * compute alphabetical ordering of leaves, for debugging purposes * * @param treeViewer * @return ordering of leaves * @throws IOException */ public static Map<Node, Float> setupAlphabeticalOrdering(TreeViewer treeViewer) throws IOException { Map<String, Node> label2node = new HashMap<String, Node>(); SortedSet<String> taxLabels = new TreeSet<String>(); PhyloTree tree = treeViewer.getPhyloTree(); for (Node v = tree.getFirstNode(); v != null; v = v.getNext()) { String label = tree.getLabel(v); if (label != null) { label = label.trim(); if (label.length() > 0) { if (v.getOutDegree() > 0) throw new IOException("Internal node has label: " + label); if (taxLabels.contains(label)) throw new IOException("Multiple occurrence of label: " + label); label2node.put(label, v); taxLabels.add(label); } } } Map<Node, Float> node2pos = new HashMap<Node, Float>(); int count = 0; for (String label : taxLabels) { node2pos.put(label2node.get(label), (float) ++count); } return node2pos; } /** * return ordering of leaves to reflect list of names * * @param treeViewer * @param names * @return ordering of labeled leaves */ public static Map<Node, Float> setupOrderingFromNames(TreeViewer treeViewer, List<String> names) throws IOException { Node[] nodes = new Node[names.size()]; Map<String, Integer> name2pos = new HashMap<String, Integer>(); int pos = 0; for (String name : names) { name2pos.put(name, pos++); } PhyloTree tree = treeViewer.getPhyloTree(); for (Node v = tree.getFirstNode(); v != null; v = v.getNext()) { if (v.getOutDegree() == 0) { String name = tree.getLabel(v); if (name == null || name.trim().length() == 0) throw new IOException("Unlabeled leaf encountered"); Integer thePos = name2pos.get(name); if (thePos == null) throw new IOException("Leaf-label without position encountered: " + name); nodes[thePos] = v; } } Map<Node, Float> node2pos = new HashMap<Node, Float>(); for (int i = 0; i < nodes.length; i++) node2pos.put(nodes[i], (float) i + 1); return node2pos; } }
gpl-3.0
z-chu/FriendBook
app/src/main/java/com/youshibi/app/ui/widget/ShapeTextView.java
790
package com.youshibi.app.ui.widget; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; /** * Created by Chu on 2017/8/22. */ public class ShapeTextView extends android.support.v7.widget.AppCompatTextView { public ShapeTextView(Context context) { super(context); } public ShapeTextView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); initSuperShapeView(attrs); } public ShapeTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initSuperShapeView(attrs); } private void initSuperShapeView(AttributeSet attrs) { new SuperConfig().beSuperView(attrs, this); } }
gpl-3.0
DISID/disid-proofs
many-to-many-concurrency-control/src/main/java/org/disid/proof/repository/BookRepositoryImpl.java
611
package org.disid.proof.repository; import io.springlets.data.jpa.repository.support.QueryDslRepositorySupportExt; import org.springframework.roo.addon.layers.repository.jpa.annotations.RooJpaRepositoryCustomImpl; import org.disid.proof.domain.Book; /** * = BookRepositoryImpl * * TODO Auto-generated class documentation * */ @RooJpaRepositoryCustomImpl(repository = BookRepositoryCustom.class) public class BookRepositoryImpl extends QueryDslRepositorySupportExt<Book> { /** * TODO Auto-generated constructor documentation */ BookRepositoryImpl() { super(Book.class); } }
gpl-3.0
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/xmlutil/XmlUtilities.java
16514
/* * Copyright © 2012 jbundle.org. All rights reserved. */ package org.jbundle.base.db.xmlutil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.xml.parsers.DocumentBuilder; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.jbundle.base.db.BaseTable; import org.jbundle.base.db.Record; import org.jbundle.base.field.BaseField; import org.jbundle.base.field.CounterField; import org.jbundle.base.field.DateField; import org.jbundle.base.field.DateTimeField; import org.jbundle.base.field.HtmlField; import org.jbundle.base.field.ObjectField; import org.jbundle.base.field.TimeField; import org.jbundle.base.field.UnusedField; import org.jbundle.base.field.XMLPropertiesField; import org.jbundle.base.field.XmlField; import org.jbundle.base.model.DBConstants; import org.jbundle.base.model.Utility; import org.jbundle.base.model.XMLTags; import org.jbundle.model.DBException; import org.jbundle.thin.base.db.Constants; import org.jbundle.thin.base.util.base64.Base64; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * This utility is used to import and export to XML file(s). * The import utility is very flexible, including the capability to import multi-level * records including sub-records and fields referencing main records. * <p>This class also has the capability to be run alone as a utility for imports only. * If you want a standalone utility for exports, use the class "ExportRecordsToXMLProcess." * <pre> * The params to pass in are: * filename - the name of the target XML file to import. * import - the name of the target XML file to import. * export - the name of the target XML file to export. * overwritedups - true if you want to overwrite duplicate records in import. * </pre> */ public class XmlUtilities extends Object { public final static String XML_ENCODING = "UTF-8"; public final static String XML_LEAD_LINE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; public final static String TEXT = "TEXT"; public final static String CDATA = "CDATA"; public final static String XML = "XML"; public static final String TYPE_PARAM = "type"; public static final String XML_VALUE = "XML"; public static final String NEWLINE = "\n"; public static final String RECORDTAB = "\t"; public static final String FIELDTAB = "\t\t"; public static final String TEMP_TAG_NAME = "temporary-tag"; public static final String START_TEMP_TAG = "<" + TEMP_TAG_NAME + ">"; public static final String END_TEMP_TAG = "</" + TEMP_TAG_NAME + ">"; /** * The parameter for the encoding attribute. */ public static final String ENCTYPE_PARAM = "enctype"; /** * The default encoding for raw data fields. */ public static final String BINARYENCODING = "base64"; //? "base64", "quoted-printable", "7bit", "8bit", and "binary". "uuencode" /** * The root tag for records. */ public static final String ROOT_TAG = "record"; /** * Export this table. * @record The record to export. * @strFileName The distination filename (deleted the old copy if this file exists). */ public static Document exportFileToDoc(BaseTable table) { DocumentBuilder db = Utility.getDocumentBuilder(); DocumentBuilder stringdb = Utility.getDocumentBuilder(); Document doc = null; synchronized (db) { doc = db.newDocument(); Element elRoot = (Element)doc.createElement(XMLTags.FILE); doc.appendChild(elRoot); exportFileToDOM(stringdb, table, doc, elRoot); } return doc; } /** * Export this table. * @record The record to export. * @strFileName The distination filename (deleted the old copy if this file exists). */ public static void exportFileToDOM(DocumentBuilder stringdb, BaseTable table, Document doc, Element elRoot) { try { table.close(); while (table.hasNext()) { table.next(); Record record = table.getRecord(); XmlUtilities.createXMLRecord(stringdb, record, doc, elRoot); } elRoot.appendChild(doc.createTextNode(NEWLINE)); } catch (DBException ex) { ex.printStackTrace(); System.exit(0); } } /** * Write out this record as an dom object. * @param stringdb The document builder that gives you access to a parser. * @param record The record to convert to an XML dom record. * @param document The XML dom document, giving you access to createElement methods. * @param elRoot The root element to add this XML record to. */ public static void createXMLRecord(DocumentBuilder stringdb, Record record, Document doc, Element elRoot) throws DBException { CounterField fldCounter = (CounterField)record.getCounterField(); Element elRecord = null; Element elField = null; elRecord = doc.createElement(record.getTableNames(false)); elRoot.appendChild(doc.createTextNode(NEWLINE + RECORDTAB)); elRoot.appendChild(elRecord); String strObjectIDName = DBConstants.STRING_OBJECT_ID_HANDLE; String strObjectID = null; Object objID = record.getHandle(DBConstants.OBJECT_ID_HANDLE); if (fldCounter != null) { strObjectIDName = fldCounter.getFieldName(); if (objID == null) // ie., for a non-persistent object objID = record.getHandle(DBConstants.BOOKMARK_HANDLE); } if (objID != null) strObjectID = objID.toString(); if (strObjectID != null) if (fldCounter == record.getField(0)) elRecord.setAttribute(strObjectIDName, strObjectID); for (int i = 0; i < record.getFieldCount(); i++) { BaseField field = record.getField(i); if (field == fldCounter) if (strObjectID != null) continue; // Not necessary to add counter field if (field instanceof UnusedField) continue; // Don't add this. elRecord.appendChild(doc.createTextNode(NEWLINE + FIELDTAB)); elRecord.appendChild(elField = doc.createElement(field.getFieldName())); if (!field.isNull()) { String string = field.toString(); String type = TEXT; if ((field instanceof ObjectField) && (field.getDataClass() == Object.class)) { string = XmlUtilities.encodeFieldData(field); type = CDATA; if ((string != null) && (string.length() > 0)) elField.setAttribute(ENCTYPE_PARAM, BINARYENCODING); } else if (field instanceof DateTimeField) { string = XmlUtilities.encodeDateTime((DateTimeField)field); } else if ((field instanceof XmlField) || (field instanceof XMLPropertiesField) || (field instanceof HtmlField)) { if ((string != null) && (string.length() > 0)) { type = XML; String strXML = string; boolean bNoRootNode = true; if ((strXML.length() < 5) || (!strXML.substring(0, 5).equalsIgnoreCase(XML_LEAD_LINE.substring(0, 5)))) strXML = XML_LEAD_LINE + START_TEMP_TAG + strXML + END_TEMP_TAG; // Always else bNoRootNode = false; InputSource is = new InputSource(new StringReader(strXML)); Document fieldDoc = null; boolean bError = false; try { fieldDoc = stringdb.parse(is); } catch (SAXException ex) { Utility.getLogger().info("Fallback to CData"); bError = true; } catch (IOException ex) { ex.printStackTrace(); bError = true; } if (!bError) { // Add the child nodes to this node (with type="XML") Node element = fieldDoc.getDocumentElement(); Node node = doc.importNode(element, true); int iCount = 0; if (bNoRootNode) { while (node.hasChildNodes()) { Node child = node.getFirstChild(); node.removeChild(child); elField.appendChild(child); iCount++; if (child.getNodeType() != Node.TEXT_NODE) iCount++; } } else { elField.appendChild(node); iCount = 20; // XML type } if (iCount > 1) // For everthing except a single text node type=xml elField.setAttribute(TYPE_PARAM, XML_VALUE); // A text field would have 1 element (not XML). } else { type = TEXT; if (Utility.isCData(string)) type = CDATA; // If not well-formed, just pass the string as CData. } } } else if (Utility.isCData(string)) type = CDATA; if (type == TEXT) elField.appendChild(doc.createTextNode(string)); else if (type == CDATA) elField.appendChild(doc.createCDATASection(string)); } } elRecord.appendChild(doc.createTextNode(NEWLINE + RECORDTAB)); } public static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); public static SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); /** * Encode date time field. * @param field * @return */ public static String encodeDateTime(DateTimeField field) { Date date = ((DateTimeField)field).getDateTime(); if (date == null) return null; if (field instanceof TimeField) return timeFormat.format(date); else if (field instanceof DateField) return dateFormat.format(date); else // if (field instanceof DateTimeField) return dateTimeFormat.format(date); } /** * Decode date time value and set the field value. * @param field * @return */ public static int decodeDateTime(DateTimeField field, String strValue) { Date date = null; try { if (strValue != null) { if (field instanceof TimeField) date = timeFormat.parse(strValue); else if (field instanceof DateField) date = dateFormat.parse(strValue); else // if (field instanceof DateTimeField) date = dateTimeFormat.parse(strValue); } } catch (ParseException e) { e.printStackTrace(); return DBConstants.ERROR_RETURN; } return field.setDateTime(date, Constants.DISPLAY, Constants.SCREEN_MOVE); } /** * Convert the current record to an XML String. * Careful, as this method just returns the XML fragment (with header or a top-level tag). * @param The record to convert. * @return The XML representation of this record. */ public static String createXMLStringRecord(Record record) { String string = DBConstants.BLANK; DocumentBuilder db = Utility.getDocumentBuilder(); DocumentBuilder stringdb = Utility.getDocumentBuilder(); Document doc = null; synchronized (db) { doc = db.newDocument(); Element elRoot = (Element)doc.createElement(ROOT_TAG); doc.appendChild(elRoot); try { XmlInOut.enableAllBehaviors(record, false, true); // Disable file behaviors createXMLRecord(stringdb, record, doc, elRoot); elRoot.appendChild(doc.createTextNode(XmlUtilities.NEWLINE)); } catch (DBException ex) { ex.printStackTrace(); return DBConstants.BLANK; } } try { StringWriter out = new StringWriter(); //, MIME2Java.convert("UTF-8")); // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); transformer.transform(source, result); out.close(); string = out.toString(); int iStartString = string.indexOf("<" + ROOT_TAG + ">") + 3 + ROOT_TAG.length(); int iEndString = string.indexOf("</" + ROOT_TAG + ">"); if (iStartString >= iEndString) string = DBConstants.BLANK; else string = string.substring(iStartString, iEndString); } catch (TransformerConfigurationException tce) { // Error generated by the parser tce.printStackTrace(); } catch (TransformerException te) { // Error generated by the parser te.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } XmlInOut.enableAllBehaviors(record, true, true); return string; } /** * Change the data in this field to base64. * WARNING - This requires 64bit encoding found in javax.mail! * @param field The field containing the binary data to encode. * @return The string encoded using base64. */ public static String encodeFieldData(BaseField field) { if (field.getData() == null) return DBConstants.BLANK; ByteArrayOutputStream baOut = new ByteArrayOutputStream(); DataOutputStream daOut = new DataOutputStream(baOut); try { field.write(daOut, false); daOut.flush(); } catch (IOException e) { e.printStackTrace(); } char[] chOut = Base64.encode(baOut.toByteArray()); if (chOut == null) return DBConstants.BLANK; // Never return new String(chOut); } /** * Change this base64 string to raw data and set the value in this field. * WARNING - This requires 64bit encoding found in javax.mail! * @param field The field containing the binary data to decode. * @param The string to decode using base64. */ public static void decodeFieldData(BaseField field, String string) { if ((string == null) || (string.length() == 0)) return; byte[] ba = Base64.decode(string.toCharArray()); InputStream is = new ByteArrayInputStream(ba); DataInputStream daIn = new DataInputStream(is); field.read(daIn, false); } }
gpl-3.0
AltruisticControlSystems/cxxCore
ConfigManager.cpp
1152
#include "ConfigManager.hpp" #include <QDebug> #include <QFile> #include <QIODevice> namespace cxxCore { //! init //! //! Initialize the ConfigManager void ConfigManager::init() { } //! deInit //! //! De-initialize the ConfigManager void ConfigManager::deInit() { mConfigHash.clear(); } //! loadConfigs //! //! Loads the configs bool ConfigManager::loadConfigs ( const QString& aFilePath //!< The path to the config file ) { QFile configFile(aFilePath); bool success = configFile.open(QIODevice::ReadOnly | QIODevice::Text); if(success) { } return success; } //! getConfig //! //! gets the specified config from the hash QString ConfigManager::getConfig ( const QString& aKey //!< The key to retrieve the config from the hash ) const { QHash<QString,QString>::const_iterator valueIter = mConfigHash.find(aKey); if(valueIter != mConfigHash.end() && valueIter.key() == aKey) { return valueIter.value(); } else { qWarning() << "ConfigManager::getConfig(" << aKey.toLatin1() <<") - Invalid Key"; return QString(); } } } // Namespace cxxCore
gpl-3.0
qyh214/wow_addons_private_use
AddOns/ElvUI_Enhanced/modules/unitframes/update_elements.lua
2024
local E, L, V, P, G = unpack(ElvUI); --Inport: Engine, Locales, PrivateDB, ProfileDB, GlobalDB, Localize Underscore local UF = E:GetModule('UnitFrames'); local sub, find = string.sub, string.find local abs, atan2, cos, sin, sqrt2, random, floor, ceil, random = math.abs, math.atan2, math.cos, math.sin, math.sqrt(2), math.random, math.floor, math.ceil, math.random local pairs, type, select, unpack = pairs, type, select, unpack local GetPlayerMapPosition, GetPlayerFacing = GetPlayerMapPosition, GetPlayerFacing local unitframeFont local function CalculateCorner(r) return 0.5 + cos(r) / sqrt2, 0.5 + sin(r) / sqrt2; end local function RotateTexture(texture, angle) local LRx, LRy = CalculateCorner(angle + 0.785398163); local LLx, LLy = CalculateCorner(angle + 2.35619449); local ULx, ULy = CalculateCorner(angle + 3.92699082); local URx, URy = CalculateCorner(angle - 0.785398163); texture:SetTexCoord(ULx, ULy, LLx, LLy, URx, URy, LRx, LRy); end function UF:UpdateGPS(frame) local gps = frame.gps if not gps then return end -- GPS Disabled or not GPS parent frame visible or not in Party or Raid, Hide gps if not frame:IsVisible() or UnitIsUnit(gps.unit, 'player') or not (UnitInParty(gps.unit) or UnitInRaid(gps.unit)) then gps:Hide() return end if gpsRestricted == true then if (gps.timer) then UF:CancelTimer(gps.timer) gps.timer = nil end gps:Hide() return end -- Arbitrary method to determine if we should try to calculate the map position local x, y = C_Map.GetPlayerMapPosition(C_Map.GetBestMapForUnit(gps.unit), gps.unit):GetXY() local distance, angle if not (x == 0 and y == 0) then -- Unit is in acceptable range, calculate position fast distance, angle = E:GetDistance('player', gps.unit, true) end if not angle then -- no bearing show - to indicate we are lost :) gps.Text:SetText("-") gps.Texture:Hide() gps:Show() return end RotateTexture(gps.Texture, angle) gps.Texture:Show() gps.Text:SetFormattedText("%d", distance) gps:Show() end
gpl-3.0
gbaychev/NClass
src/AssemblyImport/NETImport.cs
17762
// NClass - Free class diagram editor // Copyright (C) 2006-2009 Balazs Tihanyi // Copyright (C) 2020 Georgi Baychev // // 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, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using NClass.AssemblyImport.Lang; using NClass.Core; using NClass.DiagramEditor.ClassDiagram; using NClass.DiagramEditor.ClassDiagram.Shapes; using NClass.DiagramEditor.Diagrams.Connections; using NClass.DiagramEditor.Diagrams.Shapes; using NReflect; using NReflect.Filter; using NReflect.NRCode; using NReflect.NREntities; using NReflect.NRMembers; using NReflect.NRParameters; using NReflect.NRRelationship; using System; using System.Collections.Generic; using System.Drawing; using System.IO; namespace NClass.AssemblyImport { public class NETImport { // ======================================================================== // Constants #region === Constants #endregion // ======================================================================== // Fields #region === Fields /// <summary> /// The diagram to add the new entities to. /// </summary> private readonly ClassDiagram diagram; /// <summary> /// An <see cref="ImportSettings"/> instance which describes which entities and members to reflect. /// </summary> private readonly ImportSettings settings; /// <summary> /// A mapping from NReflects <see cref="NRTypeBase"/> objects to the /// corresponding NClass <see cref="TypeBase"/> objects. /// </summary> private readonly Dictionary<NRTypeBase, TypeBase> types; #endregion // ======================================================================== // Con- / Destruction #region === Con- / Destruction /// <summary> /// Initializes a new instance of <see cref="NETImport"/>. /// </summary> public NETImport(ClassDiagram diagram, ImportSettings settings) { this.diagram = diagram; this.settings = settings; types = new Dictionary<NRTypeBase, TypeBase>(); } #endregion // ======================================================================== // Properties #region === Properties #endregion // ======================================================================== // Methods #region === Methods /// <summary> /// The main entry point of this class. Imports the assembly which is given /// as the parameter. /// </summary> /// <param name="fileName">The file name and path of the assembly to import.</param> /// <returns><c>True</c>, if the import was successful.</returns> public bool ImportAssembly(string fileName, bool useNewAppDomain = true) { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullException(nameof(fileName), Strings.Error_NoAssembly); } try { diagram.Name = Path.GetFileName(fileName); diagram.RedrawSuspended = true; IncludeFilter includeFilter = new IncludeFilter(); includeFilter.Rules.AddRange(settings.FilterRules); IFilter filter = includeFilter; if(!settings.UseAsWhiteList) { filter = new InvertFilter(includeFilter); } NClassImportFilter nClassImportFilter = new NClassImportFilter(filter); Reflector reflector = new Reflector(); filter = nClassImportFilter; NRAssembly nrAssembly = reflector.Reflect(fileName, ref filter, useNewAppDomain); nClassImportFilter = (NClassImportFilter)filter; AddInterfaces(nrAssembly.Interfaces); AddClasses(nrAssembly.Classes); AddStrcts(nrAssembly.Structs); AddDelegates(nrAssembly.Delegates); AddEnums(nrAssembly.Enums); ArrangeTypes(); AddRelationships(nrAssembly); if(nClassImportFilter.UnsafeTypesPresent) { throw new UnsafeTypesPresentException(Strings.UnsafeTypesPresent); } } finally { diagram.RedrawSuspended = false; } return true; } private void AddRelationships(NRAssembly nrAssembly) { if (!settings.CreateRelationships) { return; } RelationshipCreator relationshipCreator = new RelationshipCreator(); NRRelationships nrRelationships = relationshipCreator.CreateRelationships(nrAssembly, settings.CreateNestings, settings.CreateGeneralizations, settings.CreateRealizations, settings.CreateAssociations); AddRelationships(nrRelationships); } /// <summary> /// Adds the relationships from <paramref name="nrRelationships"/> to the /// diagram. /// </summary> /// <param name="nrRelationships">The relationships to add.</param> private void AddRelationships(NRRelationships nrRelationships) { foreach(NRNesting nrNesting in nrRelationships.Nestings) { INestable parentType = types[nrNesting.ParentType] as INestable; INestableChild innerType = types[nrNesting.InnerType]; if(parentType != null && innerType != null) { diagram.AddNesting(parentType, innerType); } } foreach(NRGeneralization nrGeneralization in nrRelationships.Generalizations) { CompositeType derivedType = types[nrGeneralization.DerivedType] as CompositeType; CompositeType baseType = types[nrGeneralization.BaseType] as CompositeType; if(derivedType != null && baseType != null) { diagram.AddGeneralization(derivedType, baseType); } } foreach (NRRealization nrRealization in nrRelationships.Realizations) { CompositeType implementingType = types[nrRealization.ImplementingType] as CompositeType; InterfaceType interfaceType = types[nrRealization.BaseType] as InterfaceType; if (implementingType != null && interfaceType != null) { diagram.AddRealization(implementingType, interfaceType); } } foreach (NRAssociation nrAssociation in nrRelationships.Associations) { TypeBase first = types[nrAssociation.StartType]; TypeBase second = types[nrAssociation.EndType]; if (first != null && second != null) { AssociationRelationship associationRelationship = diagram.AddAssociation(first, second); associationRelationship.EndMultiplicity = nrAssociation.EndMultiplicity; associationRelationship.StartMultiplicity = nrAssociation.StartMultiplicity; associationRelationship.EndRole = nrAssociation.EndRole; associationRelationship.StartRole = nrAssociation.StartRole; } } } /// <summary> /// Creates a nice arrangement for each entity. /// </summary> private void ArrangeTypes() { const int Margin = RoutedConnection.Spacing * 2; const int DiagramPadding = Shape.SelectionMargin; int shapeCount = diagram.ShapeCount; int columns = (int)Math.Ceiling(Math.Sqrt(shapeCount * 2)); int shapeIndex = 0; int top = Shape.SelectionMargin; int maxHeight = 0; foreach (Shape shape in diagram.Shapes) { int column = shapeIndex % columns; shape.Location = new Point( (TypeShape.DefaultWidth + Margin) * column + DiagramPadding, top); maxHeight = Math.Max(maxHeight, shape.Height); if (column == columns - 1) { top += maxHeight + Margin; maxHeight = 0; } shapeIndex++; } } #region --- Entities /// <summary> /// Adds the submitted classes to the diagram. /// </summary> /// <param name="classes">A list of classes to add.</param> private void AddClasses(IEnumerable<NRClass> classes) { foreach (NRClass nrClass in classes) { ClassType classType = diagram.AddClass(); classType.Name = nrClass.Name; classType.AccessModifier = nrClass.AccessModifier.ToNClass(); classType.Modifier = nrClass.ClassModifier.ToNClass(); AddFields(classType, nrClass.Fields); AddProperties(classType, nrClass.Properties); AddEvents(classType, nrClass.Events); AddConstructors(classType, nrClass.Constructors); AddMethods(classType, nrClass.Methods); AddOperators(classType, nrClass.Operators); types.Add(nrClass, classType); } } /// <summary> /// Adds the submitted structs to the diagram. /// </summary> /// <param name="structs">A list of structs to add.</param> private void AddStrcts(IEnumerable<NRStruct> structs) { foreach (NRStruct nrStruct in structs) { StructureType structureType = diagram.AddStructure(); structureType.Name = nrStruct.Name; structureType.AccessModifier = nrStruct.AccessModifier.ToNClass(); AddFields(structureType, nrStruct.Fields); AddProperties(structureType, nrStruct.Properties); AddEvents(structureType, nrStruct.Events); AddConstructors(structureType, nrStruct.Constructors); AddMethods(structureType, nrStruct.Methods); AddOperators(structureType, nrStruct.Operators); types.Add(nrStruct, structureType); } } /// <summary> /// Adds the submitted interfaces to the diagram. /// </summary> /// <param name="interfaces">A list of interfaces to add.</param> private void AddInterfaces(IEnumerable<NRInterface> interfaces) { foreach (NRInterface nrInterface in interfaces) { InterfaceType interfaceType = diagram.AddInterface(); interfaceType.Name = nrInterface.Name; interfaceType.AccessModifier = nrInterface.AccessModifier.ToNClass(); AddProperties(interfaceType, nrInterface.Properties); AddEvents(interfaceType, nrInterface.Events); AddMethods(interfaceType, nrInterface.Methods); types.Add(nrInterface, interfaceType); } } /// <summary> /// Adds the submitted delegates to the diagram. /// </summary> /// <param name="delegates">A list of delegates to add.</param> private void AddDelegates(IEnumerable<NRDelegate> delegates) { foreach (NRDelegate nrDelegate in delegates) { DelegateType delegateType = diagram.AddDelegate(); delegateType.Name = nrDelegate.Name; delegateType.AccessModifier = nrDelegate.AccessModifier.ToNClass(); delegateType.ReturnType = nrDelegate.ReturnType.Name; foreach(NRParameter nrParameter in nrDelegate.Parameters) { delegateType.AddParameter(nrParameter.Declaration()); } types.Add(nrDelegate, delegateType); } } /// <summary> /// Adds the submitted enums to the diagram. /// </summary> /// <param name="enums">A list of enums to add.</param> private void AddEnums(IEnumerable<NREnum> enums) { foreach (NREnum nrEnum in enums) { EnumType enumType = diagram.AddEnum(); enumType.Name = nrEnum.Name; enumType.AccessModifier = nrEnum.AccessModifier.ToNClass(); AddEnumValues(enumType, nrEnum.Values); types.Add(nrEnum, enumType); } } #endregion #region --- Member /// <summary> /// Adds the given enum values to the given type. /// </summary> /// <param name="type">The enum to add the enum values to.</param> /// <param name="values">A list of enum values to add.</param> private void AddEnumValues(EnumType type, IEnumerable<NREnumValue> values) { foreach (NREnumValue nrEnumValue in values) { type.AddValue(nrEnumValue.Declaration()); } } /// <summary> /// Adds the given fields to the given type. /// </summary> /// <param name="type">The entity to add the fields to.</param> /// <param name="fields">A list of fields to add.</param> private void AddFields(SingleInharitanceType type, IEnumerable<NRField> fields) { foreach (NRField nrField in fields) { type.AddField().InitFromDeclaration(new NRFieldDeclaration(nrField)); } } /// <summary> /// Adds the given properties to the given type. /// </summary> /// <param name="type">The entity to add the properties to.</param> /// <param name="properties">A list of properties to add.</param> private void AddProperties(CompositeType type, IEnumerable<NRProperty> properties) { foreach (NRProperty nrProperty in properties) { type.AddProperty().InitFromDeclaration(new NRPropertyDeclaration(nrProperty)); } } /// <summary> /// Adds the given methods to the given type. /// </summary> /// <param name="type">The entity to add the methods to.</param> /// <param name="methods">A list of methods to add.</param> private void AddMethods(CompositeType type, IEnumerable<NRMethod> methods) { foreach (NRMethod nrMethod in methods) { type.AddMethod().InitFromDeclaration(new NRMethodDeclaration(nrMethod)); } } /// <summary> /// Adds the given constructors to the given type. /// </summary> /// <param name="type">The entity to add the constructors to.</param> /// <param name="constructors">A list of constructors to add.</param> private void AddConstructors(SingleInharitanceType type, IEnumerable<NRConstructor> constructors) { foreach (NRConstructor nrConstructor in constructors) { type.AddConstructor().InitFromDeclaration(new NRConstructorDeclaration(nrConstructor)); } } /// <summary> /// Adds the given operators to the given type. /// </summary> /// <param name="type">The entity to add the operators to.</param> /// <param name="operators">A list of operators to add.</param> private void AddOperators(SingleInharitanceType type, IEnumerable<NROperator> operators) { foreach (NROperator nrOperator in operators) { type.AddMethod().InitFromDeclaration(new NROperatorDeclaration(nrOperator)); } } /// <summary> /// Adds the given events to the given type. /// </summary> /// <param name="type">The entity to add the events to.</param> /// <param name="events">A list of events to add.</param> private void AddEvents(CompositeType type, IEnumerable<NREvent> events) { foreach (NREvent nrEvent in events) { type.AddEvent().InitFromDeclaration(new NREventDeclaration(nrEvent)); } } #endregion #endregion } }
gpl-3.0
jinsedeyuzhou/NewsClient
app/src/main/java/com/study/newsclient/view/CustomToast.java
1127
package com.study.newsclient.view; import android.content.Context; import android.support.design.widget.BaseTransientBottomBar; import android.view.Gravity; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.study.newsclient.R; /** * 自定义弹出对话框 * @author wyy * */ public class CustomToast extends Toast { private TextView textView; private String text; private View view; private int time; private Context context; public CustomToast(Context context, String text, int time) { super(context); this.context = context; this.text = text; this.time = time; init(); } private void init() { view = View.inflate(context, R.layout.custom_toast, null); setView(view); textView = (TextView) view.findViewById(R.id.textView); textView.setText(text); setGravity(Gravity.CENTER_HORIZONTAL, 0, 0); setDuration(time); } public static CustomToast makeText(Context context, CharSequence text, @BaseTransientBottomBar.Duration int duration) { CustomToast result = new CustomToast(context,text.toString(),duration); return result; } }
gpl-3.0
uhoogma/ounit
ounit-service/src/main/java/com/googlecode/ounit/QuestionDownloadLink.java
2593
package com.googlecode.ounit; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.extensions.protocol.opaque.IVersionedResource; import org.apache.wicket.markup.html.link.ResourceLink; import org.apache.wicket.request.Response; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.resource.IResource; import org.apache.wicket.request.resource.ResourceReference; public class QuestionDownloadLink extends ResourceLink<Void> { private static final long serialVersionUID = 1L; public static class QuestionDownloadResource implements IVersionedResource { private static final long serialVersionUID = 1L; @Override public String getVersionedName() { return OunitSession.get().getDownloadFileName(); } @Override public void respond(Attributes attributes) { File zipFile = OunitSession.get().getDownloadFile(); if (zipFile == null || zipFile.length() <= 0) { return; } Response response = attributes.getResponse(); if (response instanceof WebResponse) { WebResponse webResponse = (WebResponse) response; webResponse.setAttachmentHeader(getVersionedName()); webResponse.setContentType("application/octet-stream"); webResponse.setContentLength(zipFile.length()); } try { byte[] buf = new byte[4096]; FileInputStream fin = new FileInputStream(zipFile); int count = 0; while ((count = fin.read(buf)) != -1) { if (count == buf.length) { response.write(buf); } else { response.write(Arrays.copyOf(buf, count)); } } } catch (IOException e) { throw new WicketRuntimeException(e); } } } public QuestionDownloadLink(String id) { super(id, new ResourceReference(QuestionDownloadLink.class, "download") { private static final long serialVersionUID = 1L; final IResource resource = new QuestionDownloadResource(); @Override public IResource getResource() { return resource; } }); } @Override protected boolean getStatelessHint() { return true; } }
gpl-3.0
avp0038/2017PCTR_L04
src/p012/Ball.java
1525
package p012; import java.awt.Image; import javax.swing.ImageIcon; //TODO Transform the code to be used safely in a concurrent context. public class Ball { private String Ball = "pelota.png"; private double x, y, dx, dy; private double v, fi; private Image image; public Ball() { ImageIcon ii = new ImageIcon(this.getClass().getResource(Ball)); image = ii.getImage(); x = Billiards.Width / 4 - 16; y = Billiards.Height / 2 - 16; v = 5; fi = Math.random() * Math.PI * 2; } public void move() { v = v * Math.exp(-v / 1000); dx = v * Math.cos(fi); dy = v * Math.sin(fi); if (Math.abs(dx) < 1 && Math.abs(dy) < 1) { dx = 0; dy = 0; } x += dx; y += dy; assert x < Board.RIGHTBOARD && x > Board.LEFTBOARD && y > Board.BOTTOMBOARD && y< Board.TOPBOARD; } public void reflect() { double fiaux=fi; if (Math.abs(x + 32 - Board.RIGHTBOARD) < Math.abs(dx)) { fi = Math.PI - fi; } if (Math.abs(y + 32 - Board.BOTTOMBOARD) < Math.abs(dy)) { fi = -fi; } if (Math.abs(x - Board.LEFTBOARD) < Math.abs(dx)) { fi = Math.PI - fi; } if (Math.abs(y - Board.TOPBOARD) < Math.abs(dy)) { fi = -fi; } assert fi!=fiaux; } public int getX() { return (int) x; } public int getY() { return (int) y; } public double getFi() { return fi; } public double getdr() { return Math.sqrt(dx * dx + dy * dy); } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public Image getImage() { return image; } }
gpl-3.0
mahalaxmi123/moodleanalytics
blocks/configurable_reports/components/columns/userstats/form.php
2802
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** Configurable Reports * A Moodle block for creating customizable reports * @package blocks * @author: Juan leyva <http://www.twitter.com/jleyvadelgado> * @date: 2009 */ if (!defined('MOODLE_INTERNAL')) { die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page } require_once($CFG->libdir.'/formslib.php'); class userstats_form extends moodleform { function definition() { global $DB, $USER, $CFG; $mform =& $this->_form; $mform->addElement('header', 'crformheader' ,get_string('userstats','block_configurable_reports'), ''); $userstats = array('logins'=>get_string('statslogins','block_configurable_reports'),'activityview'=>get_string('activityview','block_configurable_reports'),'activitypost'=>get_string('activitypost','block_configurable_reports')); $userstats['coursededicationtime'] = get_string('coursededicationtime','block_configurable_reports'); $mform->addElement('select', 'stat', get_string('stat','block_configurable_reports'), $userstats); $limitoptions = array(); for ($i = 5; $i <= 150; $i+=5) { $limitoptions[$i * 60] = $i; } $mform->addElement('select', 'sessionlimittime', get_string('sessionlimittime', 'block_configurable_reports'), $limitoptions); $mform->addHelpButton('sessionlimittime', 'sessionlimittime', 'block_configurable_reports'); $mform->setDefault('sessionlimittime', 30*60); $mform->disabledIf('sessionlimittime', 'stat', 'neq', 'coursededicationtime'); $this->_customdata['compclass']->add_form_elements($mform,$this); // buttons $this->add_action_buttons(true, get_string('add')); } function validation($data, $files){ global $DB, $CFG; $errors = parent::validation($data, $files); $errors = $this->_customdata['compclass']->validate_form_elements($data,$errors); if($data['stat'] != 'coursededicationtime' && (!isset($CFG->enablestats) || !$CFG->enablestats)) { $errors['stat'] = get_string('globalstatsshouldbeenabled','block_configurable_reports'); } return $errors; } }
gpl-3.0
testing-av/testing-video
generators/src/main/java/band/full/test/video/executor/FxDisplay.java
2727
package band.full.test.video.executor; import static band.full.test.video.encoder.EncoderParameters.HD_MAIN; import static javafx.scene.layout.Priority.ALWAYS; import static javafx.scene.paint.Color.BLACK; import band.full.core.Resolution; import band.full.test.video.encoder.EncoderParameters; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Function; import java.util.function.Supplier; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.ScrollPane; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.VBox; import javafx.scene.paint.Paint; import javafx.stage.Stage; public class FxDisplay extends Application { private static Resolution size; private static Paint fill; private static Supplier<Parent> root; @Override public void start(Stage stage) throws Exception { Parent pane = root.get(); double width = size.width; double height = size.height; VBox box = new VBox(pane); VBox.setVgrow(pane, ALWAYS); box.setMinSize(width, height); box.setPrefSize(width, height); box.setMaxSize(width, height); box.setBackground(new Background(new BackgroundFill(fill, null, null))); var scroll = new ScrollPane(box); var scene = new Scene(scroll); stage.setScene(scene); stage.show(); } public static void show(Function<EncoderParameters, Parent> overlay) { show(HD_MAIN, overlay); } public static void show(EncoderParameters params, Function<EncoderParameters, Parent> overlay) { show(params.resolution, BLACK, () -> overlay.apply(params)); } public static void show(Resolution resolution, Supplier<Parent> overlay) { show(resolution, BLACK, overlay); } public static void show(Resolution resolution, Paint background, Supplier<Parent> overlay) { size = resolution; root = overlay; fill = background; launch(); } public static void runAndWait(Runnable runnable) { var future = new CompletableFuture<>(); Platform.runLater(() -> { try { runnable.run(); } catch (Throwable t) { future.completeExceptionally(t); return; } future.complete(null); }); try { future.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } }
gpl-3.0
lifemapper/core
LmWebServer/services/api/v2/matrix.py
7161
"""This module provides REST services for matrices""" import cherrypy from LmCommon.common.lmconstants import HTTPStatus, JobStatus from LmWebServer.common.lmconstants import HTTPMethod from LmWebServer.services.api.v2.base import LmService from LmWebServer.services.api.v2.matrix_column import MatrixColumnService from LmWebServer.services.common.access_control import check_user_permission from LmWebServer.services.cp_tools.lm_format import lm_formatter # ............................................................................. @cherrypy.expose @cherrypy.popargs('path_matrix_id') class MatrixService(LmService): """This class is reponsible for matrix services. """ column = MatrixColumnService() # ................................ def DELETE(self, path_gridset_id, path_matrix_id): """Attempts to delete a matrix Args: path_matrix_id: The id of the matrix to delete """ mtx = self.scribe.get_matrix(mtx_id=path_matrix_id) if mtx is None: raise cherrypy.HTTPError( HTTPStatus.NOT_FOUND, 'Matrix not found') # If allowed to, delete if check_user_permission(self.get_user_id(), mtx, HTTPMethod.DELETE): success = self.scribe.delete_object(mtx) if success: cherrypy.response.status = HTTPStatus.NO_CONTENT return raise cherrypy.HTTPError( HTTPStatus.INTERNAL_SERVER_ERROR, 'Failed to delete matrix') raise cherrypy.HTTPError( HTTPStatus.FORBIDDEN, 'User does not have permission to delete this matrix') # ................................ @lm_formatter def GET(self, path_gridset_id, path_matrix_id=None, after_time=None, alt_pred_code=None, before_time=None, date_code=None, epsg_code=None, gcm_code=None, keyword=None, limit=100, matrix_type=None, offset=0, url_user=None, status=None, **params): """GET a matrix object, list, or count """ if path_matrix_id is None: return self._list_matrices( self.get_user_id(url_user=url_user), gridset_id=path_gridset_id, after_time=after_time, alt_pred_code=alt_pred_code, before_time=before_time, date_code=date_code, epsg_code=epsg_code, gcm_code=gcm_code, keyword=keyword, limit=limit, matrix_type=matrix_type, offset=offset, status=status) if path_matrix_id.lower() == 'count': return self._count_matrices( self.get_user_id(url_user=url_user), gridset_id=path_gridset_id, after_time=after_time, alt_pred_code=alt_pred_code, before_time=before_time, date_code=date_code, epsg_code=epsg_code, gcm_code=gcm_code, keyword=keyword, matrix_type=matrix_type, status=status) return self._get_matrix(path_gridset_id, path_matrix_id) # ................................ def _count_matrices(self, user_id, gridset_id, after_time=None, alt_pred_code=None, before_time=None, date_code=None, epsg_code=None, gcm_code=None, keyword=None, matrix_type=None, status=None): """Count matrix objects matching the specified criteria Args: user_id: The user to count matrices for. Note that this may not be the same user logged into the system after_time: Return matrices modified after this time (Modified Julian Day) before_time: Return matrices modified before this time (Modified Julian Day) epsg_code: (optional) Return matrices with this EPSG code """ after_status = None before_status = None # Process status parameter if status: if status < JobStatus.COMPLETE: before_status = JobStatus.COMPLETE - 1 elif status == JobStatus.COMPLETE: before_status = JobStatus.COMPLETE + 1 after_status = JobStatus.COMPLETE - 1 else: after_status = status - 1 mtx_count = self.scribe.count_matrices( user_id=user_id, matrix_type=matrix_type, gcm_code=gcm_code, alt_pred_code=alt_pred_code, date_code=date_code, keyword=keyword, gridset_id=gridset_id, after_time=after_time, before_time=before_time, epsg=epsg_code, after_status=after_status, before_status=before_status) return {'count': mtx_count} # ................................ def _get_matrix(self, path_gridset_id, path_matrix_id): """Attempt to get a matrix """ mtx = self.scribe.get_matrix( gridset_id=path_gridset_id, mtx_id=path_matrix_id) if mtx is None: raise cherrypy.HTTPError( HTTPStatus.NOT_FOUND, 'matrix {} was not found'.format(path_matrix_id)) if check_user_permission(self.get_user_id(), mtx, HTTPMethod.GET): return mtx raise cherrypy.HTTPError( HTTPStatus.FORBIDDEN, 'User {} does not have permission to access matrix {}'.format( self.get_user_id(), path_matrix_id)) # ................................ def _list_matrices(self, user_id, gridset_id, after_time=None, alt_pred_code=None, before_time=None, date_code=None, epsg_code=None, gcm_code=None, keyword=None, limit=100, matrix_type=None, offset=0, status=None): """Count matrix objects matching the specified criteria Args: user_id: The user to count matrices for. Note that this may not be the same user logged into the system after_time: Return matrices modified after this time (Modified Julian Day) before_time: Return matrices modified before this time (Modified Julian Day) epsg_code: Return matrices with this EPSG code limit: Return this number of matrices, at most offset: Offset the returned matrices by this number """ after_status = None before_status = None # Process status parameter if status: if status < JobStatus.COMPLETE: before_status = JobStatus.COMPLETE - 1 elif status == JobStatus.COMPLETE: before_status = JobStatus.COMPLETE + 1 after_status = JobStatus.COMPLETE - 1 else: after_status = status - 1 mtx_atoms = self.scribe.list_matrices( offset, limit, user_id=user_id, matrix_type=matrix_type, gcm_code=gcm_code, alt_pred_code=alt_pred_code, date_code=date_code, keyword=keyword, gridset_id=gridset_id, after_time=after_time, before_time=before_time, epsg=epsg_code, after_status=after_status, before_status=before_status) return mtx_atoms
gpl-3.0
Comos/tage
src/Compiler/Node/Expression/Operand/AttributeNode.php
607
<?php /** * User: wangfeng * Date: 15-5-21 * Time: 下午2:14 */ namespace Comos\Tage\Compiler\Node\Expression\Operand; use Comos\Tage\Compiler\Node\AbstractNode; /** * Class AttributeNode * @package Comos\Tage\Compiler\Node\Expression\Operand */ class AttributeNode extends AbstractNode { public function __construct(array $tokens, array $childNodes = []) { parent::__construct($tokens, $childNodes); } public function compile() { return sprintf('$this->getAttribute(%s,%s)',$this->childNodes['left']->compile(),$this->childNodes['right']->compile()); } }
gpl-3.0
bengtmartensson/harctoolboxbundle
src/main/java/org/harctoolbox/irscrutinizer/exporter/WaveExporter.java
3720
/* Copyright (C) 2013, 2014 Bengt Martensson. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ package org.harctoolbox.irscrutinizer.exporter; import java.io.File; import java.io.FileNotFoundException; import org.harctoolbox.girr.Command; import org.harctoolbox.guicomponents.AudioParametersBean; import org.harctoolbox.harchardware.ir.Wave; import org.harctoolbox.ircore.IrCoreException; import org.harctoolbox.ircore.ModulatedIrSequence; import org.harctoolbox.irp.IrpException; /** * This class does something interesting and useful. Or not... */ public class WaveExporter extends CommandExporter implements ICommandExporter { private int sampleFrequency; private int sampleSize; private int channels; private boolean bigEndian; private boolean omitTail; private boolean square; private boolean divideCarrier; public WaveExporter( int sampleFrequency, int sampleSize, int channels, boolean bigEndian, boolean omitTail, boolean square, boolean divideCarrier) { super(); this.sampleFrequency = sampleFrequency; this.sampleSize = sampleSize; this.channels = channels; this.bigEndian = bigEndian; this.omitTail = omitTail; this.square = square; this.divideCarrier = divideCarrier; } public WaveExporter(AudioParametersBean exportAudioParametersBean) { this(exportAudioParametersBean.getSampleFrequency(), exportAudioParametersBean.getSampleSize(), exportAudioParametersBean.getChannels(), exportAudioParametersBean.getBigEndian(), exportAudioParametersBean.getOmitTrailingGap(), exportAudioParametersBean.getSquare(), exportAudioParametersBean.getDivideCarrier()); } @Override public String[][] getFileExtensions() { return new String[][]{ new String[] { "Wave files (*.wav *.wave)", "wav", "wave" } }; } @Override public String getFormatName() { return "Wave"; } @Override public String getPreferredFileExtension() { return "wav"; } public void export(Command command, String source, String title, int repeatCount, File exportFile) throws FileNotFoundException, IrpException, IrCoreException { export(command, source, title, repeatCount, exportFile, null); } @Override public void export(Command command, String source /* ignored */, String title /* ignored */, int repeatCount, File exportFile, String charsetName /* ignored */) throws FileNotFoundException, IrpException, IrCoreException { ModulatedIrSequence seq = command.toIrSignal().toModulatedIrSequence(repeatCount); Wave wave = new Wave(seq, sampleFrequency, sampleSize, channels, bigEndian, omitTail, square, divideCarrier); wave.export(exportFile); } @Override public boolean considersRepetitions() { return true; } }
gpl-3.0
NoBrainer/ScrollRole
scrollRoleConfig.js
52
module.exports = { env: 'dev', port: 3000 };
gpl-3.0
felixtheratruns/CampusTrees-server
pages/viewTree.php
2550
<!-- This file is part of server-side of the CampusTrees Project. It is subject to the license terms in the LICENSE file found in the top-level directory of this distribution. No part of CampusTrees Project, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the LICENSE file.--> <?php $treeid = $_GET['treeId']; require_once("/var/www/config.inc.php"); require_once(ROOT_DIR . 'classes/tree.inc.php'); require_once(ROOT_DIR . 'classes/SpeciesTable.inc.php'); if (empty($treeid) || !isset($treeid) || $treeid<1) { ?> <div class="post"> <h2 class="title"><a href="#">Unknown Tree</a></h2> <div class="entry"> <p>You did not select a valid tree. Please go back, and try again.</p> </div> </div> <div style="clear: both;">&nbsp;</div> <?php } else { $tree = new tree($treeid); $info = $tree->getProperties(); $sTable = new SpeciesTable(); $species = $sTable->GetSpecies(); ?> <div class="post"> <h2 class="title"><a href="#">Tree Information</a></h2> <div class="entry"> <?php /*<img src="images/unknowntree.gif" style="float: left;">*/ ?> <h3>Basic Information</h3> <p>Species: <a href="index.php?p=viewSpecies&amp;specId=<?php echo $info['sid']; ?>"><?php foreach ($species as $s) { if ($s['sid'] == $info['sid']) { echo $s['commonname']; break; } } ?></a><br /> Age: <?php echo $info['age']; ?><br /> Location: <?php echo $info['lat']; ?>, <?php echo $info['long']; ?></p> <h3>Tree Measurements</h3> <p>Height: <?php echo $info['height']; ?> ft<br /> Volume: <?php echo $info['vol']; ?><br /> Dry Weight: <?php echo $info['drywt']; ?> lbs<br /> Green Weight: <?php echo $info['greenwt']; ?> lbs</p> <h3>Environmental Information</h3> <p>Weight of CO<sub>2</sub>/year: <?php echo $info['co2pyear']; ?> lbs<br /> Weight of CO<sub>2</sub> in life: <?php echo $info['co2seqwt']; ?> lbs<br /> Weight of Carbon: <?php echo $info['carbonwt']; ?> lbs</p> </div> </div> <div style="clear: both;">&nbsp;</div> <?php } ?>
gpl-3.0
Jenyay/outwikerdroid
app/src/main/java/net/jenyay/outwikerdroid/core/config/BaseIniOption.java
268
package net.jenyay.outwikerdroid.core.config; /** * Created by jenyay on 11.08.15. * Base class for single record in IniConfig. */ public class BaseIniOption { IniConfig _config; public BaseIniOption (IniConfig config) { _config = config; } }
gpl-3.0
useaquestion/andach-gamerental
resources/views/admin/productindex.blade.php
886
@extends('template') @section('content') @include('admin.menu') {!! Form::open(['route' => 'admin.gameindexpost', 'method' => 'POST']) !!} <h2>Admin Game Index</h2> <div class="row"> <div class="col-12"> <a href="{{ route('admin.productcreate') }}">Click here to create a product.</a> </div> </div> <div class="row"> <div class="col-3">Image</div> <div class="col-4">Product</div> <div class="col-3">Price</div> <div class="col-2">Last Updated</div> </div> @foreach ($products as $product) <div class="row"> <div class="col-3"> {!! $product->thumb_img !!} </div> <div class="col-4"> <a href="{{ route('admin.productedit', $product->id) }}">{{ $product->name }}</a> </div> <div class="col-3"> {{ $product->price_format }} </div> <div class="col-2"> {{ $product->updated_at }} </div> </div> @endforeach @endsection
gpl-3.0
vuchannguyen/web
lib/pear/PHP/CodeSniffer/CommentParser/ParserException.php
2014
<?php /** * An exception to be thrown when a DocCommentParser finds an anomilty in a * doc comment. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <[email protected]> * @author Marc McIntyre <[email protected]> * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence * @version CVS: $Id: ParserException.php,v 1.1 2009/05/19 15:22:44 nicolasconnault Exp $ * @link http://pear.php.net/package/PHP_CodeSniffer */ /** * An exception to be thrown when a DocCommentParser finds an anomilty in a * doc comment. * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <[email protected]> * @author Marc McIntyre <[email protected]> * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence * @version Release: 1.1.0 * @link http://pear.php.net/package/PHP_CodeSniffer */ class PHP_CodeSniffer_CommentParser_ParserException extends Exception { /** * The line where the exception occured, in relation to the doc comment. * * @var int */ private $_line = 0; /** * Constructs a DocCommentParserException. * * @param string $message The message of the exception. * @param int $line The position in comment where the error occured. * A position of 0 indicates that the error occured * at the opening line of the doc comment. */ public function __construct($message, $line) { parent::__construct($message); $this->_line = $line; }//end __construct() /** * Returns the line number within the comment where the exception occured. * * @return int */ public function getLineWithinComment() { return $this->_line; }//end getLineWithinComment() }//end class ?>
gpl-3.0
cityofasheville/quickmap
js/index.js
6505
$('#search').click(function() { if ( $('#txtSearch').val()){ addressStr = $('#txtSearch').val(); var urlStr = 'http://'+QuickMap.agsServerGeocode+'/'+QuickMap.agsServerInstanceNameGeocode+'/rest/services/'+QuickMap.geocdingLayerName+'/GeocodeServer/findAddressCandidates'; var data={f:"json",Street:addressStr}; $.ajax({ url: urlStr, dataType: "jsonp", data: data, success: function (data) { if (data.candidates) { item = data.candidates[0]; QuickMap.getLatLong({ label: item.address, value: item.address, x:item.location.x,y:item.location.y } ); } } }); } }); $('#txtSearch').autocomplete({ source: function (request, response) { //This is for geocoding addressStr = $('#txtSearch').val(); var urlStr = 'http://'+QuickMap.agsServerGeocode+'/'+QuickMap.agsServerInstanceNameGeocode+'/rest/services/'+QuickMap.geocdingLayerName+'/GeocodeServer/findAddressCandidates'; var data={f:"json",Street:addressStr}; $.ajax({ url: urlStr, dataType: "jsonp", data: data, success: function (data) { if (data.candidates) { response($.map(data.candidates.slice(0, 14), function (item) {//only display first 10 return { label: item.address, value: item.address, x:item.location.x,y:item.location.y } })); } } }); }, minLength: 5, select: function (event, ui) { this.blur(); QuickMap.getLatLong(ui.item); } }); var mapAttr = 'Map data from The City of Asheville , NC', mapUrl = 'http://gis.ashevillenc.gov/tiles/basemapbw/{z}/{x}/{y}.png'; var basemapclr = L.tileLayer( mapUrl, { maxZoom: 19, minZoom: 11, tms: true, opacity:.25, attribution:mapAttr, }); var basemapsld = L.tileLayer( mapUrl, { maxZoom: 19, minZoom: 11, tms: true, attribution:mapAttr, }); var parcel= L.tileLayer( 'http://gis.ashevillenc.gov/tiles/bcparcels/{z}/{x}/{y}.png', { maxZoom: 19, minZoom: 16, tms: true, attribution:mapAttr, }); var zoning= L.tileLayer( 'http://gis.ashevillenc.gov/tiles/coazoning/{z}/{x}/{y}.png', { maxZoom: 19, minZoom: 15, tms: true, attribution:mapAttr, }); var img2010 = L.tileLayer.wms("http://services.nconemap.com/arcgis/services/Imagery/Orthoimagery_Latest/ImageServer/WMSServer?", { layers: 'Orthoimagery_Latest', format: 'image/png', transparent: true, attribution: "Imagery from - North Carolina Center for Geographic Information and Analysis" }) var map = new L.Map( 'map', { fullscreenControl: true, layers: [basemapsld,parcel,zoning] }).setView([35.593,-82.5488], 14) map.on('fullscreenchange', function () { if (map.isFullscreen()) { console.log('entered fullscreen'); } else { console.log('exited fullscreen'); } }); var bmimg = L.layerGroup([img2010,basemapclr]) var baseLayers = { "Street Map": basemapsld, "Imagery":img2010, "Street Map And Imagery":bmimg, }; var overlayLayers = { "City of Asheville zoning": zoning, "BC Parcels": parcel, } layersControl = new L.control.layers(baseLayers,overlayLayers,{collapsed: false}); layersControl.addTo(map); map.on('enterFullscreen', function(){ if(window.console) window.console.log('enterFullscreen'); }); map.on('exitFullscreen', function(){ if(window.console) window.console.log('exitFullscreen'); }); map.removeLayer(zoning); map.removeLayer(parcel); layersControl._update(); map.addEventListener('click', onMapClick); popup = new L.Popup({ maxWidth: 400, zoomAnimation:true, closeOnClick:true, }); QuickMap.identifyConfig={ "service":"bc_parcels", "tolerance":3, layers:[{ "layerindex":0, "layerlabel":"Parcels", fields:[{ "id":0, "name":"pinnum", "style":"key", "label":"PIN" }, { "id":1, "name":"owner", "style":"text", "label":"Owner" }, { "id":2, "name":"acreage", "style":"text", "label":"Acreage" }, { "id":3, "name":"taxvalue", "style":"currency", "label":"Tax Value" }, { "id":4, "name":"buildingvalue", "style":"currency", "label":"Building Value" }, { "id":5, "name":"propcard", "style":"url", "label":"Property Card" }, { "id":6, "name":"platurl", "style":"url", "label":"Plat" }, { "id":7, "name":"deedurl", "style":"url", "label":"Deed" }], }, { "layerindex":1, "layerlabel":"Zoning", fields:[{ "id":0, "name":"districts", "style":"key", //key,text,url,num "label":"Zonning District" }, { "id":1, "name":"Acreage", "style":"text", //key,text,url,num "label":"Acreage" }], }], }; function onMapClick(e) { QuickMap.getStateplane(e); } function DoTheCheck() { if (document.checkform.getfeatureinfo.checked == true) {map.addEventListener('click', onMapClick);} if (document.checkform.getfeatureinfo.checked == false) {map.removeEventListener('click', onMapClick); map.closePopup(popup);} }
gpl-3.0
cascheberg/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/jobs/RemoteDeleteSendJob.java
9815
package org.thoughtcrime.securesms.jobs; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.WorkerThread; import com.annimon.stream.Stream; import org.signal.core.util.logging.Log; import org.thoughtcrime.securesms.crypto.UnidentifiedAccessUtil; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.database.MessageDatabase; import org.thoughtcrime.securesms.database.NoSuchMessageException; import org.thoughtcrime.securesms.database.model.MessageRecord; import org.thoughtcrime.securesms.dependencies.ApplicationDependencies; import org.thoughtcrime.securesms.jobmanager.Data; import org.thoughtcrime.securesms.jobmanager.Job; import org.thoughtcrime.securesms.net.NotPushRegisteredException; import org.thoughtcrime.securesms.messages.GroupSendUtil; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.RecipientId; import org.thoughtcrime.securesms.recipients.RecipientUtil; import org.thoughtcrime.securesms.transport.RetryLaterException; import org.thoughtcrime.securesms.util.GroupUtil; import org.whispersystems.libsignal.util.guava.Optional; import org.whispersystems.signalservice.api.SignalServiceMessageSender; import org.whispersystems.signalservice.api.crypto.ContentHint; import org.whispersystems.signalservice.api.crypto.UnidentifiedAccessPair; import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException; import org.whispersystems.signalservice.api.messages.SendMessageResult; import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage; import org.whispersystems.signalservice.api.push.SignalServiceAddress; import org.whispersystems.signalservice.api.push.exceptions.ServerRejectedException; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; public class RemoteDeleteSendJob extends BaseJob { public static final String KEY = "RemoteDeleteSendJob"; private static final String TAG = Log.tag(RemoteDeleteSendJob.class); private static final String KEY_MESSAGE_ID = "message_id"; private static final String KEY_IS_MMS = "is_mms"; private static final String KEY_RECIPIENTS = "recipients"; private static final String KEY_INITIAL_RECIPIENT_COUNT = "initial_recipient_count"; private final long messageId; private final boolean isMms; private final List<RecipientId> recipients; private final int initialRecipientCount; @WorkerThread public static @NonNull RemoteDeleteSendJob create(@NonNull Context context, long messageId, boolean isMms) throws NoSuchMessageException { MessageRecord message = isMms ? DatabaseFactory.getMmsDatabase(context).getMessageRecord(messageId) : DatabaseFactory.getSmsDatabase(context).getSmsMessage(messageId); Recipient conversationRecipient = DatabaseFactory.getThreadDatabase(context).getRecipientForThreadId(message.getThreadId()); if (conversationRecipient == null) { throw new AssertionError("We have a message, but couldn't find the thread!"); } List<RecipientId> recipients = conversationRecipient.isGroup() ? Stream.of(RecipientUtil.getEligibleForSending(conversationRecipient.getParticipants())).map(Recipient::getId).toList() : Stream.of(conversationRecipient.getId()).toList(); recipients.remove(Recipient.self().getId()); return new RemoteDeleteSendJob(messageId, isMms, recipients, recipients.size(), new Parameters.Builder() .setQueue(conversationRecipient.getId().toQueueKey()) .setLifespan(TimeUnit.DAYS.toMillis(1)) .setMaxAttempts(Parameters.UNLIMITED) .build()); } private RemoteDeleteSendJob(long messageId, boolean isMms, @NonNull List<RecipientId> recipients, int initialRecipientCount, @NonNull Parameters parameters) { super(parameters); this.messageId = messageId; this.isMms = isMms; this.recipients = recipients; this.initialRecipientCount = initialRecipientCount; } @Override public @NonNull Data serialize() { return new Data.Builder().putLong(KEY_MESSAGE_ID, messageId) .putBoolean(KEY_IS_MMS, isMms) .putString(KEY_RECIPIENTS, RecipientId.toSerializedList(recipients)) .putInt(KEY_INITIAL_RECIPIENT_COUNT, initialRecipientCount) .build(); } @Override public @NonNull String getFactoryKey() { return KEY; } @Override protected void onRun() throws Exception { if (!Recipient.self().isRegistered()) { throw new NotPushRegisteredException(); } MessageDatabase db; MessageRecord message; if (isMms) { db = DatabaseFactory.getMmsDatabase(context); message = DatabaseFactory.getMmsDatabase(context).getMessageRecord(messageId); } else { db = DatabaseFactory.getSmsDatabase(context); message = DatabaseFactory.getSmsDatabase(context).getSmsMessage(messageId); } long targetSentTimestamp = message.getDateSent(); Recipient conversationRecipient = DatabaseFactory.getThreadDatabase(context).getRecipientForThreadId(message.getThreadId()); if (conversationRecipient == null) { throw new AssertionError("We have a message, but couldn't find the thread!"); } if (!message.isOutgoing()) { throw new IllegalStateException("Cannot delete a message that isn't yours!"); } List<Recipient> destinations = Stream.of(recipients).map(Recipient::resolved).toList(); List<Recipient> completions = deliver(conversationRecipient, destinations, targetSentTimestamp); for (Recipient completion : completions) { recipients.remove(completion.getId()); } Log.i(TAG, "Completed now: " + completions.size() + ", Remaining: " + recipients.size()); if (recipients.isEmpty()) { db.markAsSent(messageId, true); } else { Log.w(TAG, "Still need to send to " + recipients.size() + " recipients. Retrying."); throw new RetryLaterException(); } } @Override protected boolean onShouldRetry(@NonNull Exception e) { if (e instanceof ServerRejectedException) return false; if (e instanceof NotPushRegisteredException) return false; return e instanceof IOException || e instanceof RetryLaterException; } @Override public void onFailure() { Log.w(TAG, "Failed to send remote delete to all recipients! (" + (initialRecipientCount - recipients.size() + "/" + initialRecipientCount + ")") ); } private @NonNull List<Recipient> deliver(@NonNull Recipient conversationRecipient, @NonNull List<Recipient> destinations, long targetSentTimestamp) throws IOException, UntrustedIdentityException { SignalServiceDataMessage.Builder dataMessageBuilder = SignalServiceDataMessage.newBuilder() .withTimestamp(System.currentTimeMillis()) .withRemoteDelete(new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp)); if (conversationRecipient.isGroup()) { GroupUtil.setDataMessageGroupContext(context, dataMessageBuilder, conversationRecipient.requireGroupId().requirePush()); } SignalServiceDataMessage dataMessage = dataMessageBuilder.build(); List<SendMessageResult> results; if (conversationRecipient.isPushV2Group()) { results = GroupSendUtil.sendResendableDataMessage(context, conversationRecipient.requireGroupId().requireV2(), destinations, false, ContentHint.RESENDABLE, messageId, isMms, dataMessage); } else { SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender(); List<SignalServiceAddress> addresses = RecipientUtil.toSignalServiceAddressesFromResolved(context, destinations); List<Optional<UnidentifiedAccessPair>> unidentifiedAccess = UnidentifiedAccessUtil.getAccessFor(context, destinations); results = messageSender.sendDataMessage(addresses, unidentifiedAccess, false, ContentHint.RESENDABLE, dataMessage); DatabaseFactory.getMessageLogDatabase(context).insertIfPossible(dataMessage.getTimestamp(), destinations, results, ContentHint.RESENDABLE, messageId, isMms); } return GroupSendJobHelper.getCompletedSends(context, results); } public static class Factory implements Job.Factory<RemoteDeleteSendJob> { @Override public @NonNull RemoteDeleteSendJob create(@NonNull Parameters parameters, @NonNull Data data) { long messageId = data.getLong(KEY_MESSAGE_ID); boolean isMms = data.getBoolean(KEY_IS_MMS); List<RecipientId> recipients = RecipientId.fromSerializedList(data.getString(KEY_RECIPIENTS)); int initialRecipientCount = data.getInt(KEY_INITIAL_RECIPIENT_COUNT); return new RemoteDeleteSendJob(messageId, isMms, recipients, initialRecipientCount, parameters); } } }
gpl-3.0
maaku/p2pool
p2pool/bitcoin/networks.py
25415
import os import platform from twisted.internet import defer from . import data from p2pool.util import math, pack nets = dict( bitcoin=math.Object( P2P_PREFIX='f9beb4d9'.decode('hex'), P2P_PORT=8333, ADDRESS_VERSION=0, RPC_PORT=8332, RPC_CHECK=defer.inlineCallbacks(lambda bitcoind: defer.returnValue( 'bitcoinaddress' in (yield bitcoind.rpc_help()) and not (yield bitcoind.rpc_getinfo())['testnet'] )), SUBSIDY_FUNC=lambda height: 50*100000000 >> (height + 1)//210000, TITHE_FUNC=lambda height: (), POW_FUNC=data.hash256, BLOCK_PERIOD=600, # s SYMBOL='BTC', CONF_FILE_FUNC=lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'Bitcoin') if platform.system() == 'Windows' else os.path.expanduser('~/Library/Application Support/Bitcoin/') if platform.system() == 'Darwin' else os.path.expanduser('~/.bitcoin'), 'bitcoin.conf'), BLOCK_EXPLORER_URL_PREFIX='http://blockexplorer.com/block/', ADDRESS_EXPLORER_URL_PREFIX='http://blockexplorer.com/address/', SANE_TARGET_RANGE=(2**256//2**32//1000 - 1, 2**256//2**32 - 1), ), bitcoin_testnet=math.Object( P2P_PREFIX='0b110907'.decode('hex'), P2P_PORT=18333, ADDRESS_VERSION=111, RPC_PORT=18332, RPC_CHECK=defer.inlineCallbacks(lambda bitcoind: defer.returnValue( 'bitcoinaddress' in (yield bitcoind.rpc_help()) and (yield bitcoind.rpc_getinfo())['testnet'] )), SUBSIDY_FUNC=lambda height: 50*100000000 >> (height + 1)//210000, TITHE_FUNC=lambda height: (), POW_FUNC=data.hash256, BLOCK_PERIOD=600, # s SYMBOL='tBTC', CONF_FILE_FUNC=lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'Bitcoin') if platform.system() == 'Windows' else os.path.expanduser('~/Library/Application Support/Bitcoin/') if platform.system() == 'Darwin' else os.path.expanduser('~/.bitcoin'), 'bitcoin.conf'), BLOCK_EXPLORER_URL_PREFIX='http://blockexplorer.com/testnet/block/', ADDRESS_EXPLORER_URL_PREFIX='http://blockexplorer.com/testnet/address/', SANE_TARGET_RANGE=(2**256//2**32//1000 - 1, 2**256//2**32 - 1), ), namecoin=math.Object( P2P_PREFIX='f9beb4fe'.decode('hex'), P2P_PORT=8334, ADDRESS_VERSION=52, RPC_PORT=8332, RPC_CHECK=defer.inlineCallbacks(lambda bitcoind: defer.returnValue( 'namecoinaddress' in (yield bitcoind.rpc_help()) and not (yield bitcoind.rpc_getinfo())['testnet'] )), SUBSIDY_FUNC=lambda height: 50*100000000 >> (height + 1)//210000, TITHE_FUNC=lambda height: (), POW_FUNC=data.hash256, BLOCK_PERIOD=600, # s SYMBOL='NMC', CONF_FILE_FUNC=lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'Namecoin') if platform.system() == 'Windows' else os.path.expanduser('~/Library/Application Support/Namecoin/') if platform.system() == 'Darwin' else os.path.expanduser('~/.namecoin'), 'bitcoin.conf'), BLOCK_EXPLORER_URL_PREFIX='http://explorer.dot-bit.org/b/', ADDRESS_EXPLORER_URL_PREFIX='http://explorer.dot-bit.org/a/', SANE_TARGET_RANGE=(2**256//2**32 - 1, 2**256//2**32 - 1), ), namecoin_testnet=math.Object( P2P_PREFIX='fabfb5fe'.decode('hex'), P2P_PORT=18334, ADDRESS_VERSION=111, RPC_PORT=8332, RPC_CHECK=defer.inlineCallbacks(lambda bitcoind: defer.returnValue( 'namecoinaddress' in (yield bitcoind.rpc_help()) and (yield bitcoind.rpc_getinfo())['testnet'] )), SUBSIDY_FUNC=lambda height: 50*100000000 >> (height + 1)//210000, TITHE_FUNC=lambda height: (), POW_FUNC=data.hash256, BLOCK_PERIOD=600, # s SYMBOL='tNMC', CONF_FILE_FUNC=lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'Namecoin') if platform.system() == 'Windows' else os.path.expanduser('~/Library/Application Support/Namecoin/') if platform.system() == 'Darwin' else os.path.expanduser('~/.namecoin'), 'bitcoin.conf'), BLOCK_EXPLORER_URL_PREFIX='http://testnet.explorer.dot-bit.org/b/', ADDRESS_EXPLORER_URL_PREFIX='http://testnet.explorer.dot-bit.org/a/', SANE_TARGET_RANGE=(2**256//2**32 - 1, 2**256//2**32 - 1), ), freicoin_rc1=math.Object( P2P_PREFIX='5c9ffaaf'.decode('hex'), P2P_PORT=8639, ADDRESS_VERSION=0, RPC_PORT=8638, RPC_CHECK=defer.inlineCallbacks(lambda bitcoind: defer.returnValue( 'freicoinaddress' in (yield bitcoind.rpc_help()) and not (yield bitcoind.rpc_getinfo())['testnet'] )), SUBSIDY_FUNC=lambda height: int(mpq((161280-height) * 15916928405, 161280) + mpq(9999999999999999, 1048576)) if height < 161280 else 9536743164, TITHE_FUNC=lambda height: () if height >= 161280 else [({ 0: '1DCyWRmTXB9goqA4Zb88nU1Q8snA7d7n4x', 1: '1LoFvV5YJsSMkpyPLizqyWH8KAkevV2XwJ', 2: '1JTUD2rB3FvbNFPw7cvCdTVDM9nuZTw7Jk', 3: '18w4xQQj2iXwtq9smYkEAJrWVz4jQNU4xd', 4: '16vdGLyxdYgSCT9xAng9Js7KrsnrUHsyG2', 5: '1Lo8mmskrLnvCuthadVaRS4K7WUSFpWAwj', 6: '1J1irQQ3ZWoTPct989Nnzdtu6WjfCjQcWs', 7: '1MME2u4V2ZiU6uUVJXTZMg5sQXAyMBUNXt', 8: '1CT3kUDi3rvma8R7Jwbz7puATSU3xzfLHz', 9: '1CLupi58K9XHVeWZ8jwbWiY4Ns46mPALbe', 10: '16A8XoWWvtJrDE1AdYQoLxAQcoLQML9gjz', 11: '1NwgZoUnudfmbQ99xDRdvrYskgjQ7KBt1Z', 12: '17CDPam7M59JM6vK5xzh1vUGKjYT9Byi5S', 13: '1PyKZKfquWcu3PFzKbvmKZ2oJWXbmbsWdB', 14: '186LbdeaDsn4Y5zrLN9cfSHWpQPSHtLbgC', 15: '1MrQWWNKfVseYyGkyyLsDhFekJWGJNt2i9', 16: '1EAUtv6YfvcRUrU5SncdZ27aSJ6SBNJH67', 17: '1DuSbRKB1GL9cBeJLYsuh3DADdwJgvHAQN', 18: '1MPdcnGXHsjR6rFSBUMm4ui44q8Ra1fYRT', 19: '1Ntv6bDFj8eQnXjawcatnJjJTowo1BA8rF', 20: '14j9vnqn6FZwPZmwdvGSuESm1m3oQsHP5y', 21: '1C679HkKyki9rN8tJvtMNyXGLedPdo8zbb', 22: '1EMKZYHTcnpHVUJx4dUp5Jne2ePQKjpdTm', 23: '1PmgFAV835znVpUwGkLkvJrKc4ZzBqixNX', 24: '16zKbgjQDqua6xjrXLhCbPGFrpr8UJxf4x', 25: '1KPurbuUH5D6HRe3Y148kUbRjDyFCCm3VH', 26: '1GVyWAXxP9tgZbj8iDSQqQ5tcN36uJ3F1s', 27: '1E5udyBXuBt1e8c2R27AvSTdp8H7LEhmxr', 28: '1hQcLTTD7KiFxiojvSrrrj8Y1w2gF5bHE', 29: '17BJ1oZdZJS64curVAL6rN1yYN7YiNVXpR', 30: '1LotiV7qGfAZhVV36XtrixnEfHCiuqe39e', 31: '1Q5yedqC3adLpNjbY4CWMxPojoxnSCVGjw', 32: '1FpBGhBWn7WDZr9nP47qG3DktJbaY7P48P', 33: '1H6Nh8dRPZjMm3KViuW5ZESjRwqYnQ36nt', 34: '1NAAKtpk7VRRUtA5ja8YxCZQaisXQ28HqA', 35: '1JKxed9uYfvcPgjGdo1GQXwMQJkAnap34G', 36: '1DZ58aSGD13QfUa118rtvfKrJiVPAoxdV8', 37: '12wnNuaQHbLyThJVJvfePhV8UwQEWURLLP', 38: '16f8S6f6ZDX3N1JG2DL5kyz9KCzmwpGgt7', 39: '1PPKwAUZ6g5wWiopfyJKJZn3xUFcrJbSBF', 40: '18DzCPRpU1Y2o5FsuuvcScZaYSi2ZBTVFr', 41: '1E5fy7csgbN5G9ENRwvSwGSAibLdLk52pe', 42: '1Dapd3WLAz1jm91FpNThHamXeMjDU4TJgJ', 43: '15HQuReQzSQ1mrHWy3iYELyJLjGNe9gNEZ', 44: '1DcJhNQJLkDrSmrvATciEaf95ZvnhFFUF7', 45: '1ErNVYRnGQpzFmxkXYnqR4LbcCViby7Rfi', 46: '1D1CmGn3BCM5rviTxZEfc7NhozAetePkit', 47: '1Af3dbEWMK5VuMkUozepYPQgMeVtmKtvW9', 48: '1JY2W5m4jsYzY2YYXU6RRKDmobE3BYEbgA', 49: '1PdTBBm2xhCoUY4A6cfYCopaFDsFyTf4MY', 50: '1Fe51wUzrhyGmag9UXmzEsr6jSyWqcATAM', 51: '1kyb1A5jWYP49YTkoN2y3JFQuNp1S2gXa', 52: '1FxZ7fmDQmauMASYVuVcHeajGZQKrQ1UWB', 53: '1EwtDpNLPmUZNLFmGMmNTwviUVe3DuTFKt', 54: '1NYRPya8KWUfiSr8fXxccPoDMmBw2Uqj1y', 55: '16vQMSBZK7iy5HDFfeiP2WomfpGfSEPJx5', 56: '12E9bCLYb9uzh2MHhpsyR89V3eLXZp5afr', 57: '1EA4NJjMXSgVNsNgEc7nSyRf3epjp3ABrQ', 58: '1NN442B74LAsXUMUFZSriWZCUh8b5ECFR9', 59: '1EMaEQmjjDCjgu3auEam5ABQ1J9ZtdLdpV', 60: '1RYXoGz2cHTGsYC5zZdDwpCdGRj4aBdAX', 61: '19aDWt7kBf53uLANiWnLFnWo5CqASh79mi', 62: '1LDEniSxXknXLHT1BMWpFsBM3PQcgn1nYz', 63: '1Q4Lji94eWCC9xBzwrbRE9yTMYS5fdKg9z', 64: '16fQVYur5CVMq9VfNLYypKXNeTmvWnDKsz', 65: '1Mc3r8pCpuRiHhkD3DrWf89CUnZb6xbFbg', 66: '18oEnf5iR9CD2HFDc9Yr8kD7m5CrJVWRkv', 67: '12VDq99L8UQWr8Waqo4GreEGCEBnkxMaXy', 68: '1H7PxhMmvqiRT8NDEkSFjfDekRLQ65CqBN', 69: '17yC59RcpYsw7jX3Zw7c48AcWtJqaHUwAr', 70: '1AFT16ksWdqdjhk56gFDaRnr7vS4XCVtyQ', 71: '1G84MZVqN54QTD47YWWmimy9htaj1WC58U', 72: '13YcisL6YyUG5nqegyqyrL6pVtrMqGYtcq', 73: '1NYdmagVHfbqTgW4hYJKS2YnWrJzCnSsvZ', 74: '1PumqgHPLUjPKfddgwJA46D5GBdYgT8myg', 75: '1PFKxU6g1kQayDwvpiLX2vJgUghMqJz9Ck', 76: '154ENKy3HuYoN8xARVaxp61NUAt5GEknDj', 77: '12CJ8BD8L8tQXjrpy4UfjJwCCtoL6vsegD', 78: '1LXCWYJ6k7EG2Bi8rLh2jhV94L4G768yTa', 79: '1K1rbcUFmE7XScTsqiNEiJHyX69eqbZdDB', 80: '1uZZzXiu8n7eL96rcFWh9MvcqerYxaGce', 81: '1JidqtE1YHwXFC1utxPAp17RkM3rUqwULk', 82: '1PuMwPqNLLYi1sPxvJToid2EsfiP4xPfo6', 83: '14ZSJRvSdgYFA1xUM2txnQKdMXMfsEWvuJ', 84: '1D9RJw7p5zgz4JeWvVzYxBsAkvucRMiXfG', 85: '1JRpRLZgcfNNeVEwGQmYZw5nv7Aq3KVx5x', 86: '17Rqyx39YnpFN23dPE3CWRPC8JhuBVKktx', 87: '19pozj4JeWd6rpMDeTpx8d1Dv4rebhUkvT', 88: '15jULtTPTzXHr9ezTMFbaPJojbuYFrbrQp', 89: '19dfCSTERPh5j4XtYoJatjdjD9afReeY3s', 90: '1LgzNc1Sfbu8BaxKUESGbNzCNnpqvhpCi4', 91: '1HTvoZUUNncPkjjv17xHLEtncdrgcdnN46', 92: '1NHvSZWwk8RtgPvfhzykpvebQnVk1Q5XxX', 93: '1AzdeDfjz5C5yT6wVxurgS8QPkZviHvY8N', 94: '1BdFwnfS84uDeZn4sojUs5ZC8fSkx9o2XG', 95: '1AgCAgvQZPQTkdMg853SkM2WdRzN4Q2ATw', 96: '1JABYERsgkAYincsgCpic7MwV63iM19iXp', 97: '1JFudqZDUkBMdV4ShLmhxLD7sfNEYdBQCE', 98: '1Pqf48Skyxt77RNVwTLxUhA2BNCscaHJKa', 99: '1AtdTwFFYZJrUUSWbBLBCkodRcnqwb1a6G', 100: '14iezrH1nR9TjGtnywFPqBHbwYcEhwz8y9', 101: '16x2aavFb2AHKntUnzA3HC2wmi921YJn4i', 102: '1HovjtiToM6f2xV3Sxg4fxfvSYPCGGEXLe', 103: '1MNrqZyo7poywLPVap6PsmmT5CS4f8hyWq', 104: '1F6PzQRW2MPfCYvzgeUXoBXaEikH3E5zMk', 105: '1F2SpgUakBvx6aNgJiCtEZHnTqVWeQcoMk', 106: '13iTRwxSLGC17fzumSrRidaXe8v8awdDux', 107: '1KuyBiZBdXVq8oNGAPWEqWiFi2RyH8rvwd', 108: '1HdXmhHKkkzpn1UKmhBWFzQMYsUqxUuVZ9', 109: '1Dw9jXoWc5MsEH3uLB9pi98qeyijUrvWU3', 110: '15mW5WsusPo6LAAYLqa6ngFfQ1jX51v3Bn', 111: '1DFfarcjskvSi2w56msV4JeeVZqtuwEL9p', 112: '12SeGWd2txi4fdQKoFXsTdd2fgjDbABWyb', 113: '1MoENmjtakS8XTHcwsbVFeJkjEckMhS3xm', 114: '167pv4Hn53XQ4hFhyNtEyP36n8HrL3NU3j', 115: '1E6WgpC4bmYJagvsTzhRxZ1Z8sRSsQjmJX', 116: '1EFkVCzezsZCq56JWSBRf3Dy6tafFRxh4N', 117: '1KnKZwDb44Qf3Lutda2T85uFZiTZwe2v2C', 118: '1CLpF2fLukzBHard43mXLEXxz11gFK5dc9', 119: '1DXSfPi1Tj6tQ5qf5M6Yj6cpNmLfPKMwr1', 120: '16nHP74UsqeHewM1yUhNCL3zCjkWnqFt8g', 121: '1FeqXkG9jGEDcPaKJV8rdh4NbqTjbdvN4a', 122: '1LwwjmsoDtQ1Zh9N8doGMczP1TJnes2YoZ', 123: '1DgusdNgB6nRD2emfwURMmk33LrB7Wp95c', 124: '17kjPofVVmhZAWXnrVwfqizGtXWBufWwbf', 125: '1EnLHA3U15wXehXAC24W587EEaeyUcaA6K', 126: '1MwpkFtEwrAQNbsmbt4kB9WtoB8mFLXZ44', 127: '12iQRcVoRCbFNvoQARM3rufTkd7jXpHZEm', 128: '19zK2WFDkaHZfWa4uS5mzF2XD1KrZEMxy2', 129: '12Zs8LtRY1cTS3HKw1gwPzYjB1Ar6Er93R', 130: '1KDVcQhjZuX39Fvv8QbrSpaSycMA4YdPkU', 131: '1AT6rxNBT8sasYKrKm9fv7LdjXBS89Wewh', 132: '19YjbLEUgqV8joQMgijDWZoY1inwXf1hXc', 133: '1EpHQ43BkzmKYMiYwmRRKEXQidpgA499px', 134: '13bQP93mmUFtUGVuBEwZ9ymdbCC9yywgdL', 135: '1GatPyGkCX5YUW4f2QHJk1PzwspCRz9b3J', 136: '1Jk8sCUfHVE6VpwkkTG9qaYYS9u1zMmQAs', 137: '13N4Eiv2KiX4PeFwiWnC847JBv4TP2sn1Z', 138: '1ESzED9saJ3bVB6BbVSTFGDxRLnTgWRVDC', 139: '1CspvzG7HyuNXRLsaWnpsLXPDwkeDKd4mm', 140: '14Rs4fo9tK39kyEFoAjbvkcgGZ6k356t3T', 141: '1D6jgPJYoFhbY7gJjNMAbyfJzBGVtqSc1o', 142: '16MHoaVyYQgPU525fz2auJpK6JVyFKEiz1', 143: '1FfS9TQswYZHYDNkUmncRAYjYJkLzGncp5', 144: '14PXPSEjNjWAuqYa63RBT6gewnomE9saRu', 145: '1CHBBtBCRQz1TFyE12g8RbGPZ6UzX2AieC', 146: '1CMwT1jzfoe9VvURpZanaXVQobMQLr13W8', 147: '1696KNrMvHvnthPLZnGuYGY96UbEqLeXz6', 148: '1A7TQi9sMiNQX8uwwqFb8eqaXnpTJY4WYg', 149: '1GNuX6AN2KCF1AWtxAT9QYD6QRJubRvKaz', 150: '16L3CvHeZcZcr3wPhoEC3ZsMLN7YTonMTQ', 151: '1EnqRdqx1VZyfc5ia4pcmZstBcGdW8FGxn', 152: '1MQ1QeCMZhxFCgReGEPRS2Qy74FaPqFccW', 153: '16Za6Rn8dCmM8gctXQtwN1yQ2WXnhHsSgs', 154: '15k38dy86CRnirMY9Q1niVmfn7nfXTmppL', 155: '1MQsruCXBjCZzTZKKpPwcC74ztetbtAw4E', 156: '1cmAt63c4ZAqRe2fBQTYs5Jyx41fiBbhQ', 157: '1PBCaowV7gQM6Lj1NfSpH2TnHHmqXcYTsC', 158: '1841uXFc2kUTUogCDJwp4U1NPjSPqsg69x', 159: '1XNo9kDMM6uqvf9yCWmqj17rukC8abjtb', 160: '1A4kHAe6rNz1q8G6dYjNMyWzgVv4DxYget', 161: '18Y6y6zcJrG5j2RjmGqsUvtWkZhnTvRka7', 162: '1DkcMkHWUUVjXgAu2MFXVkUuwZ6JWv64cz', 163: '1JvXTyBxhjE9mERWEFnqeuAPgbJSi25qGd', 164: '1FHus2MsM8k4oKHt22YFYeoFkf65kxQFP3', 165: '18HLkAhrzeNsaMB3MY1xUGW7wkzjWGobT7', 166: '1AF7KmTRrS3mMxop2Viop1MctrNJmPAHQt', 167: '13g4rWjU2PK4eN9D9XXo4jRB84RiJ2hD7o', 168: '1EWUiUoxZXfTbZXDZGueag7XRnv5Mej8ZZ', 169: '1LuuGk4tyd4USQqtYypemjt5vs3VRqV1QU', 170: '15eUUDUYDuiKnt9xNbzhNFmorCK9F9mJb2', 171: '1HGzWgdrNAKsE9nE1GHtUvaXHNzvwTyPQX', 172: '11MhmCVmFszm6yTTwaK2dypwcLaybmCjp', 173: '1s9XWpGPQqhbog1S6xgGqcVnfvnLMAueZ', 174: '16f3tHcuRavx3tSWCM2jnnCX5jGa2vJe9Q', 175: '15NWaghRx51ravYTUqsnBF2hQFQeSHtTvS', 176: '1QGUUgikmqCinDQn3vfqx9q6mnT5ekA4BG', 177: '134WvpvyZUveYc98CmtWZc1oBBXdrV1GuU', 178: '1LqNfcDBn7eytc7Ln6fLrCDLkYeMa6R9dV', 179: '14xbponjm6rXp8cNzTJmtCJwvwvDuKvaCD', 180: '14D7JyUrv1HeSD7FCc8WupmbxUiGyfC7uC', 181: '1ER6GhDJokhBjB73DWDTdC2BP2J9DiqD1o', 182: '13Q3or3Hew7hBZzMoriz8LcMXwptqD5HEd', 183: '1HSyeVQEvdRwj2rutFN33cKu2tPzyGkgx2', 184: '1A1WaQQ6ZjXuEe2KYZNC3ycPg4X9czsR4D', 185: '1fhzxkMPY4hUYNywoQwyVGkinVKQrPJ2P', 186: '1Nf63BqwEmb7vU15bRfpvKEs5tMGZpR5Fi', 187: '1Gi6tjnRBecQovhRQVNmsPyVZYmphZerdg', 188: '1AJ87nhgSQkac9BUjEvbyWh8c95ciHLZWG', 189: '1WDyJLrJaLRePMtea6bAgADwzdpbW5nqd', 190: '1JTvhcJuxydevXw4ocUUteiPNWwPtMM56H', 191: '16X1LYmpxM2fPBjNTLbnPo2LdA6sB7fbNu', 192: '1315ZWhxgd6pqqTmvF21fxt5wzYvpcnZSm', 193: '17PWpyrUmkaCVPu6KXaWvuLLYvD9YU61RP', 194: '1PADxQpcx8Kvs3PprjYvM1wYFyjxB3tcs8', 195: '1BWyJmxybx3p1guhud8qxabrGbVLWaVNaM', 196: '17JpmLSEbXgmheAvTQ7iiBvR5TaSsM2Xgt', 197: '19oxMuyyipVsvxXWKBBrFmY8hQbWkiiVEv', 198: '16TvroBFWJmUN7VSHQLmyh6KiCri5QVTQu', 199: '1MXJR6XRoThY9rwvyvLkXWN17WN7rAQC4J', 200: '163N8CmDAf45CM6brXMpzg3AN2nkDXTuRt', 201: '1CWudCKLCxT5AXteLFeZRBDyb4moQH4cVL', 202: '1DYmgt2zpW2eNfyczC98aq76URHQMnfwZK', 203: '1JnE2YseXgBX4oHGo8VywsxnNkp52s6nkX', 204: '1D8WBBBCHhgLrMa8s3QU1bkRcRHEt8cNfv', 205: '1Fm5eoDvEZo4hyW4YEDu3q2gKbpCuo9hqw', 206: '18uRTixnVaKMz9tyoR6Ve6Rqdwtt8oZ1Zw', 207: '1FuByKdd2RK3hjc3UFeV56HvheyAMnjMMS', 208: '17nDqatJ7M6M9vFRa4BngCCLPGSJ6mfc8b', 209: '1G4qHkiaaVZwuLqwvh2itFjR18iThkeaDQ', 210: '18ZcHUg5wV4sSdd9pS7xv5rYsfx5D1hZWi', 211: '1CZU6UCZjtWueXQWYzyrFa4K7pTSeBQ8cw', 212: '19zRVJvXaXZvygqbHAP1ZKF5Rx9gq3Xh8u', 213: '1HQAyw9UUi2eiQHJcnbg5eeJTnv2QoEQqA', 214: '16eZAqdqypn47T8DwS1archd39uXqK8JQ8', 215: '19he5Hy915MbSZBvwHjB3LAm5UyLnmQ5TK', 216: '1CzGcY5JKDroUtdFdZJArGeEmKMEtyeAKw', 217: '1DzowkZrtEQgoDF8xgxjPBfLaBMeBHjNr2', 218: '16GA6zc9iTUB8o47oi7fbE88ayEi8C7w2r', 219: '1Mvp5TikHrzJetDMbjHkzAkP9rMBfQrais', 220: '1Lrbk1vrmCqVfajBqtwHD1x9x72jeDCon5', 221: '1AMDHRKUah3J8yESFt7NnoUXrM4ULHcUpN', 222: '1MbnTTv5FJX8RsK5tw9KjNx1VCvo94GEKK', 223: '1Hmbm1TUDuDwdVWkU1oiaReRRBTzb8fMDJ', 224: '15XYapuYSjaDc4uDXJsf3PF33YzSRs5P3M', 225: '1C3ovhhZwo73isNQPuKKD5VDm2XwByBkTK', 226: '16VJrBFjFjhLY93NihDvWqBpUeiXeL2FUi', 227: '1C9Niuy1cSW6a6g5tm8GhPsSML6ZtWeUQS', 228: '149937wZtsTvtwmixD33npnsnyUm5zjstX', 229: '1NkCKjPZUFecVWxLGnJbN7Fp8viJRG5Xg4', 230: '1MG3okwhF3YDwVWDcYsNr5ySA4eMtCATrK', 231: '1GtzbwNuHYBZaDRVpJGuDwjBQhSh5RBVRZ', 232: '1CJi6dja55AtGeuJX6WLFGTHsoofqZyDNu', 233: '1oftVXkjfpJSMKGnz1pps1xVWNUNNhAmq', 234: '168KgGGUEEx22eCNuSMjsKvn5chiZ5c217', 235: '1FmQzGLJFu3AvucwDEAjYRM4fPgiSZsT6Q', 236: '1F9t4EmWXy2Wui21LaMuZmRDwRCF38aDZN', 237: '19eFuss1dgxPdDfoAu6AsVmBUj5d2DUPu3', 238: '15Yr2PPbFGqbi2SZtZ59cvd5y2Es8atRE5', 239: '1Pz8oisCda5aJXtVVDo1mfxxvgymVNcmsM', 240: '1HkHQHNkjXp6VinoEG6a1i55NmreXC9yAX', 241: '12ShPmbsADZMacnr5u2DPxssKXjd3HaCZc', 242: '1BasQDDfZ677LF3mEAQUEFHvJexZ8ZxY47', 243: '1FVXTVaK3rwSrx67WGdNkNFwL5sVm81TEK', 244: '1NV8VjVBrkgCTJvyBHZumboXjPtSNZvRJX', 245: '1HVdN1BSusJZ42sSfJFHB2CJ6LcW5Fz31a', 246: '12j2yfUP2dNo3HwdrTDjMGZhzBcdhYvFj6', 247: '1BrWHBKCpvNYssq8Kj8yY6qvy7GqFgk8UP', 248: '1G3faUnBxMHwwX2uLn6dZJEj9pmJ2o5cnq', 249: '1Nq59Py1u73B26aTTRhZG3g9h5fmrmkeX9', 250: '1DMuz7B193myzVq4Kgg76Jb6Da2UjkAti', 251: '1124BMmAevhic3H1MQB3teQFhoVi7RVUhR', 252: '1B1hrgcDNfSuaKJi3oJ4cBtyysq2BpGFz8', 253: '18NE1w2soK6xGUYYvoTe7oEtRtQhxBLXCq', 254: '1MESy7CY2yTgxSERyejcvCGjK8Qm2EhE4g', 255: '1445Hs1Lgh9pPvD8mSt5oiGwTY8yT2sy9R', 256: '14pm2Fxwin4mwHqd5ujXAXTJJFuQ31qYUf', 257: '17UhQpeFQ3nCjj8PJKCrTWHnP8YSvrNM7h', 258: '15zVu5t8iURV2feuvmnHgYp9u7cxPC4XrN', 259: '19JriYALeNskNnvjYidpoNHNLegftkViqH', 260: '13mauBB6JYTPcfoWbNbCWKk4sNqmwxCXse', 261: '1LwRt9rpGaekbht7UAitg2ADmFtDrKThYV', 262: '15Z9wnxM6VxrRkqhLZpLskGRJ2dLRMEmCg', 263: '1GvQwfMSMRggmmFCRqf1EmvaG5U5sY4sKL', 264: '13iUoiiVq7C4fUmy94r1HEDf35YKwBAVXh', 265: '1ELZsnzgBmZSSxQQYuAANg8izDFTbzhbPB', 266: '13me2Z71XAtmkzggnqusdvuRiXZzFRGZBj', 267: '1KC7ECvdcofiYXJ63iUnvFrEH4zzhQZ2pB', 268: '1LtFLa3oaEBhmHQ5iXRvFqeNcrzU8GPNMM', 269: '1LNHH8DGXWQRyfmkSkaJcBkkiVxUhH8tBM', 270: '1Daw5kGzsqBhfRfMV6dAA4bgBZ2LBWS1nY', 271: '164XLENwRiappRPUP47sRTSyXtW8CAXVLi', 272: '1CFoTaknkFGADVo2rK92jwq18NWBzVcJGS', 273: '1MnrNuPrnuJFxYnkpKDqUymHGjb1d6qLVq', 274: '1BpwPwf8kUssmoMCoWnHCVY4wjBJi3CZyD', 275: '1jiJb2DU3DB6ujD8eV3DZXmnfwWaHti4y', 276: '1DqQnvWdtKvwBtePpCbDd8juZ9ZbeaKFdH', 277: '131D32PNpqqGtLGUaAaZePqpUdBTiy8Akh', 278: '16jK6KaY7Ub7fZ7YaBi94ZsygovzixnRNx', 279: '1EJx1ShX4UJVrzynP3oZw8wdLpSGC1KPrz', 280: '1899kFmma5FongtN9JfvFKqhwtbw2w9MDe', 281: '1FNNBK9SeDUufbbnmoagUFt7oKVbb65vaw', 282: '1LxF4pLjeSpNs4ux24MDduzCzrM2KCsE7M', 283: '1BZjVRe2CCA7G7qnG3beWWhG173f1mbNX2', 284: '1L5HWs7WrK457CzjAgnHghveFpQVv7rRTe', 285: '1Kp4bjG9nwbogd8WM62ijGG6onW9Wo4aYK', 286: '1hhvJ4QmB6RX12Bps9xhnMHCDDXTXAnDu', 287: '19xiuTYSm85gNsPZw8hGLS69e2DjVbCuAP', 288: '19WdcJU8Z1W3ZZnbpfDRbdrYGapxp1L5zo', 289: '121hT7w8DN3x1pYEowak7FjmNgihMNo2cd', 290: '1BtthjPb9GPKwgcJtrgZRQRWhiRSCHmyvk', 291: '1JKgRTkMgEodFFpPwoz9W6pejMN3x3J9X1', 292: '18zp4dHdouYqFn2qC4ttAva8cwqhZ4pm4K', 293: '1ELAVZKvGykuzRDCvFUsJTL4istYisbxpK', 294: '1PfULZdJniM8SutFdjoKvG3WLUwxZL2YUf', 295: '1DTbnuz4dPLdduseE3k5xr62eFAYjCSk3E', 296: '14jVGdWJRcqpdgWPAbbvhMfVnLha6MdnYU', 297: '1GBiMVjsqkcGxij2hGFQxVUX2WjDcr1Esf', 298: '1FGUuAuGRkSqEL8Besg33QsekxmBB75ZUH', 299: '19FsZeejdbfUKK21wENRdoR2BUowD4FsMZ', 300: '1LbBHWffmANdhcb1Wciv4jWwXPGrtVFhsU', 301: '1FT9PRuDmFKxZorYrfgibWaaBdKWv7PiB4', 302: '1FUvPJ3nXMUrFEWqkjxPe5esqQ2GoCmUAk', 303: '1LJLBDK8q7yLibK2oYTA6hbD9UpmP6U3QP', 304: '14E9GEg9T5N9aja1FV2ewNFjMK6wPEgsKb', 305: '1JYmABbYkUjAyowLwa1zoQj86PEWMBdeZP', 306: '1NCfTbrEsZrCT3Efyk5AfvqP2xY6NesWHy', 307: '1Bwd6rcgGLq8sdo3FHHSmh3J7ufqdgMeqi', 308: '1PzAWHEt2xabgWEki5hTgwtTyuKRS1at39', 309: '1Fo3r7DWDtJ8Yu2UqngNqKMSw98XgsXehW', 310: '1H1b6FLd5eqH8Q9Cw8UkZv2nY3xxKTfsH3', 311: '12x9TqiF9FQU7sqnRiCmrRZmG7dLs9hyG6', 312: '13VYYQ8K9AFiajev9QdHM6Kj8SqevRT7GS', 313: '149HFz2K7D4GffQm8t7rKQuWmcwJohsimk', 314: '1JqwkYTg3ZuWMpjhxrJYgW7E826HYoiBSG', 315: '1NiyjCKxM33nozwzU2LNtWBPWrWTUpiaAM', 316: '1LD4F5tA87e7nMwNRuHhgwH6zTFZ1LyoE2', 317: '1M3wUX9YYrcVSSw6Tncdoic3Fj13okQ63u', 318: '1PVKsqeVqM4B2ccq915GHeK3aDeruStr24', 319: '1PKNQqSuPknZ1PaqKkRqa9qYujWKL9KQ7E', }[(height*320)//161280], 49603174604)], POW_FUNC=data.hash256, BLOCK_PERIOD=600, # s SYMBOL='FRC', CONF_FILE_FUNC=lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'Freicoin') if platform.system() == 'Windows' else os.path.expanduser('~/Library/Application Support/Freicoin/') if platform.system() == 'Darwin' else os.path.expanduser('~/.freicoin'), 'freicoin.conf'), BLOCK_EXPLORER_URL_PREFIX='http://freicoin.com/block/', ADDRESS_EXPLORER_URL_PREFIX='http://freicoin.com/address/', SANE_TARGET_RANGE=(2**256//2**32 - 1, 2**256//2**32 - 1), ), litecoin=math.Object( P2P_PREFIX='fbc0b6db'.decode('hex'), P2P_PORT=9333, ADDRESS_VERSION=48, RPC_PORT=9332, RPC_CHECK=defer.inlineCallbacks(lambda bitcoind: defer.returnValue( 'litecoinaddress' in (yield bitcoind.rpc_help()) and not (yield bitcoind.rpc_getinfo())['testnet'] )), SUBSIDY_FUNC=lambda height: 50*100000000 >> (height + 1)//840000, TITHE_FUNC=lambda height: (), POW_FUNC=lambda data: pack.IntType(256).unpack(__import__('ltc_scrypt').getPoWHash(data)), BLOCK_PERIOD=150, # s SYMBOL='LTC', CONF_FILE_FUNC=lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'Litecoin') if platform.system() == 'Windows' else os.path.expanduser('~/Library/Application Support/Litecoin/') if platform.system() == 'Darwin' else os.path.expanduser('~/.litecoin'), 'litecoin.conf'), BLOCK_EXPLORER_URL_PREFIX='http://explorer.litecoin.net/block/', ADDRESS_EXPLORER_URL_PREFIX='http://explorer.litecoin.net/address/', SANE_TARGET_RANGE=(2**256//1000000000 - 1, 2**256//1000 - 1), ), litecoin_testnet=math.Object( P2P_PREFIX='fcc1b7dc'.decode('hex'), P2P_PORT=19333, ADDRESS_VERSION=111, RPC_PORT=19332, RPC_CHECK=defer.inlineCallbacks(lambda bitcoind: defer.returnValue( 'litecoinaddress' in (yield bitcoind.rpc_help()) and (yield bitcoind.rpc_getinfo())['testnet'] )), SUBSIDY_FUNC=lambda height: 50*100000000 >> (height + 1)//840000, TITHE_FUNC=lambda height: (), POW_FUNC=lambda data: pack.IntType(256).unpack(__import__('ltc_scrypt').getPoWHash(data)), BLOCK_PERIOD=150, # s SYMBOL='tLTC', CONF_FILE_FUNC=lambda: os.path.join(os.path.join(os.environ['APPDATA'], 'Litecoin') if platform.system() == 'Windows' else os.path.expanduser('~/Library/Application Support/Litecoin/') if platform.system() == 'Darwin' else os.path.expanduser('~/.litecoin'), 'litecoin.conf'), BLOCK_EXPLORER_URL_PREFIX='http://nonexistent-litecoin-testnet-explorer/block/', ADDRESS_EXPLORER_URL_PREFIX='http://nonexistent-litecoin-testnet-explorer/address/', SANE_TARGET_RANGE=(2**256//1000000000 - 1, 2**256 - 1), ), ) for net_name, net in nets.iteritems(): net.NAME = net_name
gpl-3.0
devbridge/BetterCMS
Modules/BetterCms.Module.MediaManager/Scripts/bcms.media.upload.js
28902
/*jslint unparam: true, white: true, browser: true, devel: true */ // -------------------------------------------------------------------------------------------------------------------- // <copyright file="bcms.media.upload.js" company="Devbridge Group LLC"> // // Copyright (C) 2015,2016 Devbridge Group LLC // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> // // <summary> // Better CMS is a publishing focused and developer friendly .NET open source CMS. // // Website: https://www.bettercms.com // GitHub: https://github.com/devbridge/bettercms // Email: [email protected] // </summary> // -------------------------------------------------------------------------------------------------------------------- bettercms.define('bcms.media.upload', ['bcms.jquery', 'bcms', 'bcms.dynamicContent', 'bcms.modal', 'bcms.html5Upload', 'bcms.ko.extenders', 'bcms.messages', 'bcms.security'], function ($, bcms, dynamicContent, modal, html5Upload, ko, messages, security) { 'use strict'; var mediaUpload = {}, selectors = { dragZone: '#bcms-files-drop-zone', messageBox: "#bcms-multi-file-upload-messages", fileUploadingContext: '#bcms-media-uploads', fileUploadingMasterForm: '#SaveForm', fileUploadingForm: '#ImgForm', fileUploadingTarget: '#UploadTarget', fileUploadingInput: '#uploadFile', fileUploadingResult: '#jsonResult', folderDropDown: '#folderSelectionBox', uploadButtonLabel: '.bcms-btn-upload-files-text', userAccessControlContainer: '#bcms-accesscontrol-context', overrideSelect: "bcms-media-reupload-override" }, classes = { dragZoneActive: 'bcms-file-drop-zone-active' }, links = { loadUploadFilesDialogUrl: null, uploadFileToServerUrl: null, undoFileUploadUrl: null, loadUploadSingleFileDialogUrl: null, checkUploadedFileStatuses: null }, globalization = { uploadFilesDialogTitle: null, failedToProcessFile: null, multipleFilesWarningMessageOnReupload: null }, constants = { defaultReuploadMediaId: '00000000-0000-0000-0000-000000000000' }, fileApiSupported = html5Upload.fileApiSupported(); /** * Assign objects to module. */ mediaUpload.links = links; mediaUpload.globalization = globalization; mediaUpload.openUploadFilesDialog = function (rootFolderId, rootFolderType, onSaveCallback, reuploadMediaId, onCloseCallback) { reuploadMediaId = reuploadMediaId || constants.defaultReuploadMediaId; var options = { uploads: new UploadsViewModel(), rootFolderId: rootFolderId, rootFolderType: rootFolderType, reuploadMediaId: reuploadMediaId }; options.uploads.filesToAccept(rootFolderType == 1 ? 'image/*' : ''); if (fileApiSupported) { modal.open({ title: globalization.uploadFilesDialogTitle, onLoad: function (dialog) { var url = $.format(links.loadUploadFilesDialogUrl, rootFolderId, rootFolderType, reuploadMediaId); dynamicContent.bindDialog(dialog, url, { contentAvailable: function (dialogRef, content) { initUploadFilesDialogEvents(dialog, options); var context = dialog.container.find(selectors.userAccessControlContainer).get(0); if (context) { var viewModel = { accessControl: security.createUserAccessViewModel(content.Data.UserAccessList) }; ko.applyBindings(viewModel, context); } }, beforePost: function () { dialog.container.showLoading(); }, postSuccess: function (json) { options.uploads.stopStatusChecking(); options.uploads.removeFailedUploads(); if (onSaveCallback && $.isFunction(onSaveCallback)) { onSaveCallback(json); } }, postComplete: function() { dialog.container.hideLoading(); }, postError: function () { options.uploads.filesToAccept(rootFolderType == 1 ? 'image/*' : ''); } }); }, onCloseClick: function () { options.uploads.removeAllUploads(); options.uploads.stopStatusChecking(); if (onCloseCallback && $.isFunction(onCloseCallback)) { onCloseCallback(); } }, onAcceptClick: function() { // IE10 fix: remove accept tag from upload box. options.uploads.filesToAccept(''); } }); } else { modal.open({ title: globalization.uploadFilesDialogTitle, onLoad: function(dialog) { var url = $.format(links.loadUploadSingleFileDialogUrl, rootFolderId, rootFolderType, reuploadMediaId); dynamicContent.setContentFromUrl(dialog, url, { done: function (content) { options.uploads.accessControl = security.createUserAccessViewModel(content.Data.UserAccessList); SingleFileUpload(dialog, options); } }); }, onAcceptClick: function(dialog) { var formToSubmit = $(selectors.fileUploadingMasterForm), onComplete = function (json) { messages.refreshBox(dialog.container.find(selectors.messageBox), json); if (json.Success) { try { if (onSaveCallback && $.isFunction(onSaveCallback)) { onSaveCallback(json); } } finally { options.uploads.stopStatusChecking(); options.uploads.removeFailedUploads(); dialog.close(); } } }; $.ajax({ type: 'POST', cache: false, url: formToSubmit.attr('action'), data: formToSubmit.serialize() }) .done(function(response) { onComplete(response); }) .fail(function(response) { onComplete(bcms.parseFailedResponse(response)); }); return false; }, onCloseClick: function () { options.uploads.removeAllUploads(); options.uploads.stopStatusChecking(); if (onCloseCallback && $.isFunction(onCloseCallback)) { onCloseCallback(); } } }); } }; mediaUpload.openReuploadFilesDialog = function (mediaId, rootFolderId, rootFolderType, onSaveCallback, onCloseCallback) { mediaUpload.openUploadFilesDialog(rootFolderId, rootFolderType, onSaveCallback, mediaId, onCloseCallback); }; function SingleFileUpload(dialog, options) { var context = dialog.container.find(selectors.fileUploadingContext).get(0), messageBox = messages.box({ container: dialog.container }), uploadsModel = options.uploads, fakeData = { fileName: "Uploading", fileSize: 0, fileId: null, version: null, type: null, abort: function() { /* File upload canceling is not supported. */ } }, uploadFile = new FileViewModel(fakeData), resetUploadForm = function() { var folderDropDown = dialog.container.find(selectors.folderDropDown); if (folderDropDown.length > 0) { var selectedFolderIndex = dialog.container.find(selectors.folderDropDown).get(0).selectedIndex; dialog.container.find(selectors.fileUploadingForm).get(0).reset(); dialog.container.find(selectors.folderDropDown).get(0).selectedIndex = selectedFolderIndex; } }, uploadAnimationId, animateUpload = function (fileModel) { uploadAnimationId = setInterval(function() { if (fileModel.uploadProgress() >= 100) { fileModel.uploadProgress(0); } else { fileModel.uploadProgress(fileModel.uploadProgress() + 20); }; }, 200); }, stopUploadAnimation = function () { if (uploadAnimationId) { clearInterval(uploadAnimationId); } }; dialog.container.find(selectors.uploadButtonLabel).on('click', fixUploadButtonForMozilla); // On folder changed dialog.container.find(selectors.fileUploadingForm).find(selectors.folderDropDown).on('change', function () { var value = $(this).val(), hidden = dialog.container.find(selectors.fileUploadingMasterForm).find(selectors.folderDropDown); hidden.val(value); }); // On file selected. dialog.container.find(selectors.fileUploadingInput).change(function () { var fileName = dialog.container.find(selectors.fileUploadingInput).val(); if (fileName != null && fileName != "") { // Do not allow multiple file upload on re-upload functionality. if (options.reuploadMediaId && options.reuploadMediaId != constants.defaultReuploadMediaId && uploadsModel.uploads().length > 0) { messageBox.clearMessages(); messageBox.addWarningMessage(globalization.multipleFilesWarningMessageOnReupload); var uploadedFiles = uploadsModel.uploads(); for (var i = 0; i < uploadedFiles.length; i++) { uploadedFiles[i].activate(); } return; } // Add fake file model for upload indication. uploadFile.uploadCompleted(false); uploadFile.fileName = fileName; uploadFile.file.fileName = fileName; uploadFile.uploadProgress(0); uploadsModel.activeUploads.push(uploadFile); uploadsModel.uploads.push(uploadFile); animateUpload(uploadFile); // Send file to server. dialog.container.find($(selectors.fileUploadingForm)).submit(); } }); // On file submitted. dialog.container.find($(selectors.fileUploadingTarget)).on('load', function () { stopUploadAnimation(); uploadsModel.uploads.remove(uploadFile); uploadsModel.activeUploads.remove(uploadFile); resetUploadForm(); // Check the result. var result = $(selectors.fileUploadingTarget).contents().find(selectors.fileUploadingResult).get(0); if (result == null) { return; } var newImg = $.parseJSON(result.innerHTML); if (newImg.Success == false) { var failModel = new FileViewModel(uploadFile.file); failModel.uploadFailed(true); failModel.failureMessage(''); if (newImg.Messages) { var failureMessages = ''; for (var i = 0; i < newImg.Messages.length; i++) { failureMessages += newImg.Messages[i] + ' '; } failModel.failureMessage(failureMessages); } uploadsModel.uploads.push(failModel); return; } // Add uploaded file model. var fileModel = new FileViewModel(newImg); fileModel.uploadCompleted(true); fileModel.fileId(newImg.Id); fileModel.version(newImg.Version); fileModel.type(newImg.Type); fileModel.uploadProgress(100); if (newImg.IsFailed) { fileModel.uploadFailed(true); fileModel.failureMessage(globalization.failedToProcessFile); } else if (newImg.IsProcessing) { fileModel.uploadProcessing(true); uploadsModel.startStatusChecking(uploadsModel.firstTimeout); } uploadsModel.uploads.push(fileModel); uploadsModel.activeUploads.remove(fileModel); }); ko.applyBindings(uploadsModel, context); } function UploadsViewModel() { var self = this, undoUpload = function (fileViewModel) { $.post($.format(links.undoFileUploadUrl, fileViewModel.fileId(), fileViewModel.version(), fileViewModel.type())); }, abortUpload = function (fileViewModel) { self.uploads.remove(fileViewModel); if (self.activeUploads.indexOf(fileViewModel) !== -1) { self.activeUploads.remove(fileViewModel); } if (fileViewModel.uploadCompleted() === false && fileViewModel.uploadFailed() === false) { fileViewModel.file.abort(); } else if (fileViewModel.uploadCompleted() === true) { undoUpload(fileViewModel); } }; self.uploads = ko.observableArray(); self.activeUploads = ko.observableArray(); self.filesToAccept = ko.observable(''); self.cancelAllActiveUploads = function () { var uploads = self.activeUploads.removeAll(); for (var i = 0; i < uploads.length; i++) { abortUpload(uploads[i]); } }; self.removeUpload = function (fileViewModel) { abortUpload(fileViewModel); }; self.removeAllUploads = function() { var uploads = self.uploads.removeAll(); for (var i = 0; i < uploads.length; i++) { abortUpload(uploads[i]); } }; self.removeFailedUploads = function () { for (var i = 0; i < self.uploads().length; i++) { if (self.uploads()[i].uploadFailed()) { abortUpload(self.uploads()[i]); } } }; // When one of file status is "Processing", checking file status repeatedly self.timeout = 5000; self.firstTimeout = 1000; self.timer = null; self.startStatusChecking = function (timeout) { if (!self.timer) { if (!timeout) { timeout = self.timeout; } self.timer = setTimeout(self.checkStatus, timeout); } }; self.stopStatusChecking = function () { if (self.timer) { clearTimeout(self.timer); self.timer = null; } }; self.checkStatus = function () { var ids = self.getProcessingIds(), onFail = function() { bcms.logger.error('Failed to check uploaded files statuses'); self.startStatusChecking(); }, hasProcessing = false; self.timer = null; if (ids.length > 0) { $.ajax({ type: 'POST', cache: false, url: links.checkUploadedFileStatuses, data: JSON.stringify({ ids: ids }), contentType: 'application/json; charset=utf-8' }) .done(function (response) { if (response.Success) { if (response.Data && response.Data.length > 0) { for (var i = 0; i < response.Data.length; i++) { var item = response.Data[i], id = item.Id, isProcessing = item.IsProcessing === true, isFailed = item.IsFailed === true; if (id) { for (var j = 0; j < self.uploads().length; j ++) { if (self.uploads()[j].fileId() == id) { if (isFailed) { self.uploads()[j].uploadFailed(true); self.uploads()[j].uploadProcessing(false); self.uploads()[j].failureMessage(globalization.failedToProcessFile); } else if (!isProcessing) { self.uploads()[j].uploadProcessing(false); } else if (isProcessing) { hasProcessing = true; } } } } } } if (hasProcessing) { self.startStatusChecking(); } } else { onFail(); } }) .fail(function (response) { onFail(); }); } }; self.getProcessingIds = function() { var ids = [], i; for (i = 0; i < self.uploads().length; i++) { if (self.uploads()[i].uploadProcessing()) { ids.push(self.uploads()[i].fileId()); } } return ids; }; } function FileViewModel(file) { var self = this; self.file = file; self.fileId = ko.observable(''); self.version = ko.observable(0); self.type = ko.observable(0); self.uploadProgress = ko.observable(0); self.uploadCompleted = ko.observable(false); self.uploadFailed = ko.observable(false); self.uploadProcessing = ko.observable(false); self.failureMessage = ko.observable(""); self.uploadSpeedFormatted = ko.observable(); self.fileName = file.fileName; self.fileSizeFormated = formatFileSize(file.fileSize); self.isProgressVisible = ko.observable(true); self.isActive = ko.observable(false); self.uploadCompleted.subscribe(function (newValue) { if (newValue === true) { self.uploadProgress(100); } }); self.activate = function() { self.isActive(true); setTimeout(function() { self.isActive(false); }, 4000); }; } function initUploadFilesDialogEvents(dialog, options) { var uploadsModel = options.uploads, dragZone = dialog.container.find(selectors.dragZone), messageBox = messages.box({ container: dialog.container }), cancelEvent = function (e) { e.preventDefault(); e.stopPropagation(); }; dragZone.on("dragenter dragover", function (e) { cancelEvent(e); dragZone.addClass(classes.dragZoneActive); dragZone.children().hide(); return false; }); dragZone.on("dragleave drop", function (e) { cancelEvent(e); dragZone.removeClass(classes.dragZoneActive); dragZone.children().show(); return false; }); dialog.container.find(selectors.uploadButtonLabel).on('click', fixUploadButtonForMozilla); dialog.container.find(selectors.folderDropDown).select2({ minimumResultsForSearch: -1 }); if (fileApiSupported) { var context = document.getElementById('bcms-media-uploads'); html5Upload.initialize({ uploadUrl: links.uploadFileToServerUrl, dropContainer: document.getElementById('bcms-files-drop-zone'), inputField: document.getElementById('bcms-files-upload-input'), key: 'File', data: { rootFolderId: options.rootFolderId, rootFolderType: options.rootFolderType, reuploadMediaId: options.reuploadMediaId }, maxSimultaneousUploads: 4, onFileAdded: function (file) { var overrideSelect = document.getElementById(selectors.overrideSelect); if (overrideSelect) { this.data['shouldOverride'] = overrideSelect.options[overrideSelect.selectedIndex].value; } else { this.data['shouldOverride'] = "true"; } if (options.reuploadMediaId && options.reuploadMediaId != constants.defaultReuploadMediaId && uploadsModel.uploads().length > 0) { messageBox.clearMessages(); messageBox.addWarningMessage(globalization.multipleFilesWarningMessageOnReupload); var uploadedFiles = uploadsModel.uploads(); for (var i = 0; i < uploadedFiles.length; i++) { uploadedFiles[i].activate(); } return; } var fileModel = new FileViewModel(file); uploadsModel.activeUploads.push(fileModel); uploadsModel.uploads.push(fileModel); var transferAnimationId; file.on({ // Called after received response from the server onCompleted: function(data) { var result = JSON.parse(data); if (result.Success) { uploadsModel.activeUploads.remove(fileModel); fileModel.fileId(result.Data.FileId); fileModel.version(result.Data.Version); fileModel.type(result.Data.Type); clearInterval(transferAnimationId); fileModel.isProgressVisible(true); fileModel.uploadCompleted(true); if (result.Data.IsFailed) { fileModel.uploadFailed(true); fileModel.failureMessage(globalization.failedToProcessFile); } else if (result.Data.IsProcessing) { fileModel.uploadProcessing(true); fileModel.isProgressVisible(false); uploadsModel.startStatusChecking(uploadsModel.firstTimeout); } } else { fileModel.uploadFailed(true); fileModel.failureMessage(''); if (result.Messages) { var failureMessages = ''; for (var i = 0; i < result.Messages.length; i++) { failureMessages += result.Messages[i] + ' '; } clearInterval(transferAnimationId); fileModel.isProgressVisible(true); fileModel.failureMessage(failureMessages); } } }, // Called during upload progress, first parameter is decimal value from 0 to 100. onProgress: function(progress) { fileModel.uploadProgress(parseInt(progress, 10)); }, onError: function() { fileModel.uploadFailed(true); uploadsModel.activeUploads.remove(fileModel); }, onTransfer: function () { fileModel.isProgressVisible(false); if (overrideSelect) { overrideSelect.disabled = true; } transferAnimationId = setInterval(function () { if (fileModel.uploadProgress() >= 100) { fileModel.uploadProgress(0); } else { fileModel.uploadProgress(fileModel.uploadProgress() + 20); }; }, 200); } }); } }); ko.applyBindings(uploadsModel, context); } } function fixUploadButtonForMozilla() { if ($.browser.mozilla) { $('#' + $(this).attr('for')).click(); return false; } return true; } function trimTrailingZeros(number) { return number.toFixed(1).replace(/\.0+$/, ''); } function formatFileSize(sizeInBytes) { var kiloByte = 1024, megaByte = Math.pow(kiloByte, 2), gigaByte = Math.pow(kiloByte, 3); if (sizeInBytes < kiloByte) { return sizeInBytes + ' B'; } if (sizeInBytes < megaByte) { return trimTrailingZeros(sizeInBytes / kiloByte) + ' KB'; } if (sizeInBytes < gigaByte) { return trimTrailingZeros(sizeInBytes / megaByte) + ' MB'; } return trimTrailingZeros(sizeInBytes / gigaByte) + ' GB'; } /** * Initializes page module. */ mediaUpload.init = function () { }; /** * Register initialization */ bcms.registerInit(mediaUpload.init); return mediaUpload; });
gpl-3.0
kikimo/leetcode
82-remove-duplicates-from-sorted-list-ii.go
579
package main import "fmt" type ListNode struct { Val int Next *ListNode } /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func deleteDuplicates(head *ListNode) *ListNode { ptr := &head for *ptr != nil { next := &((*ptr).Next) val := (*ptr).Val if (*next) != nil && val == (*next).Val { // TODO delete all node has Val for (*ptr) != nil && (*ptr).Val == val { next := (*ptr).Next *ptr = next } } else { ptr = next } } return head } func main() { fmt.Println("vim-go") }
gpl-3.0
cwalther/Plasma-nobink-test
Sources/Plasma/PubUtilLib/plAudioCore/plWavFile.cpp
36905
/*==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, 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/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email [email protected] or by snail mail at: Cyan Worlds, Inc. 14617 N Newport Hwy Mead, WA 99021 *==LICENSE==*/ #include <stdio.h> #include "plWavFile.h" #ifdef BUILDING_MAXPLUGIN #ifdef DX_OLD_SDK #include <dxerr9.h> #else #include <dxerr.h> #endif #include <dsound.h> #include <stdio.h> #pragma comment(lib, "winmm.lib") #ifdef PATCHER #define DXTRACE_ERR(str,hr) hr // I'm not linking in directx stuff to the just for this #endif // if it looks like I lifted this class directly from Microsoft it's because that // is exactly what I did. It's okay, though. Microsoft tells you to go ahead // and do it in the DX8 documentation. They are SO nice. //----------------------------------------------------------------------------- // Name: CWaveFile::CWaveFile() // Desc: Constructs the class. Call Open() to open a wave file for reading. // Then call Read() as needed. Calling the destructor or Close() // will close the file. //----------------------------------------------------------------------------- CWaveFile::CWaveFile() { m_pwfx = NULL; m_hmmio = NULL; m_dwSize = 0; m_bIsReadingFromMemory = FALSE; fSecsPerSample = 0; } //----------------------------------------------------------------------------- // Name: CWaveFile::~CWaveFile() // Desc: Destructs the class //----------------------------------------------------------------------------- CWaveFile::~CWaveFile() { Close(); if( !m_bIsReadingFromMemory ) { delete[] m_pwfx; } int i; for(i = 0 ; i < fMarkers.size() ; i++) { delete [] fMarkers[i]->fName; } } //----------------------------------------------------------------------------- // Name: CWaveFile::Open() // Desc: Opens a wave file for reading //----------------------------------------------------------------------------- HRESULT CWaveFile::Open(const char *strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags ) { HRESULT hr; m_dwFlags = dwFlags; m_bIsReadingFromMemory = FALSE; char fileName[MAX_PATH]; sprintf(fileName, strFileName); #ifdef UNICODE wchar_t * temp = hsStringToWString(fileName); std::wstring wFileName = temp; delete [] temp; #endif if( m_dwFlags == WAVEFILE_READ ) { if( strFileName == NULL ) return E_INVALIDARG; delete[] m_pwfx; #ifdef UNICODE m_hmmio = mmioOpen( (wchar_t*)wFileName.c_str(), NULL, MMIO_ALLOCBUF | MMIO_READ ); #else m_hmmio = mmioOpen( fileName, NULL, MMIO_ALLOCBUF | MMIO_READ ); #endif if( NULL == m_hmmio ) { HRSRC hResInfo; HGLOBAL hResData; DWORD dwSize; VOID* pvRes; // Loading it as a file failed, so try it as a resource #ifdef UNICODE if( NULL == ( hResInfo = FindResource( NULL, wFileName.c_str(), TEXT("WAVE") ) ) ) { if( NULL == ( hResInfo = FindResource( NULL, wFileName.c_str(), TEXT("WAV") ) ) ) return DXTRACE_ERR( TEXT("FindResource"), E_FAIL ); } #else if( NULL == ( hResInfo = FindResource( NULL, strFileName, TEXT("WAVE") ) ) ) { if( NULL == ( hResInfo = FindResource( NULL, strFileName, TEXT("WAV") ) ) ) return DXTRACE_ERR( TEXT("FindResource"), E_FAIL ); } #endif if( NULL == ( hResData = LoadResource( NULL, hResInfo ) ) ) return DXTRACE_ERR( TEXT("LoadResource"), E_FAIL ); if( 0 == ( dwSize = SizeofResource( NULL, hResInfo ) ) ) return DXTRACE_ERR( TEXT("SizeofResource"), E_FAIL ); if( NULL == ( pvRes = LockResource( hResData ) ) ) return DXTRACE_ERR( TEXT("LockResource"), E_FAIL ); CHAR* pData = new CHAR[ dwSize ]; memcpy( pData, pvRes, dwSize ); MMIOINFO mmioInfo; ZeroMemory( &mmioInfo, sizeof(mmioInfo) ); mmioInfo.fccIOProc = FOURCC_MEM; mmioInfo.cchBuffer = dwSize; mmioInfo.pchBuffer = (CHAR*) pData; m_hmmio = mmioOpen( NULL, &mmioInfo, MMIO_ALLOCBUF | MMIO_READ ); } if( FAILED( hr = ReadMMIO() ) ) { // ReadMMIO will fail if its an not a wave file mmioClose( m_hmmio, 0 ); return DXTRACE_ERR( TEXT("ReadMMIO"), hr ); } if( FAILED( hr = ResetFile() ) ) return DXTRACE_ERR( TEXT("ResetFile"), hr ); // After the reset, the size of the wav file is m_ck.cksize so store it now m_dwSize = m_ck.cksize; } else { #ifdef UNICODE m_hmmio = mmioOpen( (wchar_t*)wFileName.c_str(), NULL, MMIO_ALLOCBUF | MMIO_READWRITE | MMIO_CREATE ); #else m_hmmio = mmioOpen( fileName, NULL, MMIO_ALLOCBUF | MMIO_READWRITE | MMIO_CREATE ); #endif if( NULL == m_hmmio ) return DXTRACE_ERR( TEXT("mmioOpen"), E_FAIL ); if( FAILED( hr = WriteMMIO( pwfx ) ) ) { mmioClose( m_hmmio, 0 ); return DXTRACE_ERR( TEXT("WriteMMIO"), hr ); } if( FAILED( hr = ResetFile() ) ) return DXTRACE_ERR( TEXT("ResetFile"), hr ); } return hr; } //----------------------------------------------------------------------------- // Name: CWaveFile::OpenFromMemory() // Desc: copy data to CWaveFile member variable from memory //----------------------------------------------------------------------------- HRESULT CWaveFile::OpenFromMemory( BYTE* pbData, ULONG ulDataSize, WAVEFORMATEX* pwfx, DWORD dwFlags ) { m_pwfx = pwfx; m_ulDataSize = ulDataSize; m_pbData = pbData; m_pbDataCur = m_pbData; m_bIsReadingFromMemory = TRUE; if( dwFlags != WAVEFILE_READ ) return E_NOTIMPL; return S_OK; } /* This defintion for a CuePoint was ripped from the internet somewhere. There are more defs at the end of this file which attempt to document these wave file format extensions for storing markers. Cue Point-- The dwIdentifier field contains a unique number (ie, different than the ID number of any other CuePoint structure). This is used to associate a CuePoint structure with other structures used in other chunks which will be described later. The dwPosition field specifies the position of the cue point within the "play order" (as determined by the Playlist chunk. See that chunk for a discussion of the play order). The fccChunk field specifies the chunk ID of the Data or Wave List chunk which actually contains the waveform data to which this CuePoint refers. If there is only one Data chunk in the file, then this field is set to the ID 'data'. On the other hand, if the file contains a Wave List (which can contain both 'data' and 'slnt' chunks), then fccChunk will specify 'data' or 'slnt' depending upon in which type of chunk the referenced waveform data is found. The dwChunkStart and dwBlockStart fields are set to 0 for an uncompressed WAVE file that contains one 'data' chunk. These fields are used only for WAVE files that contain a Wave List (with multiple 'data' and 'slnt' chunks), or for a compressed file containing a 'data' chunk. (Actually, in the latter case, dwChunkStart is also set to 0, and only dwBlockStart is used). Again, I want to emphasize that you can avoid all of this unnecessary crap if you avoid hassling with compressed files, or Wave Lists, and instead stick to the sensible basics. The dwChunkStart field specifies the uint8_t offset of the start of the 'data' or 'slnt' chunk which actually contains the waveform data to which this CuePoint refers. This offset is relative to the start of the first chunk within the Wave List. (ie, It's the uint8_t offset, within the Wave List, of where the 'data' or 'slnt' chunk of interest appears. The first chunk within the List would be at an offset of 0). The dwBlockStart field specifies the uint8_t offset of the start of the block containing the position. This offset is relative to the start of the waveform data within the 'data' or 'slnt' chunk. The dwSampleOffset field specifies the sample offset of the cue point relative to the start of the block. In an uncompressed file, this equates to simply being the offset within the waveformData array. Unfortunately, the WAVE documentation is much too ambiguous, and doesn't define what it means by the term "sample offset". This could mean a uint8_t offset, or it could mean counting the sample points (for example, in a 16-bit wave, every 2 bytes would be 1 sample point), or it could even mean sample frames (as the loop offsets in AIFF are specified). Who knows? The guy who conjured up the Cue chunk certainly isn't saying. I'm assuming that it's a uint8_t offset, like the above 2 fields. */ class CuePoint { public: DWORD dwIdentifier; DWORD dwPosition; FOURCC fccChunk; DWORD dwChunkStart; DWORD dwBlockStart; DWORD dwSampleOffset; public: CuePoint(DWORD id, DWORD pos, FOURCC chk, DWORD ckSt, DWORD BkSt, DWORD SO) : dwIdentifier(id), dwPosition(pos), fccChunk(chk), dwChunkStart(ckSt), dwBlockStart(BkSt), dwSampleOffset(SO) {} CuePoint(){} }; // // this struct is used to hold cue pts temporarily while we wait for the labels that match them // struct myCuePoint { DWORD fId; DWORD fOffset; }; //----------------------------------------------------------------------------- // Name: CWaveFile::ReadMMIO() // Desc: Support function for reading from a multimedia I/O stream. // m_hmmio must be valid before calling. This function uses it to // update m_ckRiff, and m_pwfx. //----------------------------------------------------------------------------- HRESULT CWaveFile::ReadMMIO() { MMCKINFO ckIn; // chunk info. for general use. PCMWAVEFORMAT pcmWaveFormat; // Temp PCM structure to load in. m_pwfx = NULL; if( ( 0 != mmioDescend( m_hmmio, &m_ckRiff, NULL, 0 ) ) ) return DXTRACE_ERR( TEXT("mmioDescend"), E_FAIL ); // Check to make sure this is a valid wave file if( (m_ckRiff.ckid != FOURCC_RIFF) || (m_ckRiff.fccType != mmioFOURCC('W', 'A', 'V', 'E') ) ) return DXTRACE_ERR( TEXT("mmioFOURCC"), E_FAIL ); // Search the input file for for the 'fmt ' chunk. ckIn.ckid = mmioFOURCC('f', 'm', 't', ' '); if( 0 != mmioDescend( m_hmmio, &ckIn, &m_ckRiff, MMIO_FINDCHUNK ) ) return DXTRACE_ERR( TEXT("mmioDescend"), E_FAIL ); // Expect the 'fmt' chunk to be at least as large as <PCMWAVEFORMAT>; // if there are extra parameters at the end, we'll ignore them if( ckIn.cksize < (LONG) sizeof(PCMWAVEFORMAT) ) return DXTRACE_ERR( TEXT("sizeof(PCMWAVEFORMAT)"), E_FAIL ); // Read the 'fmt ' chunk into <pcmWaveFormat>. if( mmioRead( m_hmmio, (HPSTR) &pcmWaveFormat, sizeof(pcmWaveFormat)) != sizeof(pcmWaveFormat) ) return DXTRACE_ERR( TEXT("mmioRead"), E_FAIL ); // Allocate the waveformatex, but if its not pcm format, read the next // uint16_t, and thats how many extra bytes to allocate. if( pcmWaveFormat.wf.wFormatTag == WAVE_FORMAT_PCM ) { m_pwfx = (WAVEFORMATEX*)( new CHAR[ sizeof( WAVEFORMATEX ) ] ); if( NULL == m_pwfx ) return DXTRACE_ERR( TEXT("m_pwfx"), E_FAIL ); // Copy the bytes from the pcm structure to the waveformatex structure memcpy( m_pwfx, &pcmWaveFormat, sizeof(pcmWaveFormat) ); m_pwfx->cbSize = 0; } else { // Read in length of extra bytes. WORD cbExtraBytes = 0L; if( mmioRead( m_hmmio, (CHAR*)&cbExtraBytes, sizeof(WORD)) != sizeof(WORD) ) return DXTRACE_ERR( TEXT("mmioRead"), E_FAIL ); m_pwfx = (WAVEFORMATEX*)( new CHAR[ sizeof(WAVEFORMATEX) + cbExtraBytes ] ); if( NULL == m_pwfx ) return DXTRACE_ERR( TEXT("new"), E_FAIL ); // Copy the bytes from the pcm structure to the waveformatex structure memcpy( m_pwfx, &pcmWaveFormat, sizeof(pcmWaveFormat) ); m_pwfx->cbSize = cbExtraBytes; // Now, read those extra bytes into the structure, if cbExtraAlloc != 0. if( mmioRead( m_hmmio, (CHAR*)(((BYTE*)&(m_pwfx->cbSize))+sizeof(WORD)), cbExtraBytes ) != cbExtraBytes ) { delete m_pwfx; return DXTRACE_ERR( TEXT("mmioRead"), E_FAIL ); } } fSecsPerSample = 1.0/ (double)(pcmWaveFormat.wf.nSamplesPerSec) ; // * (((double)pcmWaveFormat.wBitsPerSample)/8.0); // Ascend the input file out of the 'fmt ' chunk. if( 0 != mmioAscend( m_hmmio, &ckIn, 0 ) ) { delete m_pwfx; return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL ); } // // Here is where we attempt to parse sound indicies from the file for loop points. // If there is no cue chunk then we just return OK // ckIn.ckid = mmioFOURCC('c', 'u', 'e', ' '); if( 0 != mmioDescend( m_hmmio, &ckIn, &m_ckRiff, MMIO_FINDCHUNK ) ) return S_OK; // No Cue Chunck so no point in reading the rest #if 0 // Expect the 'cue ' chunk to be at least as large as <PCMWAVEFORMAT>; // if there are extra parameters at the end, we'll ignore them if( ckIn.cksize < (long) ( sizeof(FOURCC) + 2*(sizeof(DWORD)) + sizeof(CuePoint) ) ) return DXTRACE_ERR( TEXT("sizeof(CueChunk)"), E_FAIL ); #endif DWORD* CueBuff = new DWORD[ckIn.cksize]; DWORD Results; Read((BYTE*)CueBuff, ckIn.cksize, &Results); std::vector<myCuePoint> myCueList; // Place to hold the cue points int numCuePoints = (ckIn.cksize - sizeof(DWORD))/sizeof(CuePoint); // this is how many there should be. unsigned int i, j; for (i = 1, j = 0; i <= ckIn.cksize && j < numCuePoints ; i += sizeof(CuePoint)/(sizeof(DWORD)), j++) { myCuePoint p; p.fId = CueBuff[i]; // dwIdentifier p.fOffset = CueBuff[i+1]; // dwPosition myCueList.push_back(p); } delete[] CueBuff; if( 0 != mmioAscend( m_hmmio, &ckIn, 0 ) ) { delete m_pwfx; return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL ); } // Goal --> Grab the label information below ckIn.ckid = mmioFOURCC('a', 'd', 't', 'l'); if( 0 != mmioDescend( m_hmmio, &ckIn, &m_ckRiff, MMIO_FINDLIST ) ) return DXTRACE_ERR( TEXT("mmioDescend, with list"), E_FAIL ); plSoundMarker *newMarker; BYTE *labelBuf = new BYTE [ckIn.cksize]; // Read the entire lable chunk and then lets parse out the individual lables. Read(labelBuf, ckIn.cksize-4, &Results); BYTE *bp = labelBuf; // Keep looking for labl chunks till we run out. while(!strncmp("labl",(char*)bp,4)) { DWORD size = *(DWORD*)(bp + 4); DWORD id = *(DWORD*)(bp + 8); newMarker = new plSoundMarker; // Grab a new label int i; int numPts = myCueList.size(); // // Do we have a matching cue point for this label? // for(i = 0 ; i < numPts; i++) { if(id == myCueList[i].fId) { newMarker->fOffset = myCueList[i].fOffset * fSecsPerSample; } } int stringSize = size - sizeof(DWORD); // text string is size of chunck - size of the size uint16_t newMarker->fName = new char[ stringSize]; strcpy(newMarker->fName, (char*)(bp + 12)); fMarkers.push_back(newMarker); bp += size + 8; // crappy fixup hack for odd length label records if(size & 1 && !strncmp("labl", (char*)(bp +1), 4)) bp++; fprintf(stderr,"Label name=%s Time =%f\n",newMarker->fName, newMarker->fOffset); } delete [] labelBuf; if( 0 != mmioAscend( m_hmmio, &ckIn, 0 ) ) { delete m_pwfx; return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL ); } return S_OK; } //----------------------------------------------------------------------------- // Name: CWaveFile::GetSize() // Desc: Retuns the size of the read access wave file //----------------------------------------------------------------------------- DWORD CWaveFile::GetSize() { return m_dwSize; } //----------------------------------------------------------------------------- // Name: CWaveFile::ResetFile() // Desc: Resets the internal m_ck pointer so reading starts from the // beginning of the file again //----------------------------------------------------------------------------- HRESULT CWaveFile::ResetFile() { if( m_bIsReadingFromMemory ) { m_pbDataCur = m_pbData; } else { if( m_hmmio == NULL ) return CO_E_NOTINITIALIZED; if( m_dwFlags == WAVEFILE_READ ) { // Seek to the data if( -1 == mmioSeek( m_hmmio, m_ckRiff.dwDataOffset + sizeof(FOURCC), SEEK_SET ) ) return DXTRACE_ERR( TEXT("mmioSeek"), E_FAIL ); // Search the input file for the 'data' chunk. m_ck.ckid = mmioFOURCC('d', 'a', 't', 'a'); if( 0 != mmioDescend( m_hmmio, &m_ck, &m_ckRiff, MMIO_FINDCHUNK ) ) return DXTRACE_ERR( TEXT("mmioDescend"), E_FAIL ); } else { // Create the 'data' chunk that holds the waveform samples. m_ck.ckid = mmioFOURCC('d', 'a', 't', 'a'); m_ck.cksize = 0; if( 0 != mmioCreateChunk( m_hmmio, &m_ck, 0 ) ) return DXTRACE_ERR( TEXT("mmioCreateChunk"), E_FAIL ); if( 0 != mmioGetInfo( m_hmmio, &m_mmioinfoOut, 0 ) ) return DXTRACE_ERR( TEXT("mmioGetInfo"), E_FAIL ); } } return S_OK; } #define MCN_USE_NEW_READ_METHOD 0 //----------------------------------------------------------------------------- // Name: CWaveFile::Read() // Desc: Reads section of data from a wave file into pBuffer and returns // how much read in pdwSizeRead, reading not more than dwSizeToRead. // This uses m_ck to determine where to start reading from. So // subsequent calls will be continue where the last left off unless // Reset() is called. //----------------------------------------------------------------------------- HRESULT CWaveFile::Read( BYTE* pBuffer, DWORD dwSizeToRead, DWORD* pdwSizeRead ) { if( m_bIsReadingFromMemory ) { if( m_pbDataCur == NULL ) return CO_E_NOTINITIALIZED; if( pdwSizeRead != NULL ) *pdwSizeRead = 0; if( (BYTE*)(m_pbDataCur + dwSizeToRead) > (BYTE*)(m_pbData + m_ulDataSize) ) { dwSizeToRead = m_ulDataSize - (DWORD)(m_pbDataCur - m_pbData); } CopyMemory( pBuffer, m_pbDataCur, dwSizeToRead ); if( pdwSizeRead != NULL ) *pdwSizeRead = dwSizeToRead; return S_OK; } else { MMIOINFO mmioinfoIn; // current status of m_hmmio if( m_hmmio == NULL ) return CO_E_NOTINITIALIZED; if( pBuffer == NULL || pdwSizeRead == NULL ) return E_INVALIDARG; if( pdwSizeRead != NULL ) *pdwSizeRead = 0; if( 0 != mmioGetInfo( m_hmmio, &mmioinfoIn, 0 ) ) return DXTRACE_ERR( TEXT("mmioGetInfo"), E_FAIL ); UINT cbDataIn = dwSizeToRead; if( cbDataIn > m_ck.cksize ) cbDataIn = m_ck.cksize; m_ck.cksize -= cbDataIn; #if !(MCN_USE_NEW_READ_METHOD) for( DWORD cT = 0; cT < cbDataIn; cT++ ) { // Copy the bytes from the io to the buffer. if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead ) { if( 0 != mmioAdvance( m_hmmio, &mmioinfoIn, MMIO_READ ) ) return DXTRACE_ERR( TEXT("mmioAdvance"), E_FAIL ); if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead ) return DXTRACE_ERR( TEXT("mmioinfoIn.pchNext"), E_FAIL ); } // Actual copy. *((BYTE*)pBuffer+cT) = *((BYTE*)mmioinfoIn.pchNext); mmioinfoIn.pchNext++; } #else // Attempt to do this a bit faster... 9.12.2001 mcn for( DWORD cT = 0; cT < cbDataIn; ) { // Copy the bytes from the io to the buffer. if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead ) { if( 0 != mmioAdvance( m_hmmio, &mmioinfoIn, MMIO_READ ) ) return DXTRACE_ERR( TEXT("mmioAdvance"), E_FAIL ); if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead ) return DXTRACE_ERR( TEXT("mmioinfoIn.pchNext"), E_FAIL ); } // Actual copy DWORD length = (DWORD)mmioinfoIn.pchEndRead - (DWORD)mmioinfoIn.pchNext; if( cT + length > cbDataIn ) length = cbDataIn - cT; memcpy( (BYTE*)pBuffer + cT, mmioinfoIn.pchNext, length ); mmioinfoIn.pchNext += length; cT += length; } #endif if( 0 != mmioSetInfo( m_hmmio, &mmioinfoIn, 0 ) ) return DXTRACE_ERR( TEXT("mmioSetInfo"), E_FAIL ); if( pdwSizeRead != NULL ) *pdwSizeRead = cbDataIn; return S_OK; } } //----------------------------------------------------------------------------- // Name: CWaveFile::AdvanceWithoutRead() // Desc: Identical to Read(), only doesn't actually read any data in. //----------------------------------------------------------------------------- HRESULT CWaveFile::AdvanceWithoutRead( DWORD dwSizeToRead, DWORD* pdwSizeRead ) { if( m_bIsReadingFromMemory ) { if( m_pbDataCur == NULL ) return CO_E_NOTINITIALIZED; if( pdwSizeRead != NULL ) *pdwSizeRead = 0; if( (BYTE*)(m_pbDataCur + dwSizeToRead) > (BYTE*)(m_pbData + m_ulDataSize) ) { dwSizeToRead = m_ulDataSize - (DWORD)(m_pbDataCur - m_pbData); } if( pdwSizeRead != NULL ) *pdwSizeRead = dwSizeToRead; return S_OK; } else { MMIOINFO mmioinfoIn; // current status of m_hmmio if( m_hmmio == NULL ) return CO_E_NOTINITIALIZED; if( pdwSizeRead == NULL ) return E_INVALIDARG; if( pdwSizeRead != NULL ) *pdwSizeRead = 0; if( 0 != mmioGetInfo( m_hmmio, &mmioinfoIn, 0 ) ) return DXTRACE_ERR( TEXT("mmioGetInfo"), E_FAIL ); UINT cbDataIn = dwSizeToRead; if( cbDataIn > m_ck.cksize ) cbDataIn = m_ck.cksize; m_ck.cksize -= cbDataIn; #if !(MCN_USE_NEW_READ_METHOD) for( DWORD cT = 0; cT < cbDataIn; cT++ ) { // Copy the bytes from the io to the buffer. if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead ) { if( 0 != mmioAdvance( m_hmmio, &mmioinfoIn, MMIO_READ ) ) return DXTRACE_ERR( TEXT("mmioAdvance"), E_FAIL ); if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead ) return DXTRACE_ERR( TEXT("mmioinfoIn.pchNext"), E_FAIL ); } mmioinfoIn.pchNext++; } #else // Attempt to do this a bit faster... 9.12.2001 mcn for( DWORD cT = 0; cT < cbDataIn; ) { if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead ) { if( 0 != mmioAdvance( m_hmmio, &mmioinfoIn, MMIO_READ ) ) return DXTRACE_ERR( TEXT("mmioAdvance"), E_FAIL ); if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead ) return DXTRACE_ERR( TEXT("mmioinfoIn.pchNext"), E_FAIL ); } // Advance DWORD length = (DWORD)mmioinfoIn.pchEndRead - (DWORD)mmioinfoIn.pchNext; if( cT + length > cbDataIn ) length = cbDataIn - cT; mmioinfoIn.pchNext += length; cT += length; } #endif if( 0 != mmioSetInfo( m_hmmio, &mmioinfoIn, 0 ) ) return DXTRACE_ERR( TEXT("mmioSetInfo"), E_FAIL ); if( pdwSizeRead != NULL ) *pdwSizeRead = cbDataIn; return S_OK; } } //----------------------------------------------------------------------------- // Name: CWaveFile::IClose() // Desc: Closes the wave file //----------------------------------------------------------------------------- HRESULT CWaveFile::IClose() { if( m_dwFlags == WAVEFILE_READ ) { mmioClose( m_hmmio, 0 ); m_hmmio = NULL; } else { m_mmioinfoOut.dwFlags |= MMIO_DIRTY; if( m_hmmio == NULL ) return CO_E_NOTINITIALIZED; if( 0 != mmioSetInfo( m_hmmio, &m_mmioinfoOut, 0 ) ) return DXTRACE_ERR( TEXT("mmioSetInfo"), E_FAIL ); // Ascend the output file out of the 'data' chunk -- this will cause // the chunk size of the 'data' chunk to be written. if( 0 != mmioAscend( m_hmmio, &m_ck, 0 ) ) return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL ); // Do this here instead... if( 0 != mmioAscend( m_hmmio, &m_ckRiff, 0 ) ) return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL ); mmioSeek( m_hmmio, 0, SEEK_SET ); if( 0 != (INT)mmioDescend( m_hmmio, &m_ckRiff, NULL, 0 ) ) return DXTRACE_ERR( TEXT("mmioDescend"), E_FAIL ); m_ck.ckid = mmioFOURCC('f', 'a', 'c', 't'); if( 0 == mmioDescend( m_hmmio, &m_ck, &m_ckRiff, MMIO_FINDCHUNK ) ) { DWORD dwSamples = 0; mmioWrite( m_hmmio, (HPSTR)&dwSamples, sizeof(DWORD) ); mmioAscend( m_hmmio, &m_ck, 0 ); } // Ascend the output file out of the 'RIFF' chunk -- this will cause // the chunk size of the 'RIFF' chunk to be written. if( 0 != mmioAscend( m_hmmio, &m_ckRiff, 0 ) ) return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL ); mmioClose( m_hmmio, 0 ); m_hmmio = NULL; } return S_OK; } //----------------------------------------------------------------------------- // Name: CWaveFile::WriteMMIO() // Desc: Support function for reading from a multimedia I/O stream // pwfxDest is the WAVEFORMATEX for this new wave file. // m_hmmio must be valid before calling. This function uses it to // update m_ckRiff, and m_ck. //----------------------------------------------------------------------------- HRESULT CWaveFile::WriteMMIO( WAVEFORMATEX *pwfxDest ) { DWORD dwFactChunk; // Contains the actual fact chunk. Garbage until WaveCloseWriteFile. MMCKINFO ckOut1; dwFactChunk = (DWORD)-1; // Create the output file RIFF chunk of form type 'WAVE'. m_ckRiff.fccType = mmioFOURCC('W', 'A', 'V', 'E'); m_ckRiff.cksize = 0; if( 0 != mmioCreateChunk( m_hmmio, &m_ckRiff, MMIO_CREATERIFF ) ) return DXTRACE_ERR( TEXT("mmioCreateChunk"), E_FAIL ); // We are now descended into the 'RIFF' chunk we just created. // Now create the 'fmt ' chunk. Since we know the size of this chunk, // specify it in the MMCKINFO structure so MMIO doesn't have to seek // back and set the chunk size after ascending from the chunk. m_ck.ckid = mmioFOURCC('f', 'm', 't', ' '); m_ck.cksize = sizeof(PCMWAVEFORMAT); if( 0 != mmioCreateChunk( m_hmmio, &m_ck, 0 ) ) return DXTRACE_ERR( TEXT("mmioCreateChunk"), E_FAIL ); // Write the PCMWAVEFORMAT structure to the 'fmt ' chunk if its that type. if( pwfxDest->wFormatTag == WAVE_FORMAT_PCM ) { if( mmioWrite( m_hmmio, (HPSTR) pwfxDest, sizeof(PCMWAVEFORMAT)) != sizeof(PCMWAVEFORMAT)) return DXTRACE_ERR( TEXT("mmioWrite"), E_FAIL ); } else { // Write the variable length size. if( (UINT)mmioWrite( m_hmmio, (HPSTR) pwfxDest, sizeof(*pwfxDest) + pwfxDest->cbSize ) != ( sizeof(*pwfxDest) + pwfxDest->cbSize ) ) return DXTRACE_ERR( TEXT("mmioWrite"), E_FAIL ); } // Ascend out of the 'fmt ' chunk, back into the 'RIFF' chunk. if( 0 != mmioAscend( m_hmmio, &m_ck, 0 ) ) return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL ); // Now create the fact chunk, not required for PCM but nice to have. This is filled // in when the close routine is called. ckOut1.ckid = mmioFOURCC('f', 'a', 'c', 't'); ckOut1.cksize = 0; if( 0 != mmioCreateChunk( m_hmmio, &ckOut1, 0 ) ) return DXTRACE_ERR( TEXT("mmioCreateChunk"), E_FAIL ); if( mmioWrite( m_hmmio, (HPSTR)&dwFactChunk, sizeof(dwFactChunk)) != sizeof(dwFactChunk) ) return DXTRACE_ERR( TEXT("mmioWrite"), E_FAIL ); // Now ascend out of the fact chunk... if( 0 != mmioAscend( m_hmmio, &ckOut1, 0 ) ) return DXTRACE_ERR( TEXT("mmioAscend"), E_FAIL ); return S_OK; } //----------------------------------------------------------------------------- // Name: CWaveFile::Write() // Desc: Writes data to the open wave file //----------------------------------------------------------------------------- HRESULT CWaveFile::Write( UINT nSizeToWrite, BYTE* pbSrcData, UINT* pnSizeWrote ) { UINT cT; if( m_bIsReadingFromMemory ) return E_NOTIMPL; if( m_hmmio == NULL ) return CO_E_NOTINITIALIZED; if( pnSizeWrote == NULL || pbSrcData == NULL ) return E_INVALIDARG; *pnSizeWrote = 0; for( cT = 0; cT < nSizeToWrite; cT++ ) { if( m_mmioinfoOut.pchNext == m_mmioinfoOut.pchEndWrite ) { m_mmioinfoOut.dwFlags |= MMIO_DIRTY; if( 0 != mmioAdvance( m_hmmio, &m_mmioinfoOut, MMIO_WRITE ) ) return DXTRACE_ERR( TEXT("mmioAdvance"), E_FAIL ); } *((BYTE*)m_mmioinfoOut.pchNext) = *((BYTE*)pbSrcData+cT); (BYTE*)m_mmioinfoOut.pchNext++; (*pnSizeWrote)++; } return S_OK; } // Overloads for plAudioFileReader (we only support writing for CWaveFile for now) CWaveFile::CWaveFile( const char *path, plAudioCore::ChannelSelect whichChan ) { m_pwfx = NULL; m_hmmio = NULL; m_dwSize = 0; m_bIsReadingFromMemory = FALSE; fSecsPerSample = 0; // Just a stub--do nothing } hsBool CWaveFile::OpenForWriting( const char *path, plWAVHeader &header ) { fHeader = header; WAVEFORMATEX winFormat; winFormat.cbSize = 0; winFormat.nAvgBytesPerSec = header.fAvgBytesPerSec; winFormat.nBlockAlign = header.fBlockAlign; winFormat.nChannels = header.fNumChannels; winFormat.nSamplesPerSec = header.fNumSamplesPerSec; winFormat.wBitsPerSample = header.fBitsPerSample; winFormat.wFormatTag = header.fFormatTag; if( SUCCEEDED( Open( path, &winFormat, WAVEFILE_WRITE ) ) ) return true; return false; } plWAVHeader &CWaveFile::GetHeader( void ) { return fHeader; } void CWaveFile::Close( void ) { IClose(); } uint32_t CWaveFile::GetDataSize( void ) { hsAssert( false, "Unsupported" ); return 0; } float CWaveFile::GetLengthInSecs( void ) { hsAssert( false, "Unsupported" ); return 0.f; } hsBool CWaveFile::SetPosition( uint32_t numBytes ) { hsAssert( false, "Unsupported" ); return false; } hsBool CWaveFile::Read( uint32_t numBytes, void *buffer ) { hsAssert( false, "Unsupported" ); return false; } uint32_t CWaveFile::NumBytesLeft( void ) { hsAssert( false, "Unsupported" ); return 0; } uint32_t CWaveFile::Write( uint32_t bytes, void *buffer ) { UINT written; Write( (DWORD)bytes, (BYTE *)buffer, &written ); return (uint32_t)written; } hsBool CWaveFile::IsValid( void ) { return true; } #if 0 THIS IS MORE STUFF having to do with WAV FILE format. It is just sitting here for documentation purposes. /* Cue Chunk-- The ID is always 'cue '. chunkSize is the number of bytes in the chunk, not counting the 8 bytes used by ID and Size fields. The dwCuePoints field is the number of CuePoint structures in the Cue Chunk. If dwCuePoints is not 0, it is followed by that many CuePoint structures, one after the other. Because all fields in a CuePoint structure are an even number of bytes, the length of any CuePoint will always be even. Thus, CuePoints are packed together with no unused bytes between them. The CuePoints need not be placed in any particular order. The Cue chunk is optional. No more than one Cue chunk can appear in a WAVE. */ class CueChunk { public: FOURCC chunkID; DWORD chunkSize; DWORD dwCuePoints; std::vector<CuePoint*> points; public: CueChunk(DWORD ChunkSize) { chunkID = mmioFOURCC('c','u','e',' '); chunkSize = ChunkSize; dwCuePoints = (ChunkSize - (sizeof(DWORD)*1))/(sizeof(CuePoint)); //points = NULL; //points = new CuePoint[dwCuePoints]; } //Cue ~CueChunk() {} //for(int i = 0; i < (int) dwCuePoints; i++) points.erase(i); } }; /* LabelChunk-- The ID is always 'labl'. chunkSize is the number of bytes in the chunk, not counting the 8 bytes used by ID and Size fields nor any possible pad uint8_t needed to make the chunk an even size (ie, chunkSize is the number of remaining bytes in the chunk after the chunkSize field, not counting any trailing pad byte). The dwIdentifier field contains a unique number (ie, different than the ID number of any other Label chunk). This field should correspond with the dwIndentifier field of some CuePoint stored in the Cue chunk. In other words, this Label chunk contains the text label associated with that CuePoint structure with the same ID number. The dwText array contains the text label. It should be a null-terminated string. (The null uint8_t is included in the chunkSize, therefore the length of the string, including the null uint8_t, is chunkSize - 4). */ class LabelChunk { public: FOURCC chunkID; DWORD chunkSize; DWORD dwIdentifier; char* dwText; public: LabelChunk(DWORD ChunkSize) { chunkID = mmioFOURCC('l','a','b','l'); chunkSize = ChunkSize; dwIdentifier = 0; dwText = NULL; } LabelChunk() { chunkID = mmioFOURCC('l','a','b','l'); chunkSize = 0; dwIdentifier = 0; dwText = NULL; } ~LabelChunk() { delete[] dwText; } }; #endif #endif // BUILDING_MAXPLUGIN
gpl-3.0
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System.Web/System/Web/UI/WebControls/DetailsViewUpdatedEventHandler.cs
906
// Decompiled with JetBrains decompiler // Type: System.Web.UI.WebControls.DetailsViewUpdatedEventHandler // Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // MVID: 7E68A73E-4066-4F24-AB0A-F147209F50EC // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll namespace System.Web.UI.WebControls { /// <summary> /// Represents the method that handles the <see cref="E:System.Web.UI.WebControls.DetailsView.ItemUpdated"/> event of a <see cref="T:System.Web.UI.WebControls.DetailsView"/> control. This class cannot be inherited. /// </summary> /// <param name="sender">The source of the event.</param><param name="e">A <see cref="T:System.Web.UI.WebControls.DetailsViewUpdatedEventArgs"/> that contains the event data.</param> public delegate void DetailsViewUpdatedEventHandler(object sender, DetailsViewUpdatedEventArgs e); }
gpl-3.0
DroneBucket/Drone_Bucket_CrazyFlie2_NRF_Firmware
nrf51_sdk/Documentation/s210/html/search/enums_6d.js
344
var searchData= [ ['motion_5foutput_5fpolarity_5ft',['motion_output_polarity_t',['../group__nrf__drivers__adns2080.html#ga0a2e533ff5cb6517085859827320e103',1,'adns2080.h']]], ['motion_5foutput_5fsensitivity_5ft',['motion_output_sensitivity_t',['../group__nrf__drivers__adns2080.html#gaf829efdc343990811ba18dd86c68ef41',1,'adns2080.h']]] ];
gpl-3.0
HY-ZhengWei/hy.common.android
google.zxing.android/src/main/java/com/google/zxing/client/android/encode/EncodeActivity.java
7720
/* * Copyright (C) 2008 ZXing 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.google.zxing.client.android.encode; import android.graphics.Point; import android.view.Display; import android.view.MenuInflater; import android.view.WindowManager; import com.google.zxing.WriterException; import com.google.zxing.client.android.Contents; import com.google.zxing.client.android.FinishListener; import com.google.zxing.client.android.Intents; import com.google.zxing.client.android.R; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.regex.Pattern; /** * This class encodes data from an Intent into a QR code, and then displays it full screen so that * another person can scan it with their device. * * @author [email protected] (Daniel Switkin) */ public final class EncodeActivity extends Activity { private static final String TAG = EncodeActivity.class.getSimpleName(); private static final int MAX_BARCODE_FILENAME_LENGTH = 24; private static final Pattern NOT_ALPHANUMERIC = Pattern.compile("[^A-Za-z0-9]"); private static final String USE_VCARD_KEY = "USE_VCARD"; private QRCodeEncoder qrCodeEncoder; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Intent intent = getIntent(); if (intent == null) { finish(); } else { String action = intent.getAction(); if (Intents.Encode.ACTION.equals(action) || Intent.ACTION_SEND.equals(action)) { setContentView(R.layout.encode); } else { finish(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.encode, menu); boolean useVcard = qrCodeEncoder != null && qrCodeEncoder.isUseVCard(); int encodeNameResource = useVcard ? R.string.menu_encode_mecard : R.string.menu_encode_vcard; MenuItem encodeItem = menu.findItem(R.id.menu_encode); encodeItem.setTitle(encodeNameResource); Intent intent = getIntent(); if (intent != null) { String type = intent.getStringExtra(Intents.Encode.TYPE); encodeItem.setVisible(Contents.Type.CONTACT.equals(type)); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int i = item.getItemId(); if (i == R.id.menu_share) { share(); return true; } else if (i == R.id.menu_encode) { Intent intent = getIntent(); if (intent == null) { return false; } intent.putExtra(USE_VCARD_KEY, !qrCodeEncoder.isUseVCard()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); return true; } else { return false; } } private void share() { QRCodeEncoder encoder = qrCodeEncoder; if (encoder == null) { // Odd Log.w(TAG, "No existing barcode to send?"); return; } String contents = encoder.getContents(); if (contents == null) { Log.w(TAG, "No existing barcode to send?"); return; } Bitmap bitmap; try { bitmap = encoder.encodeAsBitmap(); } catch (WriterException we) { Log.w(TAG, we); return; } if (bitmap == null) { return; } File bsRoot = new File(Environment.getExternalStorageDirectory(), "BarcodeScanner"); File barcodesRoot = new File(bsRoot, "Barcodes"); if (!barcodesRoot.exists() && !barcodesRoot.mkdirs()) { Log.w(TAG, "Couldn't make dir " + barcodesRoot); showErrorMessage(R.string.msg_unmount_usb); return; } File barcodeFile = new File(barcodesRoot, makeBarcodeFileName(contents) + ".png"); if (!barcodeFile.delete()) { Log.w(TAG, "Could not delete " + barcodeFile); // continue anyway } try (FileOutputStream fos = new FileOutputStream(barcodeFile)) { bitmap.compress(Bitmap.CompressFormat.PNG, 0, fos); } catch (IOException ioe) { Log.w(TAG, "Couldn't access file " + barcodeFile + " due to " + ioe); showErrorMessage(R.string.msg_unmount_usb); return; } Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:")); intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name) + " - " + encoder.getTitle()); intent.putExtra(Intent.EXTRA_TEXT, contents); intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + barcodeFile.getAbsolutePath())); intent.setType("image/png"); intent.addFlags(Intents.FLAG_NEW_DOC); startActivity(Intent.createChooser(intent, null)); } private static CharSequence makeBarcodeFileName(CharSequence contents) { String fileName = NOT_ALPHANUMERIC.matcher(contents).replaceAll("_"); if (fileName.length() > MAX_BARCODE_FILENAME_LENGTH) { fileName = fileName.substring(0, MAX_BARCODE_FILENAME_LENGTH); } return fileName; } @Override protected void onResume() { super.onResume(); // This assumes the view is full screen, which is a good assumption WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); Point displaySize = new Point(); display.getSize(displaySize); int width = displaySize.x; int height = displaySize.y; int smallerDimension = width < height ? width : height; smallerDimension = smallerDimension * 7 / 8; Intent intent = getIntent(); if (intent == null) { return; } try { boolean useVCard = intent.getBooleanExtra(USE_VCARD_KEY, false); qrCodeEncoder = new QRCodeEncoder(this, intent, smallerDimension, useVCard); Bitmap bitmap = qrCodeEncoder.encodeAsBitmap(); if (bitmap == null) { Log.w(TAG, "Could not encode barcode"); showErrorMessage(R.string.msg_encode_contents_failed); qrCodeEncoder = null; return; } ImageView view = (ImageView) findViewById(R.id.image_view); view.setImageBitmap(bitmap); TextView contents = (TextView) findViewById(R.id.contents_text_view); if (intent.getBooleanExtra(Intents.Encode.SHOW_CONTENTS, true)) { contents.setText(qrCodeEncoder.getDisplayContents()); setTitle(qrCodeEncoder.getTitle()); } else { contents.setText(""); setTitle(""); } } catch (WriterException e) { Log.w(TAG, "Could not encode barcode", e); showErrorMessage(R.string.msg_encode_contents_failed); qrCodeEncoder = null; } } private void showErrorMessage(int message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message); builder.setPositiveButton(R.string.button_ok, new FinishListener(this)); builder.setOnCancelListener(new FinishListener(this)); builder.show(); } }
gpl-3.0
rafa1231518/CommunityBot
lib/xml2js-req/xmlbuilder/lodash/fp/object.js
100
'use strict'; const convert = require('./convert'); module.exports = convert(require('../object'));
gpl-3.0
SuperDARNCanada/placeholderOS
scheduler/local_scd_server.py
12474
#!/usr/bin/python3 # Copyright 2019 SuperDARN Canada # # local_scd_server.py # 2019-04-18 # Moniters for new SWG files and adds the SWG info to the scd if there is an update. # import subprocess as sp import scd_utils import email_utils import os import datetime import time import argparse SWG_GIT_REPO_DIR = 'schedules' SWG_GIT_REPO = "https://github.com/SuperDARN/schedules.git" EXPERIMENTS = { "sas" : { "common_time" : "twofsound", "discretionary_time" : "twofsound", "htr_common_time" : "twofsound", "themis_time" : "themisscan", "special_time_normal" : "twofsound", "rbsp_time" : "rbspscan", "no_switching_time" : "normalscan", "interleaved_time" : "interleavedscan" }, "pgr" : { "common_time" : "normalscan", "discretionary_time" : "normalscan", "htr_common_time" : "normalscan", "themis_time" : "themisscan", "special_time_normal" : "normalscan", "rbsp_time" : "rbspscan", "no_switching_time" : "normalscan", "interleaved_time" : "interleavedscan" }, "rkn" : { "common_time" : "twofsound", "discretionary_time" : "twofsound", "htr_common_time" : "twofsound", "themis_time" : "themisscan", "special_time_normal" : "twofsound", "rbsp_time" : "rbspscan", "no_switching_time" : "normalscan", "interleaved_time" : "interleavedscan" }, "inv" : { "common_time" : "normalscan", "discretionary_time" : "normalscan", "htr_common_time" : "normalscan", "themis_time" : "themisscan", "special_time_normal" : "normalscan", "rbsp_time" : "rbspscan", "no_switching_time" : "normalscan", "interleaved_time" : "interleavedscan" }, "cly" : { "common_time" : "normalscan", "discretionary_time" : "normalscan", "htr_common_time" : "normalscan", "themis_time" : "themisscan", "special_time_normal" : "normalscan", "rbsp_time" : "rbspscan", "no_switching_time" : "normalscan", "interleaved_time" : "interleavedscan" } } class SWG(object): """Holds the data needed for processing a SWG file. Attributes: scd_dir (str): Path to the SCD files dir. """ def __init__(self, scd_dir): super(SWG, self).__init__() self.scd_dir = scd_dir try: cmd = "git -C {}/{} rev-parse".format(self.scd_dir, SWG_GIT_REPO_DIR) sp.check_output(cmd, shell=True) except sp.CalledProcessError as e: cmd = 'cd {}; git clone {}'.format(self.scd_dir, SWG_GIT_REPO) sp.call(cmd, shell=True) def new_swg_file_available(self): """Checks if a new swg file is uploaded via git. Returns: TYPE: True, if new git update is available. """ # This command will return the number of new commits available in master. This signals that # there are new SWG files available. cmd = "cd {}/{}; git fetch; git log ..origin/master --oneline | wc -l".format(self.scd_dir, SWG_GIT_REPO_DIR) shell_output = sp.check_output(cmd, shell=True) return bool(int(shell_output)) def pull_new_swg_file(self): """Uses git to grab the new scd updates. """ cmd = "cd {}/{}; git pull origin master".format(self.scd_dir, SWG_GIT_REPO_DIR) sp.call(cmd, shell=True) def get_next_month(self): """Finds the datetime of the next month. Returns: TYPE: datetime object. """ today = datetime.datetime.utcnow() counter = 1 new_date = today + datetime.timedelta(days=counter) while new_date.month == today.month: counter += 1 new_date = today + datetime.timedelta(days=counter) return new_date def parse_swg_to_scd(self, modes, radar, first_run): """Reads the new SWG file and parses into a set of parameters than can be used for borealis scheduling. Args: modes (Dict): Holds the modes that correspond to the SWG requests. radar (String): Radar acronym. Returns: TYPE: List of all the parsed parameters. """ if first_run: month_to_use = datetime.datetime.utcnow() else: month_to_use = next_month = self.get_next_month() year = month_to_use.strftime("%Y") month = month_to_use.strftime("%m") swg_file = "{scd_dir}/{swg_dir}/{yyyy}/{yyyymm}.swg".format(scd_dir=self.scd_dir, swg_dir=SWG_GIT_REPO_DIR, yyyy=year, yyyymm=year+month) with open(swg_file, 'r') as f: swg_lines = f.readlines() skip_line = False parsed_params = [] for idx,line in enumerate(swg_lines): # Skip line is used for special time radar lines if skip_line: skip_line = False continue # We've hit the SCD notes and no longer need to parse if "# Notes:" in line: break # Skip only white space lines if not line.strip(): continue #Lines starting with '#' are comments if line[0] == "#": continue items = line.split() #First line is month and year if idx == 0: continue start_day = items[0][0:2] start_hr = items[0][3:] end_day = items[1][0:2] end_hr = items[1][3:] if "Common Time" in line: mode_type = "common" # 2018 11 23 no longer scheduling twofsound as common time. if "no switching" in line: mode_to_use = modes["no_switching_time"] else: mode_to_use = modes["htr_common_time"] if "Special Time" in line: mode_type = "special" if "ALL" in line or radar.upper() in line: if "THEMIS" in line: mode_to_use = modes["themis_time"] elif "ST-APOG" in line or "RBSP" in line: mode_to_use = modes["rbsp_time"] elif "ARASE" in line: if "themis" in swg_lines[idx+1]: mode_to_use = modes["themis_time"] if "interleaved" in swg_lines[idx+1]: mode_to_use = modes["interleaved_time"] else: print("Unknown Special Time: using default common time") mode_to_use = modes["htr_common_time"] else: mode_to_use = modes["special_time_normal"] # Skip next line #skip_line = True if "Discretionary Time" in line: mode_type = "discretionary" mode_to_use = modes["discretionary_time"] param = {"yyyymmdd": "{}{}{}".format(year, month, start_day), "hhmm" : "{}:00".format(start_hr), "experiment" : mode_to_use, "scheduling_mode" : mode_type} parsed_params.append(param) return parsed_params def main(): parser = argparse.ArgumentParser(description="Automatically schedules new events from the SWG") parser.add_argument('--emails-filepath',required=True, help='A list of emails to send logs to') parser.add_argument('--scd-dir', required=True, help='The scd working directory') parser.add_argument('--first-run', action="store_true", help='This will generate the first set' ' of schedule files if running on' ' a fresh directory. If the next' ' month schedule is available,' ' you will need to roll back the' ' SWG schedule folder back to the' ' last commit before running in' ' continuous operation.') args = parser.parse_args() scd_dir = args.scd_dir scd_logs = scd_dir + "/logs" emailer = email_utils.Emailer(args.emails_filepath) if not os.path.exists(scd_dir): os.makedirs(scd_dir) if not os.path.exists(scd_logs): os.makedirs(scd_logs) sites = list(EXPERIMENTS.keys()) site_scds = [scd_utils.SCDUtils("{}/{}.scd".format(scd_dir, s)) for s in sites] swg = SWG(scd_dir) while True: if swg.new_swg_file_available() or args.first_run: swg.pull_new_swg_file() site_experiments = [swg.parse_swg_to_scd(EXPERIMENTS[s], s, args.first_run) for s in sites] errors = False today = datetime.datetime.utcnow() scd_error_log = today.strftime("/scd_errors.%Y%m%d") for se, site_scd in zip(site_experiments, site_scds): for ex in se: try: site_scd.add_line(ex['yyyymmdd'], ex['hhmm'], ex['experiment'], ex["scheduling_mode"]) except ValueError as e: error_msg = ("{logtime} {sitescd}: Unable to add line with parameters:\n" "\t {date} {time} {experiment} {mode}\n" "\t Exception thrown:\n" "\t\t {exception}\n") error_msg = error_msg.format(logtime=today.strftime("%c"), sitescd=site_scd.scd_filename, date=ex['yyyymmdd'], time=ex['hhmm'], experiment=ex['experiment'], mode=ex['scheduling_mode'], exception=str(e)) with open(scd_logs + scd_error_log, 'a') as f: f.write(error_msg) errors = True break except FileNotFoundError as e: error_msg = "SCD filename: {} is missing!!!\n".format(site_scd.scd_filename) with open(scd_logs + scd_error_log, 'a') as f: f.write(error_msg) errors = True break subject = "Scheduling report for swg lines" if not errors: success_msg = "All swg lines successfully scheduled.\n" for site, site_scd in zip(sites, site_scds): yyyymmdd = today.strftime("%Y%m%d") hhmm = today.strftime("%H:%M") new_lines = site_scd.get_relevant_lines(yyyymmdd, hhmm) text_lines = [site_scd.fmt_line(x) for x in new_lines] success_msg += "\t{}\n".format(site) for line in text_lines: success_msg += "\t\t{}\n".format(line) with open(scd_logs + scd_error_log, 'a') as f: f.write(success_msg) else: errors = False emailer.email_log(subject, scd_logs + scd_error_log) if args.first_run: break; else: time.sleep(300) if __name__ == '__main__': main()
gpl-3.0
inpfss/my-code-work
NET/SantechinaSucher/ConsoleApplication2/Program.cs
8592
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using HtmlAgilityPack; namespace ConsoleApplication2 { class DushOptions { public string Name { get; set; } public string Url { get; set; } public string Size { get; set; } public string Glass { get; set; } public string GlassType { get; set; } public string Features { get; set; } } class Program { private static Func<HtmlDocument, string> getName = doc => { return doc .DocumentNode .Descendants("h2") .FirstOrDefault(n => n.Attributes.Any(a => a.Name == "class" && a.Value == "detail_h2")) ?.InnerText; }; static Func<HtmlDocument, string> getSize = doc => { return doc .DocumentNode .Descendants("tr") .Where(trNode => trNode.Descendants("td").First().InnerText == "Розмір") .Select(trNode => trNode.Descendants("td").Last().InnerText.Trim()) .FirstOrDefault(); }; static Func<HtmlDocument, string> getGlassType = doc => { return doc .DocumentNode .Descendants("tr") .Where(trNode => trNode.Descendants("td").First().InnerText == "Скло") .Select(trNode => trNode.Descendants("td").Last().InnerText.Trim()) .FirstOrDefault(); }; static Func<HtmlDocument, string> getGlassDescription = doc => { return doc .DocumentNode .Descendants("tr") .Where(trNode => trNode.Descendants("td").First().InnerText == "Колір скла") .Select(trNode => trNode.Descendants("td").Last().InnerText.Trim()) .FirstOrDefault(); }; static Func<HtmlDocument, string> getBoxFeatures = doc => { return HttpUtility.HtmlDecode(doc .DocumentNode .Descendants("div") .Where(div => div.Attributes.Any(a => a.Name == "class" && a.Value == "description") && div.Descendants("p").Count() > 1) .Select(div => div.Descendants("p").Last().InnerText.Trim()) .FirstOrDefault()); }; static void Main(string[] args) { if (args.Length == 0) { args = new[] { "масаж спини", "масаж ніг", }; } Thread.CurrentThread.CurrentCulture = new CultureInfo("uk-UA"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("uk-UA"); for (int i = 0; i < args.Length; i++) { args[i] = args[i].ToUpper(); } Console.InputEncoding = Encoding.Unicode; Console.OutputEncoding = Encoding.Unicode; List<DushOptions> dushes = new List<DushOptions>(); List<string> sizes = new List<string>(); List<Tuple<string, string>> glassDescriptions = new List<Tuple<string, string>>(); List<string> glassTypes = new List<string>(); List<string> dushUrls = new List<string>(); for (int pageId = 1; pageId <= 2; pageId++) { string Url = $"http://santehnika.lviv.ua/catalog/206?page={pageId}"; HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load(Url); List<HtmlNode> dushItems = doc.DocumentNode.Descendants("div") .Where(n => n.Attributes.Any(a => a.Name == "class" && a.Value.Contains("category_item one-four inl vtop"))) .ToList(); foreach (HtmlNode hotelHeader in dushItems) { try { var dushOptions = new DushOptions(); string dushUrl = hotelHeader.Descendants("a") .FirstOrDefault() ?.GetAttributeValue("href", null); if (string.IsNullOrWhiteSpace(dushUrl)) { continue; } dushOptions.Url = dushUrl; HtmlWeb dushPage = new HtmlWeb(); HtmlDocument dushDoc = dushPage.Load(dushUrl); string dushSizes = getSize(dushDoc); sizes.Add(dushSizes); dushOptions.Size = dushSizes; string dushName = getName(dushDoc); string glassDescription = getGlassDescription(dushDoc); glassDescriptions.Add(new Tuple<string, string>(glassDescription, dushUrl)); dushOptions.Name = dushName; dushOptions.Glass = glassDescription; string glassType = getGlassType(dushDoc); glassTypes.Add(glassType); dushOptions.GlassType = glassType; string boxFeatures = getBoxFeatures(dushDoc)?.ToUpper(); dushOptions.Features = boxFeatures; dushes.Add(dushOptions); //if (boxFeatures != null && args.All(feature => boxFeatures.Contains(feature))) //{ // if (dushDoc.DocumentNode.InnerText.ToLower().Contains("мат")) // { // dushUrls.Add(dushUrl); // Console.WriteLine(dushName); // Console.WriteLine( // $"розмір: {dushSizes};\nтип скла: {glassType};\nколір скла: {glassDescription};\nфункції: {boxFeatures}"); // Console.WriteLine(); // Console.WriteLine(new string('*', 30)); // } } } catch (Exception ex) { Console.WriteLine("Error."); } } } /* Console.WriteLine(); Console.WriteLine($"Знайдено {dushUrls.Count} гідробоксів."); Console.WriteLine(); Console.WriteLine("Всі розміри:"); sizes.Distinct().OrderBy(s => s).ToList().ForEach(Console.WriteLine); Console.WriteLine(); Console.WriteLine("Всі типи скла гідробоксів:"); glassTypes.Distinct().OrderBy(s => s).ToList().ForEach(Console.WriteLine); Console.WriteLine(); Console.WriteLine("Всі кольори гідробоксів:"); glassDescriptions.Distinct(new Comp()).OrderBy(s => s).ToList().ForEach(Console.WriteLine); */ var foundedDushes = dushes.Where(x => x.Glass == "матове" || x.GlassType == "матове").ToList(); foreach (DushOptions dushOptionse in foundedDushes) { Console.WriteLine(dushOptionse.Name); Console.WriteLine(dushOptionse.Url); Console.WriteLine(dushOptionse.Features); Console.WriteLine(dushOptionse.Size); Console.WriteLine(dushOptionse.Glass); Console.WriteLine(dushOptionse.GlassType); } File.WriteAllText( "matchedDhushes.txt", string.Join(Environment.NewLine, foundedDushes.Select(x => x.Url).ToList()) ); Console.ReadLine(); } class Comp : IEqualityComparer<Tuple<String, String>> { public bool Equals(Tuple<string, string> x, Tuple<string, string> y) { return GetHashCode(x) == GetHashCode(y); } public int GetHashCode(Tuple<string, string> obj) => obj?.Item1?.GetHashCode() ?? 0; } } }
gpl-3.0
Norman0406/LISA-old
src/logbook/database/QSOEntry.cpp
2188
/*********************************************************************** * * LISA: Lightweight Integrated System for Amateur Radio * Copyright (C) 2013 Norman Link <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***********************************************************************/ #include "QSOEntry.h" #include "QSOField.h" namespace logbook { QSOEntry::QSOEntry() { initStandardFields(); } QSOEntry::~QSOEntry() { clear(); } void QSOEntry::clear() { clear(m_standardFields); clear(m_additionalFields); } void QSOEntry::clear(QVector<QSOFieldBase*>& fields) { for (int i = 0; i < fields.size(); i++) delete fields[i]; fields.clear(); } void QSOEntry::addField(const QSOFieldBase& field) { addField(field, m_additionalFields); } void QSOEntry::addField(const QSOFieldBase& field, QVector<QSOFieldBase*>& fields) { Q_UNUSED(field); Q_UNUSED(fields); } void QSOEntry::initStandardFields() { addField(QSOField<QDate>("Date")); addField(QSOField<QTime>("Start")); addField(QSOField<QTime>("End")); addField(QSOField<QString>("Callsign")); addField(QSOField<int>("RSTsent")); addField(QSOField<int>("RSTrcvd")); addField(QSOField<float>("Freq")); addField(QSOField<QString>("Mode")); addField(QSOField<QString>("Country")); addField(QSOField<QString>("Locator")); addField(QSOField<QString>("Comment")); } }
gpl-3.0
ISRAPIL/FastCorePE
src/pocketmine/level/sound/AnvilFallSound.php
321
<?php namespace pocketmine\level\sound; use pocketmine\math\Vector3; use pocketmine\network\protocol\LevelEventPacket; class AnvilFallSound extends GenericSound { public function __construct(Vector3 $pos, $pitch = 0) { parent::__construct($pos, LevelEventPacket::EVENT_SOUND_ANVIL_FALL, $pitch); } }
gpl-3.0
JohannesBuchner/PyDNest
diffusivenested.py
11913
""" Pure Python implementation of Diffusive Nested Sampling. Uses postprocess Python code from DNest3 (make sure it is in your PYTHONPATH) """ import numpy from numpy import exp, log, log10, pi class Level(object): def __init__(self, logX, cutoff, accepts=0, tries=0, visits=0, exceeds=0): self.cutoff = cutoff self.logX = logX self.accepts = accepts self.tries = tries self.visits = visits self.exceeds = exceeds def renormaliseVisits(self, regularisation): if self.tries >= regularisation: self.accepts = ((self.accepts + 1.)/(self.tries + 1.)) * regularisation self.tries = regularisation if self.visits >= regularisation: self.exceeds = ((self.exceeds + 1.)/(self.visits + 1.)) * regularisation self.visits = regularisation def incrementVisits(self, incrementExceeds): self.visits += 1 if incrementExceeds: self.exceeds += 1 def incrementTries(self, accepted): self.tries += 1 if accepted: self.accepts += 1 def __add__(self, other): assert self.logX == other.logX and self.cutoff == other.cutoff self.tries += other.tries self.accepts += other.accepts self.visits += other.visits self.exceeds += other.exceeds def __sub__(self, other): assert self.logX == other.logX and self.cutoff == other.cutoff self.tries -= other.tries self.accepts -= other.accepts self.visits -= other.visits self.exceeds -= other.exceeds def __lt__(self, other): raise NotImplementedError() def __gt__(self, other): raise NotImplementedError() def __eq__(self, other): raise NotImplementedError() def __ne__(self, other): raise NotImplementedError() def __mul__(self, other): raise NotImplementedError() def __div__(self, other): raise NotImplementedError() def recalculateLogX(levels, compression, regularisation): assert len(levels) > 0 levels[0].logX = 0. lastlevel = levels[0] for l in levels[1:]: f = log((lastlevel.exceeds + regularisation*1. / compression) / (lastlevel.visits + regularisation)) l.logX = lastlevel.logX + f lastlevel = l def renormaliseVisits(levels, regularisation): for l in levels: l.renormaliseVisits(regularisation) def binaryCoin(): return numpy.random.randint(2) == 0 class DiffusiveSampler(object): def __init__(self, priortransform, loglikelihood, draw_constrained, ndim, nlive_points = 1, # number of particles compression = numpy.e, histogramForce = 5, # beta maxLevels = 5, newLevelInterval=100, backtrackScale = 10, # lambda numParticles = 1, stepInterval = 100 # number of iterations before returning as sample ): self.nlive_points = nlive_points self.beta = histogramForce self.lam = backtrackScale self.compression = compression self.priortransform = priortransform self.loglikelihood = loglikelihood self.draw_constrained = draw_constrained self.maxLevels = maxLevels self.newLevelInterval = newLevelInterval self.saveInterval = stepInterval # store after this many steps self.levels = [Level(logX=0., cutoff=-1e300)] self.indices = [] # which level a point belongs to self.samples = [] self.keep = [] # loglikelihoods which are not accepted self.ndim = ndim # draw N starting points from prior live_pointsu = [None] * nlive_points # particles live_pointsx = [None] * nlive_points live_pointsL = numpy.empty(nlive_points) # logL for i in range(nlive_points): u = numpy.random.uniform(0, 1, size=ndim) assert len(u) == ndim, (u, ndim) x = priortransform(u) assert len(x) == ndim, (x, ndim) L = loglikelihood(x) live_pointsu[i], live_pointsx[i], live_pointsL[i] = u, x, L self.samples.append([u, x, L]) self.keep.append(L) self.indices.append(0) self.live_pointsu = live_pointsu self.live_pointsx = live_pointsx self.live_pointsL = live_pointsL self.Lmax = self.live_pointsL.max() def __next__(self): for i in range(self.saveInterval): # choose random particle to move which = numpy.random.randint(self.nlive_points) if binaryCoin(): self.updateParticle(which) self.updateIndex(which) else: self.updateIndex(which) self.updateParticle(which) # Accumulate visits, exceeds # move up in levels if necessary Li = self.live_pointsL[which] for index in range(self.indices[which], len(self.levels) - 1): exceeds = self.levels[index + 1].cutoff < Li self.levels[index].incrementVisits(exceeds) if not exceeds: break # Accumulate likelihoods for making a new level if len(self.levels) < self.maxLevels and self.levels[-1].cutoff < Li: self.keep.append(Li) # bookKeeping: if len(self.keep) > self.newLevelInterval: self.keep.sort() ii = int((1. - 1. / self.compression) * len(self.keep)) cutoff = self.keep[ii] print "# Creating level %d with logL = %.5f." % (len(self.levels), cutoff) self.levels.append(Level(self.levels[-1].logX - 1., cutoff)) if len(self.levels) == self.maxLevels: self.keep = [] renormaliseVisits(self.levels, self.newLevelInterval) else: self.keep = self.keep[ii + 1:] recalculateLogX(self.levels, self.compression, 100) self.deleteParticle() sample = self.live_pointsu[which] sampleInfo = self.indices[which], self.live_pointsL[which], numpy.random.uniform(), which recalculateLogX(self.levels, self.compression, 100) return sample, sampleInfo def logPush(self, index): assert index >= 0 and index < len(self.levels) if len(self.levels) == self.maxLevels: return 0 i = index - (len(self.levels) - 1) return i * 1. / self.lam def deleteParticle(self): # Flag each particle as good or bad bad = [self.logPush(self.indices[i]) < -5. for i in range(self.nlive_points)] nbad = sum(bad) assert nbad < self.nlive_points, "# Warning: all particles lagging! Very rare!" # Replace bad particles with copies of good ones to_replace = [i for i, isbad in enumerate(bad) if isbad] for i in to_replace: copy = i while bad[copy]: copy = numpy.random.randInt(self.nlive_points); self.live_pointsu[i], self.live_pointsx[i], self.live_pointsL[i] = \ self.live_pointsu[copy], self.live_pointsx[copy], self.live_pointsL[copy] print "# Deleting a particle. Replacing it with a copy of a good survivor." def updateParticle(self, which): # Copy the particle # Perturb the proposal particle uj, xj, Lj = self.draw_constrained( Lmin = None, # we want to get the accept priortransform=self.priortransform, loglikelihood=self.loglikelihood, previous=self.samples, ndim=self.ndim, startu = self.live_pointsu[which], startx = self.live_pointsx[which], startL = self.live_pointsL[which]) self.Lmax = max(Lj, self.Lmax) self.samples.append([uj, xj, Lj]) accepted = self.levels[self.indices[which]].cutoff < Lj if accepted: # accept self.live_pointsu[which] = uj self.live_pointsx[which] = xj self.live_pointsL[which] = Lj #print 'draw accepted', Lj, self.levels[self.indices[which]].cutoff self.levels[self.indices[which]].incrementTries(accepted) def updateIndex(self, which): index = self.indices[which] u = (10.**(2*numpy.random.uniform()) * numpy.random.normal()) offset = int(numpy.round(u)) proposedIndex = index + offset if proposedIndex == index: proposedIndex = proposedIndex + 1 if binaryCoin() else proposedIndex - 1 if proposedIndex < 0 or proposedIndex >= len(self.levels): return if self.levels[proposedIndex].cutoff >= self.live_pointsL[which]: # can not ascend return # Acceptance probability. logX part logA = self.levels[index].logX - self.levels[proposedIndex].logX # Pushing up part logA += self.logPush(proposedIndex) - self.logPush(index) # Enforce uniform exploration part (if all levels exist) if len(self.levels) == self.maxLevels: logA += self.beta * log((self.levels[index].tries + 1.) / (self.levels[proposedIndex].tries + 1.)) # Prevent exponentiation of huge numbers logA = min(0, logA) if numpy.random.uniform() <= exp(logA): # Accept! self.indices[which] = proposedIndex def store(self, which): with open('sample_info.txt', 'w') as f: f.write("# index, logLikelihood, tieBreaker, ID.\n") numpy.savetxt(f, self.samplesInfo, fmt='%d %e %f %d') with open('sample.txt', 'w') as f: f.write("# Samples file. One sample per line.\n") numpy.savetxt(f, self.samples) levels = numpy.array([ [l.logX, l.cutoff, numpy.random.uniform(), l.accepts, l.tries, l.exceeds, l.visits] for l in self.levels]) with open('levels.txt', 'w') as f: f.write("# Samples file. One sample per line.\n") numpy.savetxt(f, levels, fmt='%e %e %f %d %d %d %d') def next(self): return self.__next__() def __iter__(self): while True: yield self.__next__() def mcmc_draw(Lmin, priortransform, loglikelihood, ndim, startu, startx, startL, **kwargs): while True: # just make a proposal (non-romantic, platonic only) u = numpy.copy(startu) i = numpy.random.randint(ndim) p = u[i] p += 10**(1.5 - 6 * numpy.random.uniform(0,1)) * numpy.random.normal(0, 1); # wrap around: u[i] = p - numpy.floor(p) x = priortransform(u) L = loglikelihood(u) #print 'MCMC: %f -> %f, like %s -> %f' % (startu[i], u[i], Lmin, L) if Lmin is None or L > Lmin: return u, x, L import postprocess #import progressbar def diffusive_integrator(sampler, tolerance = 0.01): # sample from sampler samples = [] # coordinates samplesInfo = [] # logX, likelihood, (tieBreaker), livePointID finfo = open('sample_info.txt', 'w') finfo.write("# index, logLikelihood, tieBreaker, ID.\n") #numpy.savetxt(f, self.samplesInfo, fmt='%d %e %f %d') fsample = open('sample.txt', 'w') fsample.write("# Samples file. One sample per line.\n") #numpy.savetxt(f, self.samples) for i in range(1000): # keep sampling sample, sampleInfo = sampler.next() print 'new sample:', sample, sampleInfo # each sample file contains one line per live point / particle # sampleFile :: self.live_pointsu # sampleInfoFile :: self.indices, self.live_pointsL, (tieBreaker), ID? # levelFile :: logX, cutoff, (tieBreaker), accepts, tries, exceeds, visits # adding an extra number because postprocess can't deal with 1d data fsample.write(' '.join(['%e' % s for s in sample]) + " 1\n") fsample.flush() finfo.write("%d %e %f %d\n" % sampleInfo) finfo.flush() samples.append(sample) samplesInfo.append(sampleInfo) levels = numpy.array([[l.logX, l.cutoff, numpy.random.uniform(), l.accepts, l.tries, l.exceeds, l.visits] for l in sampler.levels]) flevels = open('levels.txt', 'w') flevels.write("# logX, logLikelihood, tieBreaker, accepts, tries, exceeds, visits.\n") numpy.savetxt(flevels, levels, fmt='%f %e %f %d %d %d %d') flevels.close() if i % 20 == 19: # check if tolerance achieved already logZ, H, weights, logZerr = postprocess.postprocess( loaded=(levels, numpy.asarray(samplesInfo), numpy.asarray(samples)), save=False, plot=False, verbose=False, numResampleLogX=10) print 'logZ = %.3f +- %.3f' % (logZ, logZerr) if logZerr < tolerance / 3: break return dict(logZ=logZ, logZerr=logZerr, samples=sampler.samples, weights=weights, information=H) if __name__ == '__main__': import scipy.stats def priortransform(u): return u ndim = 1 rv = scipy.stats.norm([0.654321]*ndim, [0.01]*ndim) def loglikelihood(x): #a = - 0.5 * ((x - 0.2)/0.05)**2 - 0.5 * log(2*pi*0.05**2) #b = - 0.5 * ((x - 0.7)/0.05)**2 - 0.5 * log(2*pi*0.05**2) #l = log(exp(a) + exp(b) + 0.01e-100) #print 'loglike:', x, l l = rv.logpdf(x).sum() return float(l) constrainer = mcmc_draw print 'preparing sampler' sampler = DiffusiveSampler(nlive_points = 1, priortransform=priortransform, loglikelihood=loglikelihood, draw_constrained = constrainer, ndim=1) print 'running sampler' result = diffusive_integrator(tolerance=0.01, sampler=sampler)
gpl-3.0
ncantu/socialNetWork
lib/_toDelete/NotificationTitle.php
57
<?php class NotificationTitle extends Title { } ?>
gpl-3.0
PanzerKunst/redesigned-cruited.com-frontend
rater-ui/app/models/Coupon.scala
1157
package models import play.api.libs.functional.syntax._ import play.api.libs.json.{Format, JsPath} case class Coupon(id: Long, code: String, campaignName: String, expirationTimestamp: Long, discountPercentage: Option[Int], discountPrice: Option[Price], `type`: Int, maxUseCount: Int, couponExpiredMsg: Option[String]) object Coupon { implicit val format: Format[Coupon] = ( (JsPath \ "id").format[Long] and (JsPath \ "code").format[String] and (JsPath \ "campaignName").format[String] and (JsPath \ "expirationTimestamp").format[Long] and (JsPath \ "discountPercentage").formatNullable[Int] and (JsPath \ "discountPrice").formatNullable[Price] and (JsPath \ "type").format[Int] and (JsPath \ "maxUseCount").format[Int] and (JsPath \ "couponExpiredMsg").formatNullable[String] )(Coupon.apply, unlift(Coupon.unapply)) val typeNoRestriction = 0 val typeSingleUse = 1 val typeTwoUses = 2 val typeOncePerAccount = 3 val typeNUsesPerAccount = 4 }
gpl-3.0
erikzenker/alpaka-examples
alpaka/include/alpaka/exec/ExecCpuFibers.hpp
19984
/** * \file * Copyright 2014-2015 Benjamin Worpitz * * This file is part of alpaka. * * alpaka 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. * * alpaka 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 alpaka. * If not, see <http://www.gnu.org/licenses/>. */ #pragma once // Specialized traits. #include <alpaka/acc/Traits.hpp> // acc::traits::AccType #include <alpaka/dev/Traits.hpp> // dev::traits::DevType #include <alpaka/dim/Traits.hpp> // dim::traits::DimType #include <alpaka/exec/Traits.hpp> // exec::traits::ExecType #include <alpaka/size/Traits.hpp> // size::traits::SizeType // Implementation details. #include <alpaka/acc/AccCpuFibers.hpp> // acc:AccCpuFibers #include <alpaka/dev/DevCpu.hpp> // dev::DevCpu #include <alpaka/kernel/Traits.hpp> // kernel::getBlockSharedExternMemSizeBytes #include <alpaka/workdiv/WorkDivMembers.hpp> // workdiv::WorkDivMembers #include <alpaka/core/Fibers.hpp> #include <alpaka/core/ConcurrentExecPool.hpp> // core::ConcurrentExecPool #include <alpaka/core/NdLoop.hpp> // core::NdLoop #include <alpaka/core/ApplyTuple.hpp> // core::Apply #include <boost/predef.h> // workarounds #include <boost/align.hpp> // boost::aligned_alloc #include <algorithm> // std::for_each #include <vector> // std::vector #include <tuple> // std::tuple #include <type_traits> // std::decay #if ALPAKA_DEBUG >= ALPAKA_DEBUG_MINIMAL #include <iostream> // std::cout #endif namespace alpaka { namespace exec { //############################################################################# //! The CPU fibers accelerator executor. //############################################################################# template< typename TDim, typename TSize, typename TKernelFnObj, typename... TArgs> class ExecCpuFibers final : public workdiv::WorkDivMembers<TDim, TSize> { private: //############################################################################# //! The type given to the ConcurrentExecPool for yielding the current fiber. //############################################################################# struct FiberPoolYield { //----------------------------------------------------------------------------- //! Yields the current fiber. //----------------------------------------------------------------------------- ALPAKA_FN_ACC_NO_CUDA static auto yield() -> void { boost::this_fiber::yield(); } }; //############################################################################# // Yielding is not faster for fibers. Therefore we use condition variables. // It is better to wake them up when the conditions are fulfilled because this does not cost as much as for real threads. //############################################################################# using FiberPool = alpaka::core::detail::ConcurrentExecPool< TSize, boost::fibers::fiber, // The concurrent execution type. boost::fibers::promise, // The promise type. FiberPoolYield, // The type yielding the current concurrent execution. boost::fibers::mutex, // The mutex type to use. Only required if TisYielding is true. boost::fibers::condition_variable, // The condition variable type to use. Only required if TisYielding is true. false>; // If the threads should yield. public: //----------------------------------------------------------------------------- //! Constructor. //----------------------------------------------------------------------------- template< typename TWorkDiv> ALPAKA_FN_HOST ExecCpuFibers( TWorkDiv && workDiv, TKernelFnObj const & kernelFnObj, TArgs const & ... args) : workdiv::WorkDivMembers<TDim, TSize>(std::forward<TWorkDiv>(workDiv)), m_kernelFnObj(kernelFnObj), m_args(args...) { static_assert( dim::Dim<typename std::decay<TWorkDiv>::type>::value == TDim::value, "The work division and the executor have to be of the same dimensionality!"); } //----------------------------------------------------------------------------- //! Copy constructor. //----------------------------------------------------------------------------- ALPAKA_FN_HOST ExecCpuFibers(ExecCpuFibers const &) = default; //----------------------------------------------------------------------------- //! Move constructor. //----------------------------------------------------------------------------- ALPAKA_FN_HOST ExecCpuFibers(ExecCpuFibers &&) = default; //----------------------------------------------------------------------------- //! Copy assignment operator. //----------------------------------------------------------------------------- ALPAKA_FN_HOST auto operator=(ExecCpuFibers const &) -> ExecCpuFibers & = default; //----------------------------------------------------------------------------- //! Move assignment operator. //----------------------------------------------------------------------------- ALPAKA_FN_HOST auto operator=(ExecCpuFibers &&) -> ExecCpuFibers & = default; //----------------------------------------------------------------------------- //! Destructor. //----------------------------------------------------------------------------- ALPAKA_FN_HOST ~ExecCpuFibers() = default; //----------------------------------------------------------------------------- //! Executes the kernel function object. //----------------------------------------------------------------------------- ALPAKA_FN_HOST auto operator()() const -> void { ALPAKA_DEBUG_MINIMAL_LOG_SCOPE; auto const gridBlockExtents( workdiv::getWorkDiv<Grid, Blocks>(*this)); auto const blockThreadExtents( workdiv::getWorkDiv<Block, Threads>(*this)); // Get the size of the block shared extern memory. auto const blockSharedExternMemSizeBytes( core::apply( [&](TArgs const & ... args) { return kernel::getBlockSharedExternMemSizeBytes< TKernelFnObj, acc::AccCpuFibers<TDim, TSize>>( blockThreadExtents, args...); }, m_args)); #if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL std::cout << BOOST_CURRENT_FUNCTION << " BlockSharedExternMemSizeBytes: " << blockSharedExternMemSizeBytes << " B" << std::endl; #endif acc::AccCpuFibers<TDim, TSize> acc(*static_cast<workdiv::WorkDivMembers<TDim, TSize> const *>(this)); if(blockSharedExternMemSizeBytes > 0u) { acc.m_externalSharedMem.reset( reinterpret_cast<uint8_t *>( boost::alignment::aligned_alloc(16u, blockSharedExternMemSizeBytes))); } auto const numThreadsInBlock(blockThreadExtents.prod()); FiberPool fiberPool(numThreadsInBlock, numThreadsInBlock); auto const boundGridBlockExecHost( core::apply( [this, &acc, &blockThreadExtents, &fiberPool](TArgs const & ... args) { // Bind the kernel and its arguments to the grid block function. return std::bind( &ExecCpuFibers<TDim, TSize, TKernelFnObj, TArgs...>::gridBlockExecHost, std::ref(acc), std::placeholders::_1, std::ref(blockThreadExtents), std::ref(fiberPool), std::ref(m_kernelFnObj), std::ref(args)...); }, m_args)); // Execute the blocks serially. core::ndLoopIncIdx( gridBlockExtents, boundGridBlockExecHost); // After all blocks have been processed, the external shared memory has to be deleted. acc.m_externalSharedMem.reset(); } private: //----------------------------------------------------------------------------- //! The function executed for each grid block. //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto gridBlockExecHost( acc::AccCpuFibers<TDim, TSize> & acc, Vec<TDim, TSize> const & gridBlockIdx, Vec<TDim, TSize> const & blockThreadExtents, FiberPool & fiberPool, TKernelFnObj const & kernelFnObj, TArgs const & ... args) -> void { // The futures of the threads in the current block. std::vector<boost::fibers::future<void>> futuresInBlock; // Set the index of the current block acc.m_gridBlockIdx = gridBlockIdx; // Bind the kernel and its arguments to the host block thread execution function. auto boundBlockThreadExecHost(std::bind( &ExecCpuFibers<TDim, TSize, TKernelFnObj, TArgs...>::blockThreadExecHost, std::ref(acc), std::ref(futuresInBlock), std::placeholders::_1, std::ref(fiberPool), std::ref(kernelFnObj), std::ref(args)...)); // Execute the block threads in parallel. core::ndLoopIncIdx( blockThreadExtents, boundBlockThreadExecHost); // Wait for the completion of the block thread kernels. std::for_each( futuresInBlock.begin(), futuresInBlock.end(), [](boost::fibers::future<void> & t) { t.wait(); } ); // Clean up. futuresInBlock.clear(); acc.m_fibersToIndices.clear(); acc.m_fibersToBarrier.clear(); // After a block has been processed, the shared memory has to be deleted. block::shared::freeMem(acc); } //----------------------------------------------------------------------------- //! The function executed for each block thread. //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto blockThreadExecHost( acc::AccCpuFibers<TDim, TSize> & acc, std::vector<boost::fibers::future<void>> & futuresInBlock, Vec<TDim, TSize> const & blockThreadIdx, FiberPool & fiberPool, TKernelFnObj const & kernelFnObj, TArgs const & ... args) -> void { // Bind the arguments to the accelerator block thread execution function. // The blockThreadIdx is required to be copied in because the variable will get changed for the next iteration/thread. auto boundBlockThreadExecAcc( [&, blockThreadIdx]() { blockThreadFiberFn( acc, blockThreadIdx, kernelFnObj, args...); }); // Add the bound function to the block thread pool. futuresInBlock.emplace_back( fiberPool.enqueueTask( boundBlockThreadExecAcc)); } //----------------------------------------------------------------------------- //! The fiber entry point. //----------------------------------------------------------------------------- ALPAKA_FN_HOST static auto blockThreadFiberFn( acc::AccCpuFibers<TDim, TSize> & acc, Vec<TDim, TSize> const & blockThreadIdx, TKernelFnObj const & kernelFnObj, TArgs const & ... args) -> void { // We have to store the fiber data before the kernel is calling any of the methods of this class depending on them. auto const fiberId(boost::this_fiber::get_id()); // Set the master thread id. if(blockThreadIdx.sum() == 0) { acc.m_masterFiberId = fiberId; } // We can not use the default syncBlockThreads here because it searches inside m_fibersToBarrier for the thread id. // Concurrently searching while others use emplace is unsafe! typename std::map<boost::fibers::fiber::id, TSize>::iterator itFiberToBarrier; // Save the fiber id, and index. acc.m_fibersToIndices.emplace(fiberId, blockThreadIdx); itFiberToBarrier = acc.m_fibersToBarrier.emplace(fiberId, 0).first; // Sync all threads so that the maps with thread id's are complete and not changed after here. acc.syncBlockThreads(itFiberToBarrier); // Execute the kernel itself. kernelFnObj( const_cast<acc::AccCpuFibers<TDim, TSize> const &>(acc), args...); // We have to sync all fibers here because if a fiber would finish before all fibers have been started, the new fiber could get a recycled (then duplicate) fiber id! acc.syncBlockThreads(itFiberToBarrier); } TKernelFnObj m_kernelFnObj; std::tuple<TArgs...> m_args; }; } namespace acc { namespace traits { //############################################################################# //! The CPU fibers executor accelerator type trait specialization. //############################################################################# template< typename TDim, typename TSize, typename TKernelFnObj, typename... TArgs> struct AccType< exec::ExecCpuFibers<TDim, TSize, TKernelFnObj, TArgs...>> { using type = acc::AccCpuFibers<TDim, TSize>; }; } } namespace dev { namespace traits { //############################################################################# //! The CPU fibers executor device type trait specialization. //############################################################################# template< typename TDim, typename TSize, typename TKernelFnObj, typename... TArgs> struct DevType< exec::ExecCpuFibers<TDim, TSize, TKernelFnObj, TArgs...>> { using type = dev::DevCpu; }; //############################################################################# //! The CPU fibers executor device manager type trait specialization. //############################################################################# template< typename TDim, typename TSize, typename TKernelFnObj, typename... TArgs> struct DevManType< exec::ExecCpuFibers<TDim, TSize, TKernelFnObj, TArgs...>> { using type = dev::DevManCpu; }; } } namespace dim { namespace traits { //############################################################################# //! The CPU fibers executor dimension getter trait specialization. //############################################################################# template< typename TDim, typename TSize, typename TKernelFnObj, typename... TArgs> struct DimType< exec::ExecCpuFibers<TDim, TSize, TKernelFnObj, TArgs...>> { using type = TDim; }; } } namespace exec { namespace traits { //############################################################################# //! The CPU fibers executor executor type trait specialization. //############################################################################# template< typename TDim, typename TSize, typename TKernelFnObj, typename... TArgs> struct ExecType< exec::ExecCpuFibers<TDim, TSize, TKernelFnObj, TArgs...>, TKernelFnObj, TArgs...> { using type = exec::ExecCpuFibers<TDim, TSize, TKernelFnObj, TArgs...>; }; } } namespace size { namespace traits { //############################################################################# //! The CPU fibers executor size type trait specialization. //############################################################################# template< typename TDim, typename TSize, typename TKernelFnObj, typename... TArgs> struct SizeType< exec::ExecCpuFibers<TDim, TSize, TKernelFnObj, TArgs...>> { using type = TSize; }; } } }
gpl-3.0
mjfarmer/scada_py
env/lib/python2.7/site-packages/pymodbus/client/sync.py
12819
import socket import serial from pymodbus.constants import Defaults from pymodbus.factory import ClientDecoder from pymodbus.exceptions import NotImplementedException, ParameterException from pymodbus.exceptions import ConnectionException from pymodbus.transaction import FifoTransactionManager from pymodbus.transaction import DictTransactionManager from pymodbus.transaction import ModbusSocketFramer, ModbusBinaryFramer from pymodbus.transaction import ModbusAsciiFramer, ModbusRtuFramer from pymodbus.client.common import ModbusClientMixin #---------------------------------------------------------------------------# # Logging #---------------------------------------------------------------------------# import logging _logger = logging.getLogger(__name__) #---------------------------------------------------------------------------# # The Synchronous Clients #---------------------------------------------------------------------------# class BaseModbusClient(ModbusClientMixin): ''' Inteface for a modbus synchronous client. Defined here are all the methods for performing the related request methods. Derived classes simply need to implement the transport methods and set the correct framer. ''' def __init__(self, framer): ''' Initialize a client instance :param framer: The modbus framer implementation to use ''' self.framer = framer if isinstance(self.framer, ModbusSocketFramer): self.transaction = DictTransactionManager(self) else: self.transaction = FifoTransactionManager(self) #-----------------------------------------------------------------------# # Client interface #-----------------------------------------------------------------------# def connect(self): ''' Connect to the modbus remote host :returns: True if connection succeeded, False otherwise ''' raise NotImplementedException("Method not implemented by derived class") def close(self): ''' Closes the underlying socket connection ''' pass def _send(self, request): ''' Sends data on the underlying socket :param request: The encoded request to send :return: The number of bytes written ''' raise NotImplementedException("Method not implemented by derived class") def _recv(self, size): ''' Reads data from the underlying descriptor :param size: The number of bytes to read :return: The bytes read ''' raise NotImplementedException("Method not implemented by derived class") #-----------------------------------------------------------------------# # Modbus client methods #-----------------------------------------------------------------------# def execute(self, request=None): ''' :param request: The request to process :returns: The result of the request execution ''' if not self.connect(): raise ConnectionException("Failed to connect[%s]" % (self.__str__())) return self.transaction.execute(request) #-----------------------------------------------------------------------# # The magic methods #-----------------------------------------------------------------------# def __enter__(self): ''' Implement the client with enter block :returns: The current instance of the client ''' if not self.connect(): raise ConnectionException("Failed to connect[%s]" % (self.__str__())) return self def __exit__(self, klass, value, traceback): ''' Implement the client with exit block ''' self.close() def __str__(self): ''' Builds a string representation of the connection :returns: The string representation ''' return "Null Transport" #---------------------------------------------------------------------------# # Modbus TCP Client Transport Implementation #---------------------------------------------------------------------------# class ModbusTcpClient(BaseModbusClient): ''' Implementation of a modbus tcp client ''' def __init__(self, host='127.0.0.1', port=Defaults.Port, framer=ModbusSocketFramer): ''' Initialize a client instance :param host: The host to connect to (default 127.0.0.1) :param port: The modbus port to connect to (default 502) :param framer: The modbus framer to use (default ModbusSocketFramer) .. note:: The host argument will accept ipv4 and ipv6 hosts ''' self.host = host self.port = port self.socket = None BaseModbusClient.__init__(self, framer(ClientDecoder())) def connect(self): ''' Connect to the modbus tcp server :returns: True if connection succeeded, False otherwise ''' if self.socket: return True try: self.socket = socket.create_connection((self.host, self.port), Defaults.Timeout) except socket.error, msg: _logger.error('Connection to (%s, %s) failed: %s' % \ (self.host, self.port, msg)) self.close() return self.socket != None def close(self): ''' Closes the underlying socket connection ''' if self.socket: self.socket.close() self.socket = None def _send(self, request): ''' Sends data on the underlying socket :param request: The encoded request to send :return: The number of bytes written ''' if not self.socket: raise ConnectionException(self.__str__()) if request: return self.socket.send(request) return 0 def _recv(self, size): ''' Reads data from the underlying descriptor :param size: The number of bytes to read :return: The bytes read ''' if not self.socket: raise ConnectionException(self.__str__()) return self.socket.recv(size) def __str__(self): ''' Builds a string representation of the connection :returns: The string representation ''' return "%s:%s" % (self.host, self.port) #---------------------------------------------------------------------------# # Modbus UDP Client Transport Implementation #---------------------------------------------------------------------------# class ModbusUdpClient(BaseModbusClient): ''' Implementation of a modbus udp client ''' def __init__(self, host='127.0.0.1', port=Defaults.Port, framer=ModbusSocketFramer): ''' Initialize a client instance :param host: The host to connect to (default 127.0.0.1) :param port: The modbus port to connect to (default 502) :param framer: The modbus framer to use (default ModbusSocketFramer) ''' self.host = host self.port = port self.socket = None BaseModbusClient.__init__(self, framer(ClientDecoder())) @classmethod def _get_address_family(cls, address): ''' A helper method to get the correct address family for a given address. :param address: The address to get the af for :returns: AF_INET for ipv4 and AF_INET6 for ipv6 ''' try: _ = socket.inet_pton(socket.AF_INET6, address) except socket.error: # not a valid ipv6 address return socket.AF_INET return socket.AF_INET6 def connect(self): ''' Connect to the modbus tcp server :returns: True if connection succeeded, False otherwise ''' if self.socket: return True try: family = ModbusUdpClient._get_address_family(self.host) self.socket = socket.socket(family, socket.SOCK_DGRAM) except socket.error, ex: _logger.error('Unable to create udp socket %s' % ex) self.close() return self.socket != None def close(self): ''' Closes the underlying socket connection ''' self.socket = None def _send(self, request): ''' Sends data on the underlying socket :param request: The encoded request to send :return: The number of bytes written ''' if not self.socket: raise ConnectionException(self.__str__()) if request: return self.socket.sendto(request, (self.host, self.port)) return 0 def _recv(self, size): ''' Reads data from the underlying descriptor :param size: The number of bytes to read :return: The bytes read ''' if not self.socket: raise ConnectionException(self.__str__()) return self.socket.recvfrom(size)[0] def __str__(self): ''' Builds a string representation of the connection :returns: The string representation ''' return "%s:%s" % (self.host, self.port) #---------------------------------------------------------------------------# # Modbus Serial Client Transport Implementation #---------------------------------------------------------------------------# class ModbusSerialClient(BaseModbusClient): ''' Implementation of a modbus serial client ''' def __init__(self, method='ascii', **kwargs): ''' Initialize a serial client instance The methods to connect are:: - ascii - rtu - binary :param method: The method to use for connection :param port: The serial port to attach to :param stopbits: The number of stop bits to use :param bytesize: The bytesize of the serial messages :param parity: Which kind of parity to use :param baudrate: The baud rate to use for the serial device :param timeout: The timeout between serial requests (default 3s) ''' self.method = method self.socket = None BaseModbusClient.__init__(self, self.__implementation(method)) self.port = kwargs.get('port', 0) self.stopbits = kwargs.get('stopbits', Defaults.Stopbits) self.bytesize = kwargs.get('bytesize', Defaults.Bytesize) self.parity = kwargs.get('parity', Defaults.Parity) self.baudrate = kwargs.get('baudrate', Defaults.Baudrate) self.timeout = kwargs.get('timeout', Defaults.Timeout) @staticmethod def __implementation(method): ''' Returns the requested framer :method: The serial framer to instantiate :returns: The requested serial framer ''' method = method.lower() if method == 'ascii': return ModbusAsciiFramer(ClientDecoder()) elif method == 'rtu': return ModbusRtuFramer(ClientDecoder()) elif method == 'binary': return ModbusBinaryFramer(ClientDecoder()) elif method == 'socket': return ModbusSocketFramer(ClientDecoder()) raise ParameterException("Invalid framer method requested") def connect(self): ''' Connect to the modbus tcp server :returns: True if connection succeeded, False otherwise ''' if self.socket: return True try: self.socket = serial.Serial(port=self.port, timeout=self.timeout, bytesize=self.bytesize, stopbits=self.stopbits, baudrate=self.baudrate, parity=self.parity) except serial.SerialException, msg: _logger.error(msg) self.close() return self.socket != None def close(self): ''' Closes the underlying socket connection ''' if self.socket: self.socket.close() self.socket = None def _send(self, request): ''' Sends data on the underlying socket :param request: The encoded request to send :return: The number of bytes written ''' if not self.socket: raise ConnectionException(self.__str__()) if request: return self.socket.write(request) return 0 def _recv(self, size): ''' Reads data from the underlying descriptor :param size: The number of bytes to read :return: The bytes read ''' if not self.socket: raise ConnectionException(self.__str__()) return self.socket.read(size) def __str__(self): ''' Builds a string representation of the connection :returns: The string representation ''' return "%s baud[%s]" % (self.method, self.baudrate) #---------------------------------------------------------------------------# # Exported symbols #---------------------------------------------------------------------------# __all__ = [ "ModbusTcpClient", "ModbusUdpClient", "ModbusSerialClient" ]
gpl-3.0
Coheed/Shiny-Portfolio
system/modules/core/classes/StyleSheets.php
60271
<?php /** * Contao Open Source CMS * * Copyright (c) 2005-2013 Leo Feyer * * @package Core * @link https://contao.org * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL */ /** * Run in a custom namespace, so the class can be replaced */ namespace Contao; /** * Class StyleSheets * * Provide methods to handle style sheets. * @copyright Leo Feyer 2005-2013 * @author Leo Feyer <https://contao.org> * @package Core */ class StyleSheets extends \Backend { /** * Import the Files library */ public function __construct() { parent::__construct(); $this->import('Files'); } /** * Update a particular style sheet * @param integer */ public function updateStyleSheet($intId) { $objStyleSheet = $this->Database->prepare("SELECT * FROM tl_style_sheet WHERE id=?") ->limit(1) ->execute($intId); if ($objStyleSheet->numRows < 1) { return; } // Delete the CSS file if (\Input::get('act') == 'delete') { $this->import('Files'); $this->Files->delete('assets/css/' . $objStyleSheet->name . '.css'); } // Update the CSS file else { $this->writeStyleSheet($objStyleSheet->row()); $this->log('Generated style sheet "' . $objStyleSheet->name . '.css"', 'StyleSheets updateStyleSheet()', TL_CRON); } } /** * Update all style sheets in the scripts folder */ public function updateStyleSheets() { $objStyleSheets = $this->Database->execute("SELECT * FROM tl_style_sheet"); $arrStyleSheets = $objStyleSheets->fetchEach('name'); // Make sure the dcaconfig.php file is loaded @include TL_ROOT . '/system/config/dcaconfig.php'; // Delete old style sheets foreach (scan(TL_ROOT . '/assets/css', true) as $file) { // Skip directories if (is_dir(TL_ROOT . '/assets/css/' . $file)) { continue; } // Preserve root files (is this still required now that scripts are in assets/css/scripts?) if (is_array($GLOBALS['TL_CONFIG']['rootFiles']) && in_array($file, $GLOBALS['TL_CONFIG']['rootFiles'])) { continue; } // Do not delete the combined files (see #3605) if (preg_match('/^[a-f0-9]{12}\.css$/', $file)) { continue; } $objFile = new \File('assets/css/' . $file, true); // Delete the old style sheet if ($objFile->extension == 'css' && !in_array($objFile->filename, $arrStyleSheets)) { $objFile->delete(); } } $objStyleSheets->reset(); // Create the new style sheets while ($objStyleSheets->next()) { $this->writeStyleSheet($objStyleSheets->row()); $this->log('Generated style sheet "' . $objStyleSheets->name . '.css"', 'StyleSheets updateStyleSheets()', TL_CRON); } } /** * Write a style sheet to a file * @param array */ protected function writeStyleSheet($row) { if ($row['id'] == '' || $row['name'] == '') { return; } $row['name'] = basename($row['name']); // Check whether the target file is writeable if (file_exists(TL_ROOT . '/assets/css/' . $row['name'] . '.css') && !$this->Files->is_writeable('assets/css/' . $row['name'] . '.css')) { \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['notWriteable'], 'assets/css/' . $row['name'] . '.css')); return; } $vars = array(); // Get the global theme variables $objTheme = $this->Database->prepare("SELECT vars FROM tl_theme WHERE id=?") ->limit(1) ->execute($row['pid']); if ($objTheme->vars != '') { if (is_array(($tmp = deserialize($objTheme->vars)))) { foreach ($tmp as $v) { $vars[$v['key']] = $v['value']; } } } // Merge the global style sheet variables if ($row['vars'] != '') { if (is_array(($tmp = deserialize($row['vars'])))) { foreach ($tmp as $v) { $vars[$v['key']] = $v['value']; } } } // Sort by key length (see #3316) uksort($vars, 'length_sort_desc'); // Create the file $objFile = new \File('assets/css/' . $row['name'] . '.css', true); $objFile->write('/* Style sheet ' . $row['name'] . " */\n"); $objDefinitions = $this->Database->prepare("SELECT * FROM tl_style WHERE pid=? AND invisible!=1 ORDER BY sorting") ->execute($row['id']); // Append the definition while ($objDefinitions->next()) { $objFile->append($this->compileDefinition($objDefinitions->row(), true, $vars, $row), ''); } $objFile->close(); } /** * Compile format definitions and return them as string * @param array * @param boolean * @param array * @param array * @return string */ public function compileDefinition($row, $blnWriteToFile=false, $vars=array(), $parent=array()) { $blnDebug = $GLOBALS['TL_CONFIG']['debugMode']; if ($blnWriteToFile) { $strGlue = '../../'; $lb = ($blnDebug ? "\n " : ''); $return = ''; } else { $strGlue = ''; $lb = "\n "; $return = "\n" . '<pre'. ($row['invisible'] ? ' class="disabled"' : '') .'>'; } $blnNeedsPie = false; // Comment if (!$blnWriteToFile && $row['comment'] != '') { $search = array('@^\s*/\*+@', '@\*+/\s*$@'); $comment = preg_replace($search, '', $row['comment']); $comment = wordwrap(trim($comment), 72); $return .= "\n" . '<span class="comment">' . $comment . '</span>' . "\n"; } // Selector $arrSelector = trimsplit(',', \String::decodeEntities($row['selector'])); $return .= implode(($blnWriteToFile ? ',' : ",\n"), $arrSelector) . (($blnWriteToFile && !$blnDebug) ? '' : ' ') . '{'; // Size if ($row['size']) { // Width $row['width'] = deserialize($row['width']); if (isset($row['width']['value']) && $row['width']['value'] != '') { $return .= $lb . 'width:' . $row['width']['value'] . (($row['width']['value'] == 'auto') ? '' : $row['width']['unit']) . ';'; } // Height $row['height'] = deserialize($row['height']); if (isset($row['height']['value']) && $row['height']['value'] != '') { $return .= $lb . 'height:' . $row['height']['value'] . (($row['height']['value'] == 'auto') ? '' : $row['height']['unit']) . ';'; } // Min-width $row['minwidth'] = deserialize($row['minwidth']); if (isset($row['minwidth']['value']) && $row['minwidth']['value'] != '') { $return .= $lb . 'min-width:' . $row['minwidth']['value'] . (($row['minwidth']['value'] == 'inherit') ? '' : $row['minwidth']['unit']) . ';'; } // Min-height $row['minheight'] = deserialize($row['minheight']); if (isset($row['minheight']['value']) && $row['minheight']['value'] != '') { $return .= $lb . 'min-height:' . $row['minheight']['value'] . (($row['minheight']['value'] == 'inherit') ? '' : $row['minheight']['unit']) . ';'; } // Max-width $row['maxwidth'] = deserialize($row['maxwidth']); if (isset($row['maxwidth']['value']) && $row['maxwidth']['value'] != '') { $return .= $lb . 'max-width:' . $row['maxwidth']['value'] . (($row['maxwidth']['value'] == 'inherit' || $row['maxwidth']['value'] == 'none') ? '' : $row['maxwidth']['unit']) . ';'; } // Max-height $row['maxheight'] = deserialize($row['maxheight']); if (isset($row['maxheight']['value']) && $row['maxheight']['value'] != '') { $return .= $lb . 'max-height:' . $row['maxheight']['value'] . (($row['maxheight']['value'] == 'inherit' || $row['maxheight']['value'] == 'none') ? '' : $row['maxheight']['unit']) . ';'; } } // Position if ($row['positioning']) { // Top/right/bottom/left $row['trbl'] = deserialize($row['trbl']); if (is_array($row['trbl'])) { foreach ($row['trbl'] as $k=>$v) { if ($v != '' && $k != 'unit') { $return .= $lb . $k . ':' . $v . (($v == 'auto' || $v === '0') ? '' : $row['trbl']['unit']) . ';'; } } } // Position if ($row['position'] != '') { $return .= $lb . 'position:' . $row['position'] . ';'; } // Overflow if ($row['overflow'] != '') { $return .= $lb . 'overflow:' . $row['overflow'] . ';'; } // Float if ($row['floating'] != '') { $return .= $lb . 'float:' . $row['floating'] . ';'; } // Clear if ($row['clear'] != '') { $return .= $lb . 'clear:' . $row['clear'] . ';'; } // Display if ($row['display'] != '') { $return .= $lb . 'display:' . $row['display'] . ';'; } } // Margin, padding and alignment if ($row['alignment']) { // Margin if ($row['margin'] != '' || $row['align'] != '') { $row['margin'] = deserialize($row['margin']); if (is_array($row['margin'])) { $top = $row['margin']['top']; $right = $row['margin']['right']; $bottom = $row['margin']['bottom']; $left = $row['margin']['left']; // Overwrite the left and right margin if an alignment is set if ($row['align'] != '') { if ($row['align'] == 'left' || $row['align'] == 'center') { $right = 'auto'; } if ($row['align'] == 'right' || $row['align'] == 'center') { $left = 'auto'; } } // Try to shorten the definition if ($top != '' && $right != '' && $bottom != '' && $left != '') { if ($top == $right && $top == $bottom && $top == $left) { $return .= $lb . 'margin:' . $top . (($top == 'auto' || $top === '0') ? '' : $row['margin']['unit']) . ';'; } elseif ($top == $bottom && $right == $left) { $return .= $lb . 'margin:' . $top . (($top == 'auto' || $top === '0') ? '' : $row['margin']['unit']) . ' ' . $right . (($right == 'auto' || $right === '0') ? '' : $row['margin']['unit']) . ';'; } elseif ($top != $bottom && $right == $left) { $return .= $lb . 'margin:' . $top . (($top == 'auto' || $top === '0') ? '' : $row['margin']['unit']) . ' ' . $right . (($right == 'auto' || $right === '0') ? '' : $row['margin']['unit']) . ' ' . $bottom . (($bottom == 'auto' || $bottom === '0') ? '' : $row['margin']['unit']) . ';'; } else { $return .= $lb . 'margin:' . $top . (($top == 'auto' || $top === '0') ? '' : $row['margin']['unit']) . ' ' . $right . (($right == 'auto' || $right === '0') ? '' : $row['margin']['unit']) . ' ' . $bottom . (($bottom == 'auto' || $bottom === '0') ? '' : $row['margin']['unit']) . ' ' . $left . (($left == 'auto' || $left === '0') ? '' : $row['margin']['unit']) . ';'; } } else { $arrDir = array('top'=>$top, 'right'=>$right, 'bottom'=>$bottom, 'left'=>$left); foreach ($arrDir as $k=>$v) { if ($v != '') { $return .= $lb . 'margin-' . $k . ':' . $v . (($v == 'auto' || $v === '0') ? '' : $row['margin']['unit']) . ';'; } } } } } // Padding if ($row['padding'] != '') { $row['padding'] = deserialize($row['padding']); if (is_array($row['padding'])) { $top = $row['padding']['top']; $right = $row['padding']['right']; $bottom = $row['padding']['bottom']; $left = $row['padding']['left']; // Try to shorten the definition if ($top != '' && $right != '' && $bottom != '' && $left != '') { if ($top == $right && $top == $bottom && $top == $left) { $return .= $lb . 'padding:' . $top . (($top === '0') ? '' : $row['padding']['unit']) . ';'; } elseif ($top == $bottom && $right == $left) { $return .= $lb . 'padding:' . $top . (($top === '0') ? '' : $row['padding']['unit']) . ' ' . $right . (($right === '0') ? '' : $row['padding']['unit']) . ';'; } elseif ($top != $bottom && $right == $left) { $return .= $lb . 'padding:' . $top . (($top === '0') ? '' : $row['padding']['unit']) . ' ' . $right . (($right === '0') ? '' : $row['padding']['unit']) . ' ' . $bottom . (($bottom === '0') ? '' : $row['padding']['unit']) . ';'; } else { $return .= $lb . 'padding:' . $top . (($top === '0') ? '' : $row['padding']['unit']) . ' ' . $right . (($right === '0') ? '' : $row['padding']['unit']) . ' ' . $bottom . (($bottom === '0') ? '' : $row['padding']['unit']) . ' ' . $left . (($left === '0') ? '' : $row['padding']['unit']) . ';'; } } else { $arrDir = array('top'=>$top, 'right'=>$right, 'bottom'=>$bottom, 'left'=>$left); foreach ($arrDir as $k=>$v) { if ($v != '') { $return .= $lb . 'padding-' . $k . ':' . $v . (($v === '0') ? '' : $row['padding']['unit']) . ';'; } } } } } // Vertical alignment if ($row['verticalalign'] != '') { $return .= $lb . 'vertical-align:' . $row['verticalalign'] . ';'; } // Text alignment if ($row['textalign'] != '') { $return .= $lb . 'text-align:' . $row['textalign'] . ';'; } // White space if ($row['whitespace'] != '') { $return .= $lb . 'white-space:' . $row['whitespace'] . ';'; } } // Background if ($row['background']) { $bgColor = deserialize($row['bgcolor'], true); // Try to shorten the definition if ($row['bgimage'] != '' && $row['bgposition'] != '' && $row['bgrepeat'] != '') { if (($strImage = $this->generateBase64Image($row['bgimage'], $parent)) !== false) { $return .= $lb . 'background:' . (($bgColor[0] != '') ? $this->compileColor($bgColor, $blnWriteToFile, $vars) . ' ' : '') . 'url("' . $strImage . '") ' . $row['bgposition'] . ' ' . $row['bgrepeat'] . ';'; } else { $glue = (strncmp($row['bgimage'], 'data:', 5) !== 0 && strncmp($row['bgimage'], 'http://', 7) !== 0 && strncmp($row['bgimage'], 'https://', 8) !== 0 && strncmp($row['bgimage'], '/', 1) !== 0) ? $strGlue : ''; $return .= $lb . 'background:' . (($bgColor[0] != '') ? $this->compileColor($bgColor, $blnWriteToFile, $vars) . ' ' : '') . 'url("' . $glue . $row['bgimage'] . '") ' . $row['bgposition'] . ' ' . $row['bgrepeat'] . ';'; } } else { // Background color if ($bgColor[0] != '') { $return .= $lb . 'background-color:' . $this->compileColor($bgColor, $blnWriteToFile, $vars) . ';'; } // Background image if ($row['bgimage'] == 'none') { $return .= $lb . 'background-image:none;'; } elseif ($row['bgimage'] != '') { if (($strImage = $this->generateBase64Image($row['bgimage'], $parent)) !== false) { $return .= $lb . 'background-image:url("' . $strImage . '");'; } else { $glue = (strncmp($row['bgimage'], 'data:', 5) !== 0 && strncmp($row['bgimage'], 'http://', 7) !== 0 && strncmp($row['bgimage'], 'https://', 8) !== 0 && strncmp($row['bgimage'], '/', 1) !== 0) ? $strGlue : ''; $return .= $lb . 'background-image:url("' . $glue . $row['bgimage'] . '");'; } } // Background position if ($row['bgposition'] != '') { $return .= $lb . 'background-position:' .$row['bgposition']. ';'; } // Background repeat if ($row['bgrepeat'] != '') { $return .= $lb . 'background-repeat:' .$row['bgrepeat']. ';'; } } // Background gradient if ($row['gradientAngle'] != '' && $row['gradientColors'] != '') { $row['gradientColors'] = deserialize($row['gradientColors']); if (is_array($row['gradientColors']) && count(array_filter($row['gradientColors'])) > 0) { $blnNeedsPie = true; $bgImage = ''; // CSS3 PIE only supports -pie-background, so if there is a background image, include it here, too. if ($row['bgimage'] != '' && $row['bgposition'] != '' && $row['bgrepeat'] != '') { $glue = (strncmp($row['bgimage'], 'data:', 5) !== 0 && strncmp($row['bgimage'], 'http://', 7) !== 0 && strncmp($row['bgimage'], 'https://', 8) !== 0 && strncmp($row['bgimage'], '/', 1) !== 0) ? $strGlue : ''; $bgImage = 'url("' . $glue . $row['bgimage'] . '") ' . $row['bgposition'] . ' ' . $row['bgrepeat'] . ','; } // Default starting point if ($row['gradientAngle'] == '') { $row['gradientAngle'] = 'to top'; } $row['gradientColors'] = array_values(array_filter($row['gradientColors'])); // Add a hash tag to the color values foreach ($row['gradientColors'] as $k=>$v) { $row['gradientColors'][$k] = '#' . $v; } // Convert the angle for the legacy commands (see #4569) if (strpos($row['gradientAngle'], 'deg') !== false) { $angle = (abs(intval($row['gradientAngle']) - 450) % 360) . 'deg'; } else { switch ($row['gradientAngle']) { case 'to top': $angle = 'bottom'; break; case 'to right': $angle = 'left'; break; case 'to bottom': $angle = 'top'; break; case 'to left': $angle = 'right'; break; case 'to top left': $angle = 'bottom right'; break; case 'to top right': $angle = 'bottom left'; break; case 'to bottom left': $angle = 'top right'; break; case 'to bottom right': $angle = 'top left'; break; } } $colors = implode(',', $row['gradientColors']); $legacy = $angle . ',' . $colors; $gradient = $row['gradientAngle'] . ',' . $colors; $return .= $lb . 'background:' . $bgImage . '-moz-linear-gradient(' . $legacy . ');'; $return .= $lb . 'background:' . $bgImage . '-webkit-linear-gradient(' . $legacy . ');'; $return .= $lb . 'background:' . $bgImage . '-o-linear-gradient(' . $legacy . ');'; $return .= $lb . 'background:' . $bgImage . '-ms-linear-gradient(' . $legacy . ');'; $return .= $lb . 'background:' . $bgImage . 'linear-gradient(' . $gradient . ');'; $return .= $lb . '-pie-background:' . $bgImage . 'linear-gradient(' . $legacy . ');'; } } // Box shadow if ($row['shadowsize'] != '') { $shColor = deserialize($row['shadowcolor'], true); $row['shadowsize'] = deserialize($row['shadowsize']); if (is_array($row['shadowsize']) && $row['shadowsize']['top'] != '' && $row['shadowsize']['right'] != '') { $blnNeedsPie = true; $offsetx = $row['shadowsize']['top']; $offsety = $row['shadowsize']['right']; $blursize = $row['shadowsize']['bottom']; $radius = $row['shadowsize']['left']; $shadow = $offsetx . (($offsetx === '0') ? '' : $row['shadowsize']['unit']); $shadow .= ' ' . $offsety . (($offsety === '0') ? '' : $row['shadowsize']['unit']); if ($blursize != '') { $shadow .= ' ' . $blursize . (($blursize === '0') ? '' : $row['shadowsize']['unit']); } if ($radius != '') { $shadow .= ' ' . $radius . (($radius === '0') ? '' : $row['shadowsize']['unit']); } if ($shColor[0] != '') { $shadow .= ' ' . $this->compileColor($shColor, $blnWriteToFile, $vars); } $shadow .= ';'; // Prefix required in Safari <= 5 and Android $return .= $lb . '-webkit-box-shadow:' . $shadow; $return .= $lb . 'box-shadow:' . $shadow; } } } // Border if ($row['border']) { $bdColor = deserialize($row['bordercolor'], true); $row['borderwidth'] = deserialize($row['borderwidth']); // Border width if (is_array($row['borderwidth'])) { $top = $row['borderwidth']['top']; $right = $row['borderwidth']['right']; $bottom = $row['borderwidth']['bottom']; $left = $row['borderwidth']['left']; // Try to shorten the definition if ($top != '' && $right != '' && $bottom != '' && $left != '' && $top == $right && $top == $bottom && $top == $left) { $return .= $lb . 'border:' . $top . $row['borderwidth']['unit'] . (($row['borderstyle'] != '') ? ' ' .$row['borderstyle'] : '') . (($bdColor[0] != '') ? ' ' . $this->compileColor($bdColor, $blnWriteToFile, $vars) : '') . ';'; } elseif ($top != '' && $right != '' && $bottom != '' && $left != '' && $top == $bottom && $left == $right) { $return .= $lb . 'border-width:' . $top . $row['borderwidth']['unit'] . ' ' . $right . $row['borderwidth']['unit'] . ';'; if ($row['borderstyle'] != '') { $return .= $lb . 'border-style:' . $row['borderstyle'] . ';'; } if ($bdColor[0] != '') { $return .= $lb . 'border-color:' . $this->compileColor($bdColor, $blnWriteToFile, $vars) . ';'; } } elseif ($top == '' && $right == '' && $bottom == '' && $left == '') { if ($row['borderstyle'] != '') { $return .= $lb . 'border-style:' . $row['borderstyle'] . ';'; } if ($bdColor[0] != '') { $return .= $lb . 'border-color:' . $this->compileColor($bdColor, $blnWriteToFile, $vars) . ';'; } } else { $arrDir = array('top'=>$top, 'right'=>$right, 'bottom'=>$bottom, 'left'=>$left); foreach ($arrDir as $k=>$v) { if ($v != '') { $return .= $lb . 'border-' . $k . ':' . $v . $row['borderwidth']['unit'] . (($row['borderstyle'] != '') ? ' ' . $row['borderstyle'] : '') . (($bdColor[0] != '') ? ' ' . $this->compileColor($bdColor, $blnWriteToFile, $vars) : '') . ';'; } } } } else { if ($row['borderstyle'] != '') { $return .= $lb . 'border-style:' . $row['borderstyle'] . ';'; } if ($bdColor[0] != '') { $return .= $lb . 'border-color:' . $this->compileColor($bdColor, $blnWriteToFile, $vars) . ';'; } } // Border radius if ($row['borderradius'] != '') { $row['borderradius'] = deserialize($row['borderradius']); if (is_array($row['borderradius']) && ($row['borderradius']['top'] != '' || $row['borderradius']['right'] != '' || $row['borderradius']['bottom'] != '' || $row['borderradius']['left'] != '')) { $blnNeedsPie = true; $top = $row['borderradius']['top']; $right = $row['borderradius']['right']; $bottom = $row['borderradius']['bottom']; $left = $row['borderradius']['left']; $borderradius = ''; // Try to shorten the definition if ($top != '' && $right != '' && $bottom != '' && $left != '') { if ($top == $right && $top == $bottom && $top == $left) { $borderradius = $top . (($top === '0') ? '' : $row['borderradius']['unit']) . ';'; } elseif ($top == $bottom && $right == $left) { $borderradius = $top . (($top === '0') ? '' : $row['borderradius']['unit']) . ' ' . $right . (($right === '0') ? '' : $row['borderradius']['unit']) . ';'; } elseif ($top != $bottom && $right == $left) { $borderradius = $top . (($top === '0') ? '' : $row['borderradius']['unit']) . ' ' . $right . (($right === '0') ? '' : $row['borderradius']['unit']) . ' ' . $bottom . (($bottom === '0') ? '' : $row['borderradius']['unit']) . ';'; } else { $borderradius .= $top . (($top === '0') ? '' : $row['borderradius']['unit']) . ' ' . $right . (($right === '0') ? '' : $row['borderradius']['unit']) . ' ' . $bottom . (($bottom === '0') ? '' : $row['borderradius']['unit']) . ' ' . $left . (($left === '0') ? '' : $row['borderradius']['unit']) . ';'; } $return .= $lb . 'border-radius:' . $borderradius; } else { $arrDir = array('top-left'=>$top, 'top-right'=>$right, 'bottom-right'=>$bottom, 'bottom-left'=>$left); foreach ($arrDir as $k=>$v) { if ($v != '') { $return .= $lb . 'border-' . $k . '-radius:' . $v . (($v === '0') ? '' : $row['borderradius']['unit']) . ';'; } } } } } // Border collapse if ($row['bordercollapse'] != '') { $return .= $lb . 'border-collapse:' . $row['bordercollapse'] . ';'; } // Border spacing $row['borderspacing'] = deserialize($row['borderspacing']); if (isset($row['borderspacing']['value']) && $row['borderspacing']['value'] != '') { $return .= $lb . 'border-spacing:' . $row['borderspacing']['value'] . $row['borderspacing']['unit'] . ';'; } } // Font if ($row['font']) { $row['fontsize'] = deserialize($row['fontsize']); $row['lineheight'] = deserialize($row['lineheight']); $row['fontfamily'] = str_replace(', ', ',', $row['fontfamily']); // Try to shorten the definition if ($row['fontfamily'] != '' && $row['fontfamily'] != 'inherit' && isset($row['fontsize']['value']) && $row['fontsize']['value'] != '' && $row['fontsize']['value'] != 'inherit') { $return .= $lb . 'font:' . $row['fontsize']['value'] . $row['fontsize']['unit'] . ((isset($row['lineheight']['value']) && $row['lineheight']['value'] != '') ? '/' . $row['lineheight']['value'] . $row['lineheight']['unit'] : '') . ' ' . $row['fontfamily'] . ';'; } else { // Font family if ($row['fontfamily'] != '') { $return .= $lb . 'font-family:' . $row['fontfamily'] . ';'; } // Font size if (isset($row['fontsize']['value']) && $row['fontsize']['value'] != '') { $return .= $lb . 'font-size:' . $row['fontsize']['value'] . $row['fontsize']['unit'] . ';'; } // Line height if (isset($row['lineheight']['value']) && $row['lineheight']['value'] != '') { $return .= $lb . 'line-height:' . $row['lineheight']['value'] . $row['lineheight']['unit'] . ';'; } } // Font style $row['fontstyle'] = deserialize($row['fontstyle']); if (is_array($row['fontstyle'])) { if (in_array('bold', $row['fontstyle'])) { $return .= $lb . 'font-weight:bold;'; } if (in_array('italic', $row['fontstyle'])) { $return .= $lb . 'font-style:italic;'; } if (in_array('normal', $row['fontstyle'])) { $return .= $lb . 'font-weight:normal;'; } if (in_array('underline', $row['fontstyle'])) { $return .= $lb . 'text-decoration:underline;'; } if (in_array('line-through', $row['fontstyle'])) { $return .= $lb . 'text-decoration:line-through;'; } if (in_array('overline', $row['fontstyle'])) { $return .= $lb. 'text-decoration:overline;'; } if (in_array('notUnderlined', $row['fontstyle'])) { $return .= $lb . 'text-decoration:none;'; } if (in_array('small-caps', $row['fontstyle'])) { $return .= $lb . 'font-variant:small-caps;'; } } $fnColor = deserialize($row['fontcolor'], true); // Font color if ($fnColor[0] != '') { $return .= $lb . 'color:' . $this->compileColor($fnColor, $blnWriteToFile, $vars) . ';'; } // Text transform if ($row['texttransform'] != '') { $return .= $lb . 'text-transform:' . $row['texttransform'] . ';'; } // Text indent $row['textindent'] = deserialize($row['textindent']); if (isset($row['textindent']['value']) && $row['textindent']['value'] != '') { $return .= $lb . 'text-indent:' . $row['textindent']['value'] . $row['textindent']['unit'] . ';'; } // Letter spacing $row['letterspacing'] = deserialize($row['letterspacing']); if (isset($row['letterspacing']['value']) && $row['letterspacing']['value'] != '') { $return .= $lb . 'letter-spacing:' . $row['letterspacing']['value'] . $row['letterspacing']['unit'] . ';'; } // Word spacing $row['wordspacing'] = deserialize($row['wordspacing']); if (isset($row['wordspacing']['value']) && $row['wordspacing']['value'] != '') { $return .= $lb . 'word-spacing:' . $row['wordspacing']['value'] . $row['wordspacing']['unit'] . ';'; } } // List if ($row['list']) { // List bullet if ($row['liststyletype'] != '') { $return .= $lb . 'list-style-type:' . $row['liststyletype'] . ';'; } // List image if ($row['liststyleimage'] == 'none') { $return .= $lb . 'list-style-image:none;'; } elseif ($row['liststyleimage'] != '') { if (($strImage = $this->generateBase64Image($row['liststyleimage'], $parent)) !== false) { $return .= $lb . 'list-style-image:url("' . $strImage . '");'; } else { $glue = (strncmp($row['liststyleimage'], 'data:', 5) !== 0 && strncmp($row['liststyleimage'], 'http://', 7) !== 0 && strncmp($row['liststyleimage'], 'https://', 8) !== 0 && strncmp($row['liststyleimage'], '/', 1) !== 0) ? $strGlue : ''; $return .= $lb . 'list-style-image:url("' . $glue . $row['liststyleimage'] . '");'; } } } // CSS3PIE if ($blnNeedsPie && !$parent['disablePie']) { $return .= $lb . 'behavior:url(\'assets/css3pie/'.CSS3PIE.'/PIE.htc\');'; } // Custom code if ($row['own'] != '') { $own = trim(\String::decodeEntities($row['own'])); $own = preg_replace('/url\("(?!data:|\/)/', 'url("' . $strGlue, $own); $own = preg_split('/[\n\r]+/', $own); $return .= $lb . implode(($blnWriteToFile ? '' : $lb), $own); } // Allow custom definitions if (isset($GLOBALS['TL_HOOKS']['compileDefinition']) && is_array($GLOBALS['TL_HOOKS']['compileDefinition'])) { foreach ($GLOBALS['TL_HOOKS']['compileDefinition'] as $callback) { $this->import($callback[0]); $strTemp = $this->$callback[0]->$callback[1]($row, $blnWriteToFile, $vars); if ($strTemp != '') { $return .= $lb . $strTemp; } } } // Close the format definition if ($blnWriteToFile) { // Remove the last semi-colon (;) before the closing bracket if (substr($return, -1) == ';') { $return = substr($return, 0, -1); } $nl = $blnDebug ? "\n" : ''; $return .= $nl . '}' . $nl; } else { $return .= "\n}</pre>\n"; } // Replace global variables if (strpos($return, '$') !== false && !empty($vars)) { $return = str_replace(array_keys($vars), array_values($vars), $return); } return $return; } /** * Compile a color value and return a hex or rgba color * @param mixed * @param boolean * @param array * @return string */ protected function compileColor($color, $blnWriteToFile=false, $vars=array()) { if (!is_array($color)) { return '#' . $this->shortenHexColor($color); } elseif (!isset($color[1]) || empty($color[1])) { return '#' . $this->shortenHexColor($color[0]); } else { return 'rgba(' . implode(',', $this->convertHexColor($color[0], $blnWriteToFile, $vars)) . ','. ($color[1] / 100) .')'; } } /** * Try to shorten a hex color * @param string * @return string */ protected function shortenHexColor($color) { if ($color[0] == $color[1] && $color[2] == $color[3] && $color[4] == $color[5]) { return $color[0] . $color[2] . $color[4]; } return $color; } /** * Convert hex colors to rgb * @param string * @param boolean * @param array * @return array * @see http://de3.php.net/manual/de/function.hexdec.php#99478 */ protected function convertHexColor($color, $blnWriteToFile=false, $vars=array()) { // Support global variables if (strncmp($color, '$', 1) === 0) { if (!$blnWriteToFile) { return array($color); } else { $color = str_replace(array_keys($vars), array_values($vars), $color); } } $rgb = array(); // Try to convert using bitwise operation if (strlen($color) == 6) { $dec = hexdec($color); $rgb['red'] = 0xFF & ($dec >> 0x10); $rgb['green'] = 0xFF & ($dec >> 0x8); $rgb['blue'] = 0xFF & $dec; } // Shorthand notation elseif (strlen($color) == 3) { $rgb['red'] = hexdec(str_repeat(substr($color, 0, 1), 2)); $rgb['green'] = hexdec(str_repeat(substr($color, 1, 1), 2)); $rgb['blue'] = hexdec(str_repeat(substr($color, 2, 1), 2)); } return $rgb; } /** * Return a form to choose an existing style sheet and import it * @return string * @throws \Exception */ public function importStyleSheet() { if (\Input::get('key') != 'import') { return ''; } $this->import('BackendUser', 'User'); $class = $this->User->uploader; // See #4086 if (!class_exists($class)) { $class = 'FileUpload'; } $objUploader = new $class(); // Import CSS if (\Input::post('FORM_SUBMIT') == 'tl_style_sheet_import') { $arrUploaded = $objUploader->uploadTo('system/tmp'); if (empty($arrUploaded)) { \Message::addError($GLOBALS['TL_LANG']['ERR']['all_fields']); $this->reload(); } foreach ($arrUploaded as $strCssFile) { // Folders cannot be imported if (is_dir(TL_ROOT . '/' . $strCssFile)) { \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['importFolder'], basename($strCssFile))); continue; } $objFile = new \File($strCssFile, true); // Check the file extension if ($objFile->extension != 'css') { \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension)); continue; } // Check the file name $strName = preg_replace('/\.css$/i', '', basename($strCssFile)); $strName = $this->checkStyleSheetName($strName); // Create the new style sheet $objStyleSheet = $this->Database->prepare("INSERT INTO tl_style_sheet (pid, tstamp, name, media) VALUES (?, ?, ?, ?)") ->execute(\Input::get('id'), time(), $strName, array('all')); $insertId = $objStyleSheet->insertId; if (!is_numeric($insertId) || $insertId < 0) { throw new \Exception('Invalid insert ID'); } // Read the file and remove carriage returns $strFile = $objFile->getContent(); $strFile = str_replace("\r", '', $strFile); $arrTokens = array(); $strBuffer = ''; $intSorting = 0; $strComment = ''; $strCategory = ''; $intLength = strlen($strFile); // Tokenize for ($i=0; $i<$intLength; $i++) { $char = $strFile[$i]; // Whitespace if ($char == '' || $char == "\n" || $char == "\t") { // Ignore } // Comment elseif ($char == '/') { if ($strFile[$i+1] == '*') { while ($i<$intLength) { $strBuffer .= $strFile[$i++]; if ($strFile[$i] == '/' && $strFile[$i-1] == '*') { $arrTokens[] = array ( 'type' => 'comment', 'content' => $strBuffer . $strFile[$i] ); $strBuffer = ''; break; } } } } // At block elseif ($char == '@') { $intLevel = 0; $strSelector = ''; while ($i<$intLength) { $strBuffer .= $strFile[$i++]; if ($strFile[$i] == '{') { if (++$intLevel == 1) { ++$i; $strSelector = $strBuffer; $strBuffer = ''; } } elseif ($strFile[$i] == '}') { if (--$intLevel == 0) { $arrTokens[] = array ( 'type' => 'atblock', 'selector' => $strSelector, 'content' => $strBuffer ); $strBuffer = ''; break; } } } } // Regular block else { while ($i<$intLength) { $strBuffer .= $strFile[$i++]; if ($strFile[$i] == '{') { ++$i; $strSelector = $strBuffer; $strBuffer = ''; } elseif ($strFile[$i] == '}') { $arrTokens[] = array ( 'type' => 'block', 'selector' => $strSelector, 'content' => $strBuffer ); $strBuffer = ''; break; } } } } foreach ($arrTokens as $arrToken) { // Comments if ($arrToken['type'] == 'comment') { // Category (comments start with /** and contain only one line) if (strncmp($arrToken['content'], '/**', 3) === 0 && substr_count($arrToken['content'], "\n") == 2) { $strCategory = trim(str_replace(array('/*', '*/', '*'), '', $arrToken['content'])); } // Declaration comment elseif (strpos($arrToken['content'], "\n") === false) { $strComment = trim(str_replace(array('/*', '*/', '*'), '', $arrToken['content'])); } } // At blocks like @media or @-webkit-keyframe elseif ($arrToken['type'] == 'atblock') { $arrSet = array ( 'pid' => $insertId, 'category' => $strCategory, 'comment' => $strComment, 'sorting' => $intSorting += 128, 'selector' => trim($arrToken['selector']), 'own' => $arrToken['content'] ); $this->Database->prepare("INSERT INTO tl_style %s")->set($arrSet)->execute(); $strComment = ''; } // Regular blocks else { $arrDefinition = array ( 'pid' => $insertId, 'category' => $strCategory, 'comment' => $strComment, 'sorting' => $intSorting += 128, 'selector' => trim($arrToken['selector']), 'attributes' => $arrToken['content'] ); $this->createDefinition($arrDefinition); $strComment = ''; } } // Write the style sheet $this->updateStyleSheet($insertId); // Notify the user if ($strName . '.css' != basename($strCssFile)) { \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_renamed'], basename($strCssFile), $strName . '.css')); } else { \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_imported'], $strName . '.css')); } } // Redirect \System::setCookie('BE_PAGE_OFFSET', 0, 0); $this->redirect(str_replace('&key=import', '', \Environment::get('request'))); } // Return form return ' <div id="tl_buttons"> <a href="' .ampersand(str_replace('&key=import', '', \Environment::get('request'))). '" class="header_back" title="' .specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']). '" accesskey="b">' .$GLOBALS['TL_LANG']['MSC']['backBT']. '</a> </div> <h2 class="sub_headline">' .$GLOBALS['TL_LANG']['tl_style_sheet']['import'][1]. '</h2> ' .\Message::generate(). ' <form action="' .ampersand(\Environment::get('request'), true). '" id="tl_style_sheet_import" class="tl_form" method="post" enctype="multipart/form-data"> <div class="tl_formbody_edit"> <input type="hidden" name="FORM_SUBMIT" value="tl_style_sheet_import"> <input type="hidden" name="REQUEST_TOKEN" value="'.REQUEST_TOKEN.'"> <input type="hidden" name="MAX_FILE_SIZE" value="'.$GLOBALS['TL_CONFIG']['maxFileSize'].'"> <div class="tl_tbox"> <h3>'.$GLOBALS['TL_LANG']['tl_style_sheet']['source'][0].'</h3>'.$objUploader->generateMarkup().(isset($GLOBALS['TL_LANG']['tl_style_sheet']['source'][1]) ? ' <p class="tl_help tl_tip">'.$GLOBALS['TL_LANG']['tl_style_sheet']['source'][1].'</p>' : '').' </div> </div> <div class="tl_formbody_submit"> <div class="tl_submit_container"> <input type="submit" name="save" id="save" class="tl_submit" accesskey="s" value="' .specialchars($GLOBALS['TL_LANG']['tl_style_sheet']['import'][0]). '"> </div> </div> </form>'; } /** * Check the name of an imported file * @param string * @return string */ public function checkStyleSheetName($strName) { $objStyleSheet = $this->Database->prepare("SELECT COUNT(*) AS count FROM tl_style_sheet WHERE name=?") ->limit(1) ->execute($strName); if ($objStyleSheet->count < 1) { return $strName; } $chunks = explode('-', $strName); $i = (count($chunks) > 1) ? array_pop($chunks) : 0; $strName = implode('-', $chunks) . '-' . (intval($i) + 1); return $this->checkStyleSheetName($strName); } /** * Create a format definition and insert it into the database * @param array */ protected function createDefinition($arrDefinition) { $arrSet = array ( 'pid' => $arrDefinition['pid'], 'sorting' => $arrDefinition['sorting'], 'tstamp' => time(), 'comment' => $arrDefinition['comment'], 'category' => $arrDefinition['category'], 'selector' => $arrDefinition['selector'] ); $arrAttributes = array_map('trim', explode(';', $arrDefinition['attributes'])); foreach ($arrAttributes as $strDefinition) { // Skip empty definitions if (trim($strDefinition) == '') { continue; } // Handle important definitions if (strpos($strDefinition, 'important') !== false || strpos($strDefinition, 'transparent') !== false || strpos($strDefinition, 'inherit') !== false) { $arrSet['own'][] = $strDefinition; continue; } $arrChunks = array_map('trim', explode(':', $strDefinition, 2)); $strKey = strtolower($arrChunks[0]); switch ($strKey) { case 'width': case 'height': if ($arrChunks[1] == 'auto') { $strUnit = ''; $varValue = 'auto'; } else { $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrChunks[1]); $varValue = preg_replace('/[^0-9\.-]+/', '', $arrChunks[1]); } $arrSet['size'] = 1; $arrSet[$strKey]['value'] = $varValue; $arrSet[$strKey]['unit'] = $strUnit; break; case 'min-width': case 'min-height': $strName = str_replace('-', '', $strKey); if ($arrChunks[1] == 'inherit') { $strUnit = ''; $varValue = 'inherit'; } else { $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrChunks[1]); $varValue = preg_replace('/[^0-9\.-]+/', '', $arrChunks[1]); } $arrSet['size'] = 1; $arrSet[$strName]['value'] = $varValue; $arrSet[$strName]['unit'] = $strUnit; break; case 'max-width': case 'max-height': $strName = str_replace('-', '', $strKey); if ($arrChunks[1] == 'inherit' || $arrChunks[1] == 'none') { $strUnit = ''; $varValue = $arrChunks[1]; } else { $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrChunks[1]); $varValue = preg_replace('/[^0-9\.-]+/', '', $arrChunks[1]); } $arrSet['size'] = 1; $arrSet[$strName]['value'] = $varValue; $arrSet[$strName]['unit'] = $strUnit; break; case 'top': case 'right': case 'bottom': case 'left': if ($arrChunks[1] == 'auto') { $strUnit = ''; $varValue = 'auto'; } elseif (isset($arrSet['trbl']['unit'])) { $arrSet['own'][] = $strDefinition; break; } else { $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrChunks[1]); $varValue = preg_replace('/[^0-9\.-]+/', '', $arrChunks[1]); } $arrSet['positioning'] = 1; $arrSet['trbl'][$strKey] = $varValue; if ($strUnit != '') { $arrSet['trbl']['unit'] = $strUnit; } break; case 'position': case 'overflow': case 'clear': case 'display': $arrSet['positioning'] = 1; $arrSet[$strKey] = $arrChunks[1]; break; case 'float': $arrSet['positioning'] = 1; $arrSet['floating'] = $arrChunks[1]; break; case 'margin': case 'padding': $arrSet['alignment'] = 1; $arrTRBL = preg_split('/\s+/', $arrChunks[1]); $arrUnits = array(); switch (count($arrTRBL)) { case 1: if ($arrTRBL[0] == 'auto') { $strUnit = ''; $varValue = 'auto'; } else { $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[0]); $varValue = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[0]); } $arrSet[$strKey] = array ( 'top' => $varValue, 'right' => $varValue, 'bottom' => $varValue, 'left' => $varValue, 'unit' => $strUnit ); break; case 2: if ($arrTRBL[0] == 'auto') { $varValue_1 = 'auto'; } else { $arrUnits[] = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[0]); $varValue_1 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[0]); } if ($arrTRBL[1] == 'auto') { $varValue_2 = 'auto'; } else { $arrUnits[] = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[1]); $varValue_2 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[1]); } // Move to custom section if there are different units if (count(array_filter(array_unique($arrUnits))) > 1) { $arrSet['alignment'] = ''; $arrSet['own'][] = $strDefinition; break; } $arrSet[$strKey] = array ( 'top' => $varValue_1, 'right' => $varValue_2, 'bottom' => $varValue_1, 'left' => $varValue_2, 'unit' => '' ); // Overwrite the unit foreach ($arrUnits as $strUnit) { if ($strUnit != '') { $arrSet[$strKey]['unit'] = $strUnit; break; } } break; case 3: if ($arrTRBL[0] == 'auto') { $varValue_1 = 'auto'; } else { $arrUnits[] = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[0]); $varValue_1 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[0]); } if ($arrTRBL[1] == 'auto') { $varValue_2 = 'auto'; } else { $arrUnits[] = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[1]); $varValue_2 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[1]); } if ($arrTRBL[2] == 'auto') { $varValue_3 = 'auto'; } else { $arrUnits[] = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[2]); $varValue_3 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[2]); } // Move to custom section if there are different units if (count(array_filter(array_unique($arrUnits))) > 1) { $arrSet['alignment'] = ''; $arrSet['own'][] = $strDefinition; break; } $arrSet[$strKey] = array ( 'top' => $varValue_1, 'right' => $varValue_2, 'bottom' => $varValue_3, 'left' => $varValue_2, 'unit' => '' ); // Overwrite the unit foreach ($arrUnits as $strUnit) { if ($strUnit != '') { $arrSet[$strKey]['unit'] = $strUnit; break; } } break; case 4: if ($arrTRBL[0] == 'auto') { $varValue_1 = 'auto'; } else { $arrUnits[] = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[0]); $varValue_1 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[0]); } if ($arrTRBL[1] == 'auto') { $varValue_2 = 'auto'; } else { $arrUnits[] = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[1]); $varValue_2 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[1]); } if ($arrTRBL[2] == 'auto') { $varValue_3 = 'auto'; } else { $arrUnits[] = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[2]); $varValue_3 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[2]); } if ($arrTRBL[3] == 'auto') { $varValue_4 = 'auto'; } else { $arrUnits[] = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[3]); $varValue_4 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[3]); } // Move to custom section if there are different units if (count(array_filter(array_unique($arrUnits))) > 1) { $arrSet['alignment'] = ''; $arrSet['own'][] = $strDefinition; break; } $arrSet[$strKey] = array ( 'top' => $varValue_1, 'right' => $varValue_2, 'bottom' => $varValue_3, 'left' => $varValue_4, 'unit' => '' ); // Overwrite the unit foreach ($arrUnits as $strUnit) { if ($strUnit != '') { $arrSet[$strKey]['unit'] = $strUnit; break; } } break; } break; case 'margin-top': case 'margin-right': case 'margin-bottom': case 'margin-left': $arrSet['alignment'] = 1; $strName = str_replace('margin-', '', $strKey); if ($arrChunks[1] == 'auto') { $strUnit = ''; $varValue = 'auto'; } else { $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrChunks[1]); $varValue = preg_replace('/[^0-9\.-]+/', '', $arrChunks[1]); } $arrSet['margin'][$strName] = $varValue; if (empty($arrSet['margin']['unit'])) { $arrSet['margin']['unit'] = $strUnit; } break; case 'padding-top': case 'padding-right': case 'padding-bottom': case 'padding-left': $arrSet['alignment'] = 1; $strName = str_replace('padding-', '', $strKey); $varValue = preg_replace('/[^0-9\.-]+/', '', $arrChunks[1]); $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrChunks[1]); $arrSet['padding'][$strName] = $varValue; $arrSet['padding']['unit'] = $strUnit; break; case 'align': case 'text-align': case 'vertical-align': case 'white-space': $arrSet['alignment'] = 1; $arrSet[str_replace('-', '', $strKey)] = $arrChunks[1]; break; case 'background-color': if (!preg_match('/^#[a-f0-9]+$/i', $arrChunks[1])) { $arrSet['own'][] = $strDefinition; } else { $arrSet['background'] = 1; $arrSet['bgcolor'] = str_replace('#', '', $arrChunks[1]); } break; case 'background-image': $url = preg_replace('/url\(["\']?([^"\'\)]+)["\']?\)/i', '$1', $arrChunks[1]); if (strncmp($url, '-', 1) === 0) { // Ignore vendor prefixed commands } elseif (strncmp($url, 'radial-gradient', 15) === 0) { $arrSet['own'][] = $strDefinition; // radial gradients (see #4640) } else { $arrSet['background'] = 1; // Handle linear gradients (see #4640) if (strncmp($url, 'linear-gradient', 15) === 0) { $colors = trimsplit(',', preg_replace('/linear-gradient ?\(([^\)]+)\)/', '$1', $url)); $arrSet['gradientAngle'] = array_shift($colors); $arrSet['gradientColors'] = serialize($colors); } else { $arrSet['bgimage'] = $url; } } break; case 'background-position': $arrSet['background'] = 1; if (preg_match('/[0-9]+/', $arrChunks[1])) { $arrSet['own'][] = $strDefinition; } else { $arrSet['bgposition'] = $arrChunks[1]; } break; case 'background-repeat': $arrSet['background'] = 1; $arrSet['bgrepeat'] = $arrChunks[1]; break; case 'border': if ($arrChunks[1] == 'none') { $arrSet['own'][] = $strDefinition; break; } $arrWSC = preg_split('/\s+/', $arrChunks[1]); if ($arrWSC[2] != '' && !preg_match('/^#[a-f0-9]+$/i', $arrWSC[2])) { $arrSet['own'][] = $strDefinition; break; } $arrSet['border'] = 1; $varValue = preg_replace('/[^0-9\.-]+/', '', $arrWSC[0]); $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrWSC[0]); $arrSet['borderwidth'] = array ( 'top' => $varValue, 'right' => $varValue, 'bottom' => $varValue, 'left' => $varValue, 'unit' => $strUnit ); if ($arrWSC[1] != '') { $arrSet['borderstyle'] = $arrWSC[1]; } if ($arrWSC[2] != '') { $arrSet['bordercolor'] = str_replace('#', '', $arrWSC[2]); } break; case 'border-top': case 'border-right': case 'border-bottom': case 'border-left': if ($arrChunks[1] == 'none') { $arrSet['own'][] = $strDefinition; break; } $arrWSC = preg_split('/\s+/', $arrChunks[1]); if ($arrWSC[2] != '' && !preg_match('/^#[a-f0-9]+$/i', $arrWSC[2])) { $arrSet['own'][] = $strDefinition; break; } $arrSet['border'] = 1; $strName = str_replace('border-', '', $strKey); $varValue = preg_replace('/[^0-9\.-]+/', '', $arrWSC[0]); $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrWSC[0]); if ((isset($arrSet['borderwidth']['unit']) && $arrSet['borderwidth']['unit'] != $strUnit) || ($arrWSC[1] != '' && isset($arrSet['borderstyle']) && $arrSet['borderstyle'] != $arrWSC[1]) || ($arrWSC[2] != '' && isset($arrSet['bordercolor']) && $arrSet['bordercolor'] != $arrWSC[2])) { $arrSet['own'][] = $strDefinition; break; } $arrSet['borderwidth'][$strName] = preg_replace('/[^0-9\.-]+/', '', $varValue); $arrSet['borderwidth']['unit'] = $strUnit; if ($arrWSC[1] != '') { $arrSet['borderstyle'] = $arrWSC[1]; } if ($arrWSC[2] != '') { $arrSet['bordercolor'] = str_replace('#', '', $arrWSC[2]); } break; case 'border-width': $arrSet['border'] = 1; $arrTRBL = preg_split('/\s+/', $arrChunks[1]); $strUnit = ''; foreach ($arrTRBL as $v) { if ($v != 0) { $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[0]); } } switch (count($arrTRBL)) { case 1: $varValue = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[0]); $arrSet['borderwidth'] = array ( 'top' => $varValue, 'right' => $varValue, 'bottom' => $varValue, 'left' => $varValue, 'unit' => $strUnit ); break; case 2: $varValue_1 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[0]); $varValue_2 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[1]); $arrSet['borderwidth'] = array ( 'top' => $varValue_1, 'right' => $varValue_2, 'bottom' => $varValue_1, 'left' => $varValue_2, 'unit' => $strUnit ); break; case 4: $arrSet['borderwidth'] = array ( 'top' => preg_replace('/[^0-9\.-]+/', '', $arrTRBL[0]), 'right' => preg_replace('/[^0-9\.-]+/', '', $arrTRBL[1]), 'bottom' => preg_replace('/[^0-9\.-]+/', '', $arrTRBL[2]), 'left' => preg_replace('/[^0-9\.-]+/', '', $arrTRBL[3]), 'unit' => $strUnit ); break; } break; case 'border-color': if (!preg_match('/^#[a-f0-9]+$/i', $arrChunks[1])) { $arrSet['own'][] = $strDefinition; } else { $arrSet['border'] = 1; $arrSet['bordercolor'] = str_replace('#', '', $arrChunks[1]); } break; case 'border-radius': $arrSet['border'] = 1; $arrTRBL = preg_split('/\s+/', $arrChunks[1]); $strUnit = ''; foreach ($arrTRBL as $v) { if ($v != 0) { $strUnit = preg_replace('/[^ceimnptx%]/', '', $arrTRBL[0]); } } switch (count($arrTRBL)) { case 1: $varValue = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[0]); $arrSet['borderradius'] = array ( 'top' => $varValue, 'right' => $varValue, 'bottom' => $varValue, 'left' => $varValue, 'unit' => $strUnit ); break; case 2: $varValue_1 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[0]); $varValue_2 = preg_replace('/[^0-9\.-]+/', '', $arrTRBL[1]); $arrSet['borderradius'] = array ( 'top' => $varValue_1, 'right' => $varValue_2, 'bottom' => $varValue_1, 'left' => $varValue_2, 'unit' => $strUnit ); break; case 4: $arrSet['borderradius'] = array ( 'top' => preg_replace('/[^0-9\.-]+/', '', $arrTRBL[0]), 'right' => preg_replace('/[^0-9\.-]+/', '', $arrTRBL[1]), 'bottom' => preg_replace('/[^0-9\.-]+/', '', $arrTRBL[2]), 'left' => preg_replace('/[^0-9\.-]+/', '', $arrTRBL[3]), 'unit' => $strUnit ); break; } break; case '-moz-border-radius': case '-webkit-border-radius': // Ignore break; case 'border-style': case 'border-collapse': $arrSet['border'] = 1; $arrSet[str_replace('-', '', $strKey)] = $arrChunks[1]; break; case 'border-spacing': $arrSet['border'] = 1; $arrSet['borderspacing'] = array ( 'value' => preg_replace('/[^0-9\.-]+/', '', $arrChunks[1]), 'unit' => preg_replace('/[^ceimnptx%]/', '', $arrChunks[1]) ); break; case 'font-family': $arrSet['font'] = 1; $arrSet[str_replace('-', '', $strKey)] = $arrChunks[1]; break; case 'font-size': if (!preg_match('/[0-9]+/', $arrChunks[1])) { $arrSet['own'][] = $strDefinition; } else { $arrSet['font'] = 1; $arrSet['fontsize'] = array ( 'value' => preg_replace('/[^0-9\.-]+/', '', $arrChunks[1]), 'unit' => preg_replace('/[^ceimnptx%]/', '', $arrChunks[1]) ); } break; case 'font-weight': if ($arrChunks[1] == 'bold' || $arrChunks[1] == 'normal') { $arrSet['font'] = 1; $arrSet['fontstyle'][] = $arrChunks[1]; } else { $arrSet['own'][] = $strDefinition; } break; case 'font-style': if ($arrChunks[1] == 'italic') { $arrSet['font'] = 1; $arrSet['fontstyle'][] = 'italic'; } else { $arrSet['own'][] = $strDefinition; } break; case 'text-decoration': $arrSet['font'] = 1; switch ($arrChunks[1]) { case 'underline': $arrSet['fontstyle'][] = 'underline'; break; case 'none': $arrSet['fontstyle'][] = 'notUnderlined'; break; case 'overline': case 'line-through': $arrSet['fontstyle'][] = $arrChunks[1]; break; } break; case 'font-variant': $arrSet['font'] = 1; if ($arrChunks[1] == 'small-caps') { $arrSet['fontstyle'][] = 'small-caps'; } else { $arrSet['own'][] = $strDefinition; } break; case 'color': if (!preg_match('/^#[a-f0-9]+$/i', $arrChunks[1])) { $arrSet['own'][] = $strDefinition; } else { $arrSet['font'] = 1; $arrSet['fontcolor'] = str_replace('#', '', $arrChunks[1]); } break; case 'line-height': $arrSet['font'] = 1; $arrSet['lineheight'] = array ( 'value' => preg_replace('/[^0-9\.-]+/', '', $arrChunks[1]), 'unit' => preg_replace('/[^ceimnptx%]/', '', $arrChunks[1]) ); break; case 'text-transform': $arrSet['font'] = 1; $arrSet['texttransform'] = $arrChunks[1]; break; case 'text-indent': case 'letter-spacing': case 'word-spacing': $strName = str_replace('-', '', $strKey); $arrSet['font'] = 1; $arrSet[$strName] = array ( 'value' => preg_replace('/[^0-9\.-]+/', '', $arrChunks[1]), 'unit' => preg_replace('/[^ceimnptx%]/', '', $arrChunks[1]) ); break; case 'list-style-type': $arrSet['list'] = 1; $arrSet[str_replace('-', '', $strKey)] = $arrChunks[1]; break; case 'list-style-image': $arrSet['list'] = 1; $arrSet['liststyleimage'] = preg_replace('/url\(["\']?([^"\'\)]+)["\']?\)/i', '$1', $arrChunks[1]); break; case 'behavior': if ($arrChunks[1] != 'url(\'assets/'.CSS3PIE.'/css3pie/PIE.htc\')') { $arrSet['own'][] = $strDefinition; } break; default: $blnIsOwn = true; // Allow custom definitions if (isset($GLOBALS['TL_HOOKS']['createDefinition']) && is_array($GLOBALS['TL_HOOKS']['createDefinition'])) { foreach ($GLOBALS['TL_HOOKS']['createDefinition'] as $callback) { $this->import($callback[0]); $arrTemp = $this->$callback[0]->$callback[1]($strKey, $arrChunks[1], $strDefinition, $arrSet); if ($arrTemp && is_array($arrTemp)) { $blnIsOwn = false; $arrSet = array_merge($arrSet, $arrTemp); } } } // Unknown definition if ($blnIsOwn) { $arrSet['own'][] = $strDefinition; } break; } } if (!empty($arrSet['own'])) { $arrSet['own'] = implode(";\n", $arrSet['own']) . ';'; } $this->Database->prepare("INSERT INTO tl_style %s")->set($arrSet)->execute(); } /** * Return an image as data: string * @param string * @param array * @return string|boolean */ protected function generateBase64Image($strImage, $arrParent) { if ($arrParent['embedImages'] > 0 && file_exists(TL_ROOT . '/' . $strImage)) { $objImage = new \File($strImage, true); $strExtension = $objImage->extension; // Fix the jpg mime type if ($strExtension == 'jpg') { $strExtension = 'jpeg'; } // Return the data: string if ($objImage->size <= $arrParent['embedImages']) { return 'data:image/' . $strExtension . ';base64,' . base64_encode($objImage->getContent()); } } return false; } }
gpl-3.0
clockfort/amd-app-sdk-fixes
samples/opencl/cl/app/NBody/NBody.hpp
11305
/* ============================================================ Copyright (c) 2009 Advanced Micro Devices, Inc. All rights reserved. Redistribution and use of this material is permitted under the following conditions: Redistributions must retain the above copyright notice and all terms of this license. In no event shall anyone redistributing or accessing or using this material commence or participate in any arbitration or legal action relating to this material against Advanced Micro Devices, Inc. or any copyright holders or contributors. The foregoing shall survive any expiration or termination of this license or any agreement or access or use related to this material. ANY BREACH OF ANY TERM OF THIS LICENSE SHALL RESULT IN THE IMMEDIATE REVOCATION OF ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL. THIS MATERIAL IS PROVIDED BY ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" IN ITS CURRENT CONDITION AND WITHOUT ANY REPRESENTATIONS, GUARANTEE, OR WARRANTY OF ANY KIND OR IN ANY WAY RELATED TO SUPPORT, INDEMNITY, ERROR FREE OR UNINTERRUPTED OPERA TION, OR THAT IT IS FREE FROM DEFECTS OR VIRUSES. ALL OBLIGATIONS ARE HEREBY DISCLAIMED - WHETHER EXPRESS, IMPLIED, OR STATUTORY - INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, ACCURACY, COMPLETENESS, OPERABILITY, QUALITY OF SERVICE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, REVENUE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED OR BASED ON ANY THEORY OF LIABILITY ARISING IN ANY WAY RELATED TO THIS MATERIAL, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE ENTIRE AND AGGREGATE LIABILITY OF ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS SHALL NOT EXCEED TEN DOLLARS (US $10.00). ANYONE REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL ACCEPTS THIS ALLOCATION OF RISK AND AGREES TO RELEASE ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS FROM ANY AND ALL LIABILITIES, OBLIGATIONS, CLAIMS, OR DEMANDS IN EXCESS OF TEN DOLLARS (US $10.00). THE FOREGOING ARE ESSENTIAL TERMS OF THIS LICENSE AND, IF ANY OF THESE TERMS ARE CONSTRUED AS UNENFORCEABLE, FAIL IN ESSENTIAL PURPOSE, OR BECOME VOID OR DETRIMENTAL TO ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR CONTRIBUTORS FOR ANY REASON, THEN ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL SHALL TERMINATE IMMEDIATELY. MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF THIS LICENSE OR ANY AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL. NOTICE IS HEREBY PROVIDED, AND BY REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL SUCH NOTICE IS ACKNOWLEDGED, THAT THIS MATERIAL MAY BE SUBJECT TO RESTRICTIONS UNDER THE LAWS AND REGULATIONS OF THE UNITED STATES OR OTHER COUNTRIES, WHICH INCLUDE BUT ARE NOT LIMITED TO, U.S. EXPORT CONTROL LAWS SUCH AS THE EXPORT ADMINISTRATION REGULATIONS AND NATIONAL SECURITY CONTROLS AS DEFINED THEREUNDER, AS WELL AS STATE DEPARTMENT CONTROLS UNDER THE U.S. MUNITIONS LIST. THIS MATERIAL MAY NOT BE USED, RELEASED, TRANSFERRED, IMPORTED, EXPORTED AND/OR RE-EXPORTED IN ANY MANNER PROHIBITED UNDER ANY APPLICABLE LAWS, INCLUDING U.S. EXPORT CONTROL LAWS REGARDING SPECIFICALLY DESIGNATED PERSONS, COUNTRIES AND NATIONALS OF COUNTRIES SUBJECT TO NATIONAL SECURITY CONTROLS. MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF ANY LICENSE OR AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL. NOTICE REGARDING THE U.S. GOVERNMENT AND DOD AGENCIES: This material is provided with "RESTRICTED RIGHTS" and/or "LIMITED RIGHTS" as applicable to computer software and technical data, respectively. Use, duplication, distribution or disclosure by the U.S. Government and/or DOD agencies is subject to the full extent of restrictions in all applicable regulations, including those found at FAR52.227 and DFARS252.227 et seq. and any successor regulations thereof. Use of this material by the U.S. Government and/or DOD agencies is acknowledgment of the proprietary rights of any copyright holders and contributors, including those of Advanced Micro Devices, Inc., as well as the provisions of FAR52.227-14 through 23 regarding privately developed and/or commercial computer software. This license forms the entire agreement regarding the subject matter hereof and supersedes all proposals and prior discussions and writings between the parties with respect thereto. This license does not affect any ownership, rights, title, or interest in, or relating to, this material. No terms of this license can be modified or waived, and no breach of this license can be excused, unless done so in a writing signed by all affected parties. Each term of this license is separately enforceable. If any term of this license is determined to be or becomes unenforceable or illegal, such term shall be reformed to the minimum extent necessary in order for this license to remain in effect in accordance with its terms as modified by such reformation. This license shall be governed by and construed in accordance with the laws of the State of Texas without regard to rules on conflicts of law of any state or jurisdiction or the United Nations Convention on the International Sale of Goods. All disputes arising out of this license shall be subject to the jurisdiction of the federal and state courts in Austin, Texas, and all defenses are hereby waived concerning personal jurisdiction and venue of these courts. ============================================================ */ #ifndef NBODY_H_ #define NBODY_H_ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <SDKCommon.hpp> #include <SDKApplication.hpp> #include <SDKCommandArgs.hpp> #include <SDKFile.hpp> #define GROUP_SIZE 256 /** * NBody * Class implements OpenCL NBody sample * Derived from SDKSample base class */ class NBody : public SDKSample { cl_double setupTime; /**< time taken to setup OpenCL resources and building kernel */ cl_double kernelTime; /**< time taken to run kernel and read result back */ cl_float delT; /**< dT (timestep) */ cl_float espSqr; /**< Softening Factor*/ cl_float* initPos; /**< initial position */ cl_float* initVel; /**< initial velocity */ cl_float* vel; /**< Output velocity */ cl_float* refPos; /**< Reference position */ cl_float* refVel; /**< Reference velocity */ cl_context context; /**< CL context */ cl_device_id *devices; /**< CL device list */ cl_mem currPos; /**< Position of partciles */ cl_mem currVel; /**< Velocity of partciles */ cl_mem newPos; /**< Position of partciles */ cl_mem newVel; /**< Velocity of partciles */ cl_command_queue commandQueue; /**< CL command queue */ cl_program program; /**< CL program */ cl_kernel kernel; /**< CL kernel */ size_t groupSize; /**< Work-Group size */ cl_int numParticles; int iterations; bool exchange; /** Exchange current pos/vel with new pos/vel */ streamsdk::SDKDeviceInfo deviceInfo; /**< Structure to store device information*/ streamsdk::KernelWorkGroupInfo kernelInfo; /**< Structure to store kernel related info */ private: float random(float randMax, float randMin); public: bool isFirstLuanch; cl_event glEvent; /** * Constructor * Initialize member variables * @param name name of sample (string) */ explicit NBody(std::string name) : SDKSample(name), setupTime(0), kernelTime(0), delT(0.005f), espSqr(500.0f), initPos(NULL), initVel(NULL), vel(NULL), refPos(NULL), refVel(NULL), devices(NULL), groupSize(GROUP_SIZE), iterations(1), exchange(true), isFirstLuanch(true), glEvent(NULL) { numParticles = 1024; } /** * Constructor * Initialize member variables * @param name name of sample (const char*) */ explicit NBody(const char* name) : SDKSample(name), setupTime(0), kernelTime(0), delT(0.005f), espSqr(500.0f), initPos(NULL), initVel(NULL), vel(NULL), refPos(NULL), refVel(NULL), devices(NULL), groupSize(GROUP_SIZE), iterations(1), exchange(true), isFirstLuanch(true), glEvent(NULL) { numParticles = 1024; } ~NBody(); /** * Allocate and initialize host memory array with random values * @return SDK_SUCCESS on success and SDK_FAILURE on failure */ int setupNBody(); /** * Override from SDKSample, Generate binary image of given kernel * and exit application * @return SDK_SUCCESS on success and SDK_FAILURE on failure */ int genBinaryImage(); /** * OpenCL related initialisations. * Set up Context, Device list, Command Queue, Memory buffers * Build CL kernel program executable * @return SDK_SUCCESS on success and SDK_FAILURE on failure */ int setupCL(); /** * Set values for kernels' arguments * @return SDK_SUCCESS on success and SDK_FAILURE on failure */ int setupCLKernels(); /** * Enqueue calls to the kernels * on to the command queue, wait till end of kernel execution. * Get kernel start and end time if timing is enabled * @return SDK_SUCCESS on success and SDK_FAILURE on failure */ int runCLKernels(); /** * Reference CPU implementation of Binomial Option * for performance comparison */ void nBodyCPUReference(); /** * Override from SDKSample. Print sample stats. */ void printStats(); /** * Override from SDKSample. Initialize * command line parser, add custom options * @return SDK_SUCCESS on success and SDK_FAILURE on failure */ int initialize(); /** * Override from SDKSample, adjust width and height * of execution domain, perform all sample setup * @return SDK_SUCCESS on success and SDK_FAILURE on failure */ int setup(); /** * Override from SDKSample * Run OpenCL NBody * @return SDK_SUCCESS on success and SDK_FAILURE on failure */ int run(); /** * Override from SDKSample * Cleanup memory allocations * @return SDK_SUCCESS on success and SDK_FAILURE on failure */ int cleanup(); /** * Override from SDKSample * Verify against reference implementation * @return SDK_SUCCESS on success and SDK_FAILURE on failure */ int verifyResults(); }; #endif // NBODY_H_
gpl-3.0
pmediano/jidt
java/unittests/infodynamics/measures/discrete/SInfoTester.java
2961
/* * Java Information Dynamics Toolkit (JIDT) * Copyright (C) 2012, Joseph T. Lizier * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package infodynamics.measures.discrete; import infodynamics.utils.RandomGenerator; import junit.framework.TestCase; public class SInfoTester extends TestCase { public void testIndependent() throws Exception { SInfoCalculatorDiscrete sCalc = new SInfoCalculatorDiscrete(2, 3); double sinfo = sCalc.compute(new int[][] {{0,0,0},{0,0,1},{0,1,0},{0,1,1},{1,0,0},{1,0,1},{1,1,0},{1,1,1}}); assertEquals(0.0, sinfo, 0.000001); } public void testXor() throws Exception { // 3 variables SInfoCalculatorDiscrete sCalc = new SInfoCalculatorDiscrete(2, 3); double sinfo = sCalc.compute(new int[][] {{0,0,1},{0,1,0},{1,0,0},{1,1,1}}); assertEquals(3.0, sinfo, 0.000001); // 4 variables sCalc = new SInfoCalculatorDiscrete(2, 4); sinfo = sCalc.compute(new int[][] {{0,0,0,1},{0,0,1,0},{0,1,0,0},{1,0,0,0},{1,1,1,0},{1,1,0,1},{1,0,1,1},{0,1,1,1}}); assertEquals(4.0, sinfo, 0.000001); } public void testCopy() throws Exception { // 3 variables SInfoCalculatorDiscrete sCalc = new SInfoCalculatorDiscrete(2, 3); double sinfo = sCalc.compute(new int[][] {{0,0,0},{1,1,1}}); assertEquals(3.0, sinfo, 0.000001); // 4 variables sCalc = new SInfoCalculatorDiscrete(2, 4); sinfo = sCalc.compute(new int[][] {{0,0,0,0},{1,1,1,1}}); assertEquals(4.0, sinfo, 0.000001); } public void testCompareTCAndDTC() throws Exception { // Generate random data and check that it matches the explicit computation // using TC and DTC calculators RandomGenerator rg = new RandomGenerator(); int[][] data = rg.generateRandomInts(10, 4, 2); // O-info calculator SInfoCalculatorDiscrete sCalc = new SInfoCalculatorDiscrete(2, 4); double sinfo_direct = sCalc.compute(data); // TC and DTC calculators MultiInformationCalculatorDiscrete tcCalc = new MultiInformationCalculatorDiscrete(2, 4); DualTotalCorrelationCalculatorDiscrete dtcCalc = new DualTotalCorrelationCalculatorDiscrete(2, 4); tcCalc.initialise(); tcCalc.addObservations(data); double sinfo_test = tcCalc.computeAverageLocalOfObservations() + dtcCalc.compute(data); assertEquals(sinfo_direct, sinfo_test, 0.000001); } }
gpl-3.0
osen/mutiny
src/mutiny/Font.cpp
1862
#include "Font.h" #include "Texture2d.h" #include "CharacterInfo.h" #include "Vector2.h" #include "Debug.h" #include "Application.h" #include "Resources.h" #include <string> #include <fstream> #include <iostream> namespace mutiny { namespace engine { ref<Font> Font::load(std::string path) { ref<Font> font = new Font(); //Debug::log("Loading font from '" + path + "'"); //font->texture = Resources::load<Texture2d>(path); font->texture.reset(Texture2d::load(path).try_get()); if(font->texture.get() == NULL) { return NULL; } std::vector<std::string> characters; int maxChars = 0; std::string chars; for(int i = 32; i < 127; i++) { chars += (char)i; } maxChars = chars.length(); characters.push_back(chars); //Debug::log(chars); Vector2 charSize((float)font->texture->getWidth() / (float)maxChars, (float)font->texture->getHeight() / (float)characters.size()); for(int y = 0; y < characters.size(); y++) { for(int x = 0; x < characters[y].length(); x++) { CharacterInfo info = {}; info.index = characters[y][x]; info.vert = Rect(0, 0, charSize.x, charSize.y); info.uv.x = ((float)x * charSize.x) / (float)font->texture->getWidth(); info.uv.y = ((float)y * charSize.y) / (float)font->texture->getHeight(); info.uv.width = ((float)x * charSize.x + charSize.x) / (float)font->texture->getWidth(); info.uv.height = ((float)y * charSize.y + charSize.y) / (float)font->texture->getHeight(); font->characterInfo.push_back(info); } } return font; } bool Font::getCharacterInfo(char character, CharacterInfo& characterInfo) { for(int i = 0; i < this->characterInfo.size(); i++) { if(this->characterInfo.at(i).index == character) { characterInfo = this->characterInfo.at(i); return true; } } return false; } } }
gpl-3.0
Malvineous/libgamecommon
include/camoto/stream_filtered.hpp
9148
/** * @file camoto/stream_filtered.hpp * @brief Pass read/write operations through a filter to modify the data. * * Copyright (C) 2010-2016 Adam Nielsen <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _CAMOTO_STREAM_FILTERED_HPP_ #define _CAMOTO_STREAM_FILTERED_HPP_ #include <functional> #include <memory> #include <camoto/filter.hpp> #include <camoto/stream_string.hpp> namespace camoto { namespace stream { class output_filtered; /// Set real-size function callback (to set the prefiltered/native size) /** * This function is called with an integer parameter when a stream::filtered * is flushed, to notify the callee of how much data was passed to the filter. * This can be different to the amount of data that was written out to the * underlying stream, such as in the case of a filter which performs * compression. In this case, the number of bytes that end up in the * destination stream will be the compressed size of the data, and this callback * will be supplied with the number of bytes passed to the filter (effectively * the decompressed size of the data, in this case.) * * This is useful mainly for game archives, which often store both the * compressed and decompressed sizes of the files they contain. * * Since no other data can be passed with this function call, usually * std::bind is used to create a "wrapping" around some other function with * more parameters. * * The function signature is: * @code * void fnTruncate(stream::output_filtered* filt, stream::len new_length); * @endcode * * The filt parameter is the stream::filtered itself. new_length is the new * "real" size, as opposed to the stored size which is obviously the number of * bytes actually written to the stream. * * This example uses std::bind to package up a call to the Linux * truncate() function (which requires both a filename and size) such that * the filename is supplied in advance and not required when the \e fn_truncate * call is made. * * @code * fn_truncate fnTruncate = std::bind<void>(truncate, "graphics.dat", _2); * // later... * fnTruncate(out, 123); // calls truncate("graphics.dat", 123) * @endcode * * This callback is used in cases where both a file's compressed and * decompressed size are stored. Here the callback will be notified with the * prefiltered size during the flush() call, with the postfiltered size * being the amount of data that was actually written to the stream. * * The callback should throw stream::write_error if the operation did not * succeed. */ typedef std::function<void(stream::output_filtered*, stream::len)> fn_notify_prefiltered_size; /// Read-only stream applying a filter to another read-only stream. class CAMOTO_GAMECOMMON_API input_filtered: virtual public input_string { public: /// Apply a filter to the given stream. /** * As data is read from this stream (the input_filtered instance), data is * in turn read from \e parent and passed through \e read_filter before * being returned to the caller. * * @param parent * Parent stream supplying the data. * * @param read_filter * Filter to process data. */ input_filtered(std::shared_ptr<input> parent, std::shared_ptr<filter> read_filter); virtual stream::len try_read(uint8_t *buffer, stream::len len); virtual void seekg(stream::delta off, seek_from from); virtual stream::pos tellg() const; virtual stream::len size() const; /// A partial write is about to occur, ensure the unfiltered data is present. /** * When opening a read/write stream, the data is not populated * automatically to avoid unnecessary computation in case it is going to be * overwritten. * * This function is overridden in a read/write stream so that the original * data is populated before any read or write occurs. */ virtual void populate() const; /// Non-const version of populate() that actually does the work. void realPopulate(); /// Get the parent stream. std::shared_ptr<input> get_stream(); protected: /// Parent stream for reading std::shared_ptr<input> in_parent; /// Filter to pass data through std::shared_ptr<filter> read_filter; /// Has the input data been run through the filter yet? bool populated; }; /// Write-only stream applying a filter to another write-only stream. class CAMOTO_GAMECOMMON_API output_filtered: virtual public output_string { public: /// Apply a filter to the given stream. /** * As data is written to this stream (the output_filtered instance), the * data is first passed through \e write_filter before being written to * \e parent. * * @param parent * Parent stream to write the processed data to. * * @param write_filter * Filter to process data. * * @param resize * Notification function called when the stream is resized. This function * doesn't have to do anything (and can be NULL) but it is used in cases * where a game archive stores both a file's compressed and decompressed * size. Here the callback will be notified of the decompressed size * during the flush() call, while parent->truncate() will be called with * the compressed size. */ output_filtered(std::shared_ptr<output> parent, std::shared_ptr<filter> write_filter, fn_notify_prefiltered_size resize); virtual ~output_filtered(); virtual stream::len try_write(const uint8_t *buffer, stream::len len); virtual void seekp(stream::delta off, seek_from from); virtual stream::pos tellp() const; virtual void flush(); /// A partial write is about to occur, ensure the unfiltered data is present. /** * When opening a read/write stream, the data is not populated * automatically to avoid unnecessary computation in case it is going to be * overwritten. * * This function is overridden in a read/write stream so that the original * data is populated before any read or write occurs. */ virtual void populate() const; /// Get the parent stream. std::shared_ptr<output> get_stream(); protected: /// Parent stream for writing std::shared_ptr<output> out_parent; /// Filter to pass data through std::shared_ptr<filter> write_filter; /// Size-change notification callback fn_notify_prefiltered_size fn_set_orig_size; /// true once filter has run once (set to false again on write) bool done_filter; /// true once data has been written, until flush() has been called bool need_flush; }; /// Read/write stream applying a filter to another read/write stream. class CAMOTO_GAMECOMMON_API filtered: virtual public inout, virtual public input_filtered, virtual public output_filtered { public: /// Apply a filter to the given stream. /** * As data is read from this stream (the filtered instance), data is * in turn read from \e parent and passed through \e read_filter before * being returned to the caller. Likewise any data written is passed * through \e write_filter before being written to \e parent. * * Internally this is implemented by reading the entire contents of * \e parent in the constructor, passing it through \e read_filter and * storing it in memory. Data is then read from and written to this * memory buffer. On flush(), the data is passed through \e write_filter * and written back to the parent stream. * * @param parent * Parent stream supplying the data. * * @param read_filter * Filter to process data. * * @param write_filter * Filter to process data. * * @param set_orig_size * Notification function called when the stream is flushed. This function * doesn't have to do anything (and can be NULL) but it is used in cases * where a game archive stores both a file's compressed and decompressed * size. Here the callback will be notified of the decompressed size * during the flush() call (i.e. the number of bytes written in to the * filter, as opposed to the number of bytes which came out of it, which * will be fewer in the case of a filter that performs compression.) */ filtered(std::shared_ptr<inout> parent, std::shared_ptr<filter> read_filter, std::shared_ptr<filter> write_filter, fn_notify_prefiltered_size set_orig_size); virtual void truncate(stream::len size); virtual void populate() const; /// Get the parent stream. std::shared_ptr<inout> get_stream(); }; } // namespace stream } // namespace camoto #endif // _CAMOTO_STREAM_FILTERED_HPP_
gpl-3.0
moose3d/moose
src/Moose/Graphics/MooseModelHelper.cpp
5574
/******************************************************************************/ * Moose3D is a game development framework. * * Copyright 2006-2013 Anssi Gröhn / entity at iki dot fi. * * This file is part of Moose3D. * * Moose3D 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. * * Moose3D 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 Moose3D. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ #include "MooseModelHelper.h" #include "MooseMilkshapeLoader.h" #include "MooseObjLoader.h" #include "MooseDefaultEntities.h" #include <sstream> #include <string> #include <cassert> #include <aiPostProcess.h> #include <stdexcept> #include <MooseVertexDescriptor.h> #include <MooseIndexArray.h> #include <MooseExceptions.h> //////////////////////////////////////////////////////////////////////////////// namespace prefix = Moose::Data; using namespace std; using namespace Moose::Graphics; using namespace Moose::Data; using namespace Moose::Spatial; using namespace Moose::Exceptions; ///////////////////////////////////////////////////////////////// const COpenAssetImportLoader * Moose::Data::CModelHelper::GetModelLoader() { return m_pLoader; } ///////////////////////////////////////////////////////////////// void Moose::Data::CModelHelper::Load( const char *szFilename ) { if ( m_pLoader ) delete m_pLoader; m_pLoader = new COpenAssetImportLoader(); m_pLoader->Load(szFilename); } //////////////////////////////////////////////////////////////////////////////// Moose::Data::MeshNameList Moose::Data::CModelHelper::GetAvailableMeshes() const { // If we have stuff, then return name list (vector) if ( m_pLoader ) { return m_pLoader->GetMeshes(); } else return MeshNameList(); // otherwise return empty list } ///////////////////////////////////////////////////////////////// Moose::Graphics::CModel * Moose::Data::CModelHelper::CreateModel( int iFlags, const char *szGroupName, bool bInterleaved ) { CModel *pModel = new CModel(); m_pLoader->SelectMesh(szGroupName); /* Resource allocation is one-way, either everything succeeds or nothing goes.*/ if ( bInterleaved ) { CVertexDescriptor *pInterleaved = m_pLoader->GetInterleavedArray(); // manage array int iRetval = g_VertexMgr->Create( pInterleaved, g_UniqueName, pModel->GetVertexHandle() ); if ( iRetval != 0 ) { throw CMooseRuntimeError("Cannot create vertex array"); } } else { // Create vertex handle int iRetval = g_VertexMgr->Create( m_pLoader->GetVertexArray(), g_UniqueName, pModel->GetVertexHandle() ); if ( iRetval != 0 ) { throw CMooseRuntimeError("Cannot create vertex array"); } /* load vertex normals */ if ( iFlags & OPT_VERTEX_NORMALS && m_pLoader->HasNormalArray() ) { /* Create normal handle */ iRetval = g_VertexMgr->Create(m_pLoader->GetNormalArray(), g_UniqueName, pModel->GetNormalHandle()); if ( iRetval != 0 ) { throw CMooseRuntimeError("Cannot create normal array"); } } /* load texture coordinates */ if ( iFlags & OPT_VERTEX_TEXCOORDS && m_pLoader->HasTexCoordArray()) { /* Create texcoord handle */ iRetval = g_VertexMgr->Create(m_pLoader->GetTexCoordArray(), g_UniqueName, pModel->GetTextureCoordinateHandle(0)); if ( iRetval != 0 ) { throw CMooseRuntimeError("Cannot create texture coordinate array"); } } /* load colors */ if ( iFlags & OPT_VERTEX_COLORS ) { } } CIndexArray *pArray = m_pLoader->GetIndexArray(); assert( pArray->GetNumIndices() > 0 ); int iRetval = g_IndexMgr->Create( pArray, g_UniqueName, pModel->GetIndices()); if ( iRetval != 0 ) { throw CMooseRuntimeError("Cannot create index array"); } return pModel; } ///////////////////////////////////////////////////////////////// CIndexArray * Moose::Data::CModelHelper::CreateIndices( const char *szGroupName, const char *szResourceName ) { // Sanity check, no data, no indices. if ( !m_pLoader ) return NULL; m_pLoader->SelectMesh(szGroupName); CIndexArray *pIndices = NULL; pIndices = m_pLoader->GetIndexArray(); // Create resource either by unique name or resource name int iRetval; if ( szResourceName == NULL ) { iRetval = g_IndexMgr->Create( pIndices, g_UniqueName); } else { iRetval = g_IndexMgr->Create( pIndices, szResourceName); } if ( iRetval != 0 ) { throw CMooseRuntimeError("Cannot create index array"); } return pIndices; } ///////////////////////////////////////////////////////////////// void Moose::Data::CModelHelper::Clear() { delete m_pLoader; m_pLoader = NULL; } /////////////////////////////////////////////////////////////////
gpl-3.0
Samsemilio/OpenCommonsGame
BackEnd/OpenCommonsGame.Collections.MongoDb/ObjectTypeCollection.cs
968
using MongoDB.Bson; using MongoDB.Driver; using OpenCommonsGame.Editor; using OpenCommonsGame.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OpenCommonsGame.Collections.MongoDb { public class ObjectTypeCollection : IObjectTypeCollection { public IResolver Resolver { get; set; } public ObjectTypeDictionary ConnectedDictionary { get; protected set; } public ObjectTypeCollection(IResolver resolver) { if (resolver == null) throw new ArgumentNullException("resolver"); Resolver = resolver; ConnectedDictionary = new ObjectTypeDictionary(resolver); } public IDictionary<string, IObjectType> ObjectTypes { get { return ConnectedDictionary; } } } }
gpl-3.0
Arunkrishna008/Yeng-App-Android
app/src/main/java/hsm/yeng/rules/Rules1.java
2068
package hsm.yeng.rules; import android.content.res.AssetManager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebSettings; import android.webkit.WebView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import hsm.yeng.R; /** * */ public class Rules1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getActivity().setTitle("News and Update"); Log.e("oncreate view..........", "News"); // Inflate the layout for this fragment View v=inflater.inflate(R.layout.fragment_btech, container, false); /* rules.getSettings().setJavaScriptEnabled(true); rules.loadUrl("file:///android_asset/rules.html"); rules.setVerticalScrollBarEnabled(true);*/ AssetManager mgr = getContext().getAssets(); try { InputStream in = mgr.open("rules",AssetManager.ACCESS_BUFFER); String sHTML = streamToString(in); in.close(); //display this html in the browser } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return v; } private String streamToString(InputStream in) throws IOException { if(in == null) { return ""; } Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { } return writer.toString(); } }
gpl-3.0
jonathandlo/deep-space-dive
Deep Space Dive/Program/Levels/LevelMenu.cs
1540
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SharpDX; using SharpDX.Direct2D1; using SharpDX.Mathematics.Interop; namespace DSD { public class LevelMenu : GameLevel { protected Title MainTitle; protected Button NewGameButton; protected Button OptionsButton; protected Button QuitButton; public override void Load() { MainTitle = new Title("Deep Space Dive", 70, 70); NewGameButton = new Button("New Game", 30, Constants.Height - 300, 400, 70, false); OptionsButton = new Button("Options", 30, Constants.Height - 200, 400, 70, false); QuitButton = new Button("Quit", 30, Constants.Height - 100, 400, 70, false); } public override void Unload() { } public override void Update(InputStates pInputStates, long pFrames) { MainTitle.Update(pInputStates, pFrames); NewGameButton.Update(pInputStates, pFrames); OptionsButton.Update(pInputStates, pFrames); QuitButton.Update(pInputStates, pFrames); if (NewGameButton.LoopResultStates.Activate) GameController.SwitchLevel(new LevelOne()); if (QuitButton.LoopResultStates.Activate || pInputStates.Quit) GraphicsWindow.Instance.ShouldQuit = true; } public override void Render(RenderTarget pRender, float pPercent) { pRender.Clear(new RawColor4(0.9f, 0.85f, 0.75f, 1.0f)); MainTitle.Render(pRender, pPercent); NewGameButton.Render(pRender, pPercent); OptionsButton.Render(pRender, pPercent); QuitButton.Render(pRender, pPercent); } } }
gpl-3.0
MyCoRe-Org/mycore
mycore-viewer/src/main/typescript/modules/base/widgets/toolbar/model/ToolbarText.ts
1283
/* * This file is part of *** M y C o R e *** * See http://www.mycore.de/ for details. * * MyCoRe 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. * * MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>. */ /// <reference path="../../../Utils.ts" /> /// <reference path="ToolbarComponent.ts" /> namespace mycore.viewer.widgets.toolbar { export class ToolbarText extends ToolbarComponent { constructor(id: string, text: string) { super(id); this.addProperty(new ViewerProperty<string>(this, "text", text)); } public get text(): string { return this.getProperty("text").value; } public set text(text: string) { this.getProperty("text").value = text; } } }
gpl-3.0
AlxMedia/kontrast
search.php
1180
<?php get_header(); ?> <div class="content"> <?php get_template_part('inc/page-title'); ?> <div class="pad group"> <div class="notebox"> <?php esc_html_e('For the term','kontrast'); ?> "<span><?php echo get_search_query(); ?></span>". <?php if ( !have_posts() ): ?> <?php esc_html_e('Please try another search:','kontrast'); ?> <?php endif; ?> <div class="search-again"> <?php get_search_form(); ?> </div> </div> <?php if ( have_posts() ) : ?> <?php if ( get_theme_mod('blog-standard','off') == 'on' ): ?> <?php while ( have_posts() ): the_post(); ?> <?php get_template_part('content-standard'); ?> <?php endwhile; ?> <?php else: ?> <div class="post-list group"> <?php $i = 1; echo '<div class="post-row">'; while ( have_posts() ): the_post(); ?> <?php get_template_part('content'); ?> <?php if($i % 2 == 0) { echo '</div><div class="post-row">'; } $i++; endwhile; echo '</div>'; ?> </div><!--/.post-list--> <?php endif; ?> <?php get_template_part('inc/pagination'); ?> <?php endif; ?> </div><!--/.pad--> </div><!--/.content--> <?php get_sidebar(); ?> <?php get_footer(); ?>
gpl-3.0
aohrem/Aeolus
class/datavalidation.class.php
15400
<?php class DataValidation { // default values for sensitivity of the outlier detection, window size and factor private $defaultSensitivity = 2; private $windowSizes = array('6h' => 12, '24h' => 8, '48h' => 8, '1w' => 24, '1m' => 7, '3m' => 7); private $factor = array(1.0, 5.0, 1.5, 1.0); private $validation = true; // containers for the data and trans array, used sensitivity, window size and for the sensor types private $dataArray; private $transArray; private $sensitivity; private $windowSize; private $sensors; public function __construct($dataArray, $sensors, $sensitivity, $time) { // data array which shall be validated $this->dataArray = $dataArray; // sensor types used to iterate the data array $this->sensors = $sensors; // window size depends on the given time frame, because every time frame uses different data frequencies $this->windowSize = $this->windowSizes[$time]; // initialize sensitivity if there was just the default value given if ( $sensitivity == 'default' ) { $this->sensitivity = $this->defaultSensitivity; } else { $this->sensitivity = $sensitivity; } // cancel data validation if the amount of data values is too small if ( sizeof($this->dataArray) < $this->windowSize ) { $this->validation = false; } } // returns the default sensitivity public function getDefaultSensitivity() { return $this->defaultSensitivity; } // function calculates outliers in the data array and returns an array with the estimated outliers // based on "Outliers and robust methods" slides of Katharina Henneböhl, ifgi public function getOutliers() { if ( $this->validation ) { // apply the running medians algorithm and save returned array $ytmed = $this->runmed($this->dataArray, $this->windowSize, $this->sensors); // k is half of the window size $k = floor($this->windowSize / 2); // n is the size of the data array $n = sizeof($this->dataArray); // calculate the trans array $i = 0; foreach ( $this->dataArray as $key => $val ) { $this->transArray[$i] = $key; $i++; } foreach ( $this->sensors as $sensor ) { // calculate trans array by iterating the data array and assign an index to each value $i = 0; foreach ( $this->dataArray as $key => $val ) { $this->transArray[$i] = $key; // if there is no value, it is classified as an outlier if ( ! isset($val[$sensor]) ) { $outliers[$sensor][$key] = true; } // fill in outlier array with default (false) values else { $outliers[$sensor][$key] = false; } $i++; } // get the array window with length of the given window size at the start of the array $frontWindow = $this->getArrayWindow($this->dataArray, 0, $this->windowSize, $sensor); // calculate the IQR ... $frontInterQuartileRange = abs($this->quantile($frontWindow, 0.75) - $this->quantile($frontWindow, 0.25)); // ... and the median of that window $frontMedian = $this->median($this->dataArray, $sensor, 0, $this->windowSize); // check first $windowSize values for outliers for ( $j = 0; $j < $this->windowSize; $j++ ) { $outliers = $this->checkValue($j, $frontMedian, $frontInterQuartileRange, $outliers, $sensor); } $index = $k; while ( $index < ( $n - $k ) ) { // get the array window with length of the given window size $window = $this->getArrayWindow($this->dataArray, $index - $k, $index + $k, $sensor); // calculate inter quartile range of current window (absolute value of the difference between 75% and 25% quantile) $interQuartileRange = abs($this->quantile($window, 0.75) - $this->quantile($window, 0.25)); $median = $ytmed[$this->transArray[$index - 1]][$sensor]; // if current value is less than (median - factor * inter quartile range) or greater than (median + factor * inter quartile range), it is classified as an outlier $outliers = $this->checkValue($index - 1, $median, $interQuartileRange, $outliers, $sensor); $index++; } // get the array window with length of the given window size at the start of the array $backStart = sizeof($this->dataArray) - $this->windowSize; $backWindow = $this->getArrayWindow($this->dataArray, $backStart, sizeof($this->dataArray), $sensor); // calculate the IQR ... $backInterQuartileRange = abs($this->quantile($backWindow, 0.75) - $this->quantile($backWindow, 0.25)); // ... and the median of that window $backMedian = $this->median($this->dataArray, $sensor, $backStart, sizeof($this->dataArray)); // check last $windowSize values for outliers for ( $j = $backStart; $j < sizeof($this->dataArray); $j++ ) { $outliers = $this->checkValue($j, $backMedian, $backInterQuartileRange, $outliers, $sensor); } } return $outliers; } return false; } // checks if outliers in the data array were found public function containsOutliers($outliers) { if ( $this->validation ) { // iterate outlier array and return true if there is at least one outlier foreach ( $outliers as $sensor => $val ) { foreach ( $outliers[$sensor] as $time => $outlier ) { if ( $outlier ) { return true; } } } } // if there was no outlier in the array, return false return false; } // returns data array with linear interpolated outliers public function interpolateOutliers($outliers) { if ( $this->validation ) { // iterate sensors foreach ( $outliers as $sensor => $val ) { // i is the index of the current outlier dataset, used by the trans array $i = 0; foreach ( $outliers[$sensor] as $time => $outlier ) { if ( $outlier ) { // get next predecessor which is not an outlier $pred = 1; while ( isset($this->transArray[$i - $pred]) && (( floatval($this->dataArray[$this->transArray[$i - $pred]][$sensor]) == 0.0 ) || ( isset($outliers[$sensor][$this->transArray[$i - $pred]]) && $outliers[$sensor][$this->transArray[$i - $pred]] ) ) ) { $pred++; } // get next successor which is not an outlier $succ = 1; while ( isset($this->transArray[$i + $succ]) && (( floatval($this->dataArray[$this->transArray[$i + $succ]][$sensor]) == 0.0 ) || ( isset($outliers[$sensor][$this->transArray[$i + $succ]]) && $outliers[$sensor][$this->transArray[$i + $succ]] ) ) ) { $succ++; } // if a predecessor and a successor were found: linear interpolation (mean) if ( isset($this->transArray[$i - $pred]) && isset($this->transArray[$i + $succ]) ) { $interpolatedValue = round(($this->dataArray[$this->transArray[$i - $pred]][$sensor] + $this->dataArray[$this->transArray[$i + $succ]][$sensor] ) / 2, 3); } // if just a successor was found: take successor's value as interpolated value else if ( ! isset($this->transArray[$i - $pred]) && isset($this->transArray[$i + $succ]) ) { $interpolatedValue = $this->dataArray[$this->transArray[$i + $succ]][$sensor]; } // if just a predecessor was found: take predecessors's value as interpolated value else if ( isset($this->transArray[$i - $pred]) && ! isset($this->transArray[$i + $succ]) ) { $interpolatedValue = $this->dataArray[$this->transArray[$i - $pred]][$sensor]; } // save interpolated value in the data array $this->dataArray[$time][$sensor] = $interpolatedValue; } $i++; } } } return $this->dataArray; } // if value at $index is less than (median - factor * inter quartile range) or greater than (median + factor * inter quartile range), it is classified as an outlier private function checkValue($index, $median, $iqr, $outliers, $sensor) { if ( $iqr == 0 ) { $iqr++; } if ( floatval($this->dataArray[$this->transArray[$index]][$sensor]) != 0.0 ) { if ( $this->dataArray[$this->transArray[$index]][$sensor] < ($median - $this->factor[$this->sensitivity] * $iqr) || $this->dataArray[$this->transArray[$index]][$sensor] > ($median + $this->factor[$this->sensitivity] * $iqr) ) { $outliers[$sensor][$this->transArray[$index]] = true; } } else { $outliers[$sensor][$this->transArray[$index]] = false; } return $outliers; } // calculates the median of $dataArray on column $sensor from index $start to index $end private function median($dataArray, $sensor, $start, $end) { $sensorArray = array(); $i = 0; $j = 0; // iterate values of the data array foreach ( $dataArray as $val ) { // check if value is within the given interval if ( $j >= $start - 1 && $j < $end ) { // if there is a value for the given sensor, save the value in another array if ( floatval($val[$sensor]) != 0.0 ) { $sensorArray[$i] = $val[$sensor]; $i++; } else { $end++; } } $j++; } // sort the sensor array sort($sensorArray); // median is mid value in this array $median = 0; if ( isset($sensorArray[floor(sizeof($sensorArray) / 2)]) ) { $median = $sensorArray[floor(sizeof($sensorArray) / 2)]; } return $median; } // running medians function, smoothes the data array private function runmed($dataArray, $windowSize, $sensors) { $runmedArray = array(); // i is the index of the dataset, used by the trans array foreach ( $sensors as $sensor ) { $i = 0; // apply the running median algorithm as described in R library documentation for each value of the data array // running median in R library documentation: http://rss.acs.unt.edu/Rdoc/library/stats/html/runmed.html foreach ( $dataArray as $key => $val ) { $start = $i - floor($windowSize / 2); $end = $i + floor($windowSize / 2); $runmedArray[$key][$sensor] = $this->median($dataArray, $sensor, $start, $end); $i++; } } // return smoothed data array return $runmedArray; } // function replicates an array of $size with $value for each element private function rep($value, $size) { $array = array(); for ( $i = 0; $i < $size; $i++ ) { $array[$i] = $value; } return $array; } // function gives back the subarray from $start to $end, but just for $sensor private function getArrayWindow($array, $start, $end, $sensor) { $arrayWindow = array(); // i is the index of the new array where the next value of the subarray will be saved // j is the index of the current value of the array $i = 0; $j = 0; foreach ( $array as $key => $val ) { // check if value is within the given interval if ( $j >= $start - 1 && $j < $end ) { // if there is a value, save it to our new subarray if ( floatval($val[$sensor]) != 0.0 ) { $arrayWindow[$i] = $val[$sensor]; $i++; } else { $end++; } } $j++; } return $arrayWindow; } // returns the $p-quantile of $array // applied algorithm (like in R library: type 7): http://stat.ethz.ch/R-manual/R-patched/library/stats/html/quantile.html private function quantile($array, $p) { $n = sizeof($array); sort($array); $np = $n * $p; $m = 1 - $p; $j = floor($np + $m); $g = $np + $m - $j; if ( isset($array[$j - 1]) && isset($array[$j]) ) { return (1 - $g) * $array[$j - 1] + $g * $array[$j]; } else { return false; } } } ?>
gpl-3.0